<?php

namespace App\Http\Controllers\Api\DistributorsManages;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\DistributorsManages\VerifyDamagedReportsController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
//渠道残损申报
class DamagedReportsController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $search_data = $request->all();
        $list_data = DB::table('damaged_declare_wd')
                        ->where('dadw_cid', $user_info->adm_cid)
                        ->where('dadw_shop_id', $user_info->adm_shop_id)
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['dadw_damaged_number'])) {
                                $query->where('dadw_damaged_number', $search_data['dadw_damaged_number']);
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['dadw_state'])) {
                                $query->where('dadw_state', $search_data['dadw_state']);
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['state'])) {
                                $query->where('dadw_state', $search_data['state']);
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['dadw_plan'])) {
                                $query->where('dadw_plan', $search_data['dadw_plan']);
                            }
                        })
                        ->where(function($query) use($search_data) {
                        //如果选择开始时间并且选择结束时间
                            if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                            $query->whereBetween('dadw_create_time', [$search_data['start_time'], $search_data['end_time'].' 23:59:59']);
                            } else{
                                // 如果选择开始时间
                                if (!empty($search_data['start_time'])) {
                                    $query->where('dadw_create_time', '>=',$search_data['start_time']);
                                } else{
                                    // 如果选择结束时间
                                    if (!empty($search_data['end_time'])) {
                                        $query->where('dadw_create_time', '<=',$search_data['end_time'].' 23:59:59');
                                    }
                                }
                            }
                        }) //添加时间
                        ->select('dadw_damaged_amount', 'dadw_damaged_number', 'dadw_true_amount', 'dadw_total_money', 'dadw_remark','dadw_plan', 'dadw_state', 'dadw_create_time','dadw_id')
                        ->orderBy('dadw_id', 'desc')
                        ->paginate($this->show_count);
        $state_count = DB::table('damaged_declare_wd')
            ->where('dadw_cid', $user_info->adm_cid)
            ->where('dadw_shop_id', $user_info->adm_shop_id)
            ->select(DB::raw('count(*) as count, dadw_state'))
            ->groupBy('dadw_state')
            ->get();

        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;       //一页显示多少个
        $data_info['data'] = $list_data->items();                //返回数据
        $data_info['state_count'] = $state_count;
        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if($list_data) {
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$data_info,'list_button'=>$list_button]);
        }else{
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        } 
    }

    //新增残损单
    public function add(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyDamagedReportsController;
        $error_message = $verify_data->addValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $img = []; 
        foreach ($request['img'] as $key => $value) {
            $img[] = uploadBase64Img($value);
        }
        $img = implode(',',$img);
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        DB::beginTransaction();
        $damaged['dadw_cid'] = $user_info->adm_cid;//公司id
        $damaged['dadw_shop_id'] = $user_info->adm_shop_id;//配送商id
        $damaged['dadw_damaged_amount'] = 1;//残损数量

        $odd = 'CS'.date('Ymd').rand(10000,99990);
        $damaged['dadw_damaged_number'] = $odd;//残损单号
        $damaged['dadw_belongs_bill'] = $request['belongs_bill'];//所属配送账单号
        $damaged['dadw_state'] = 1;//1待审核2已撤销3未完成4已完成
        $dadw_id = DB::table('damaged_declare_wd')->insertGetid($damaged);
        $ddgw['ddgw_dadw_id'] = $dadw_id;
        $ddgw['ddgw_goo_img'] = $img;//商品图片
        $ddgw['ddgw_storage_code'] = $request['ddgw_storage_code'] ?:'';//电瓶码号
        $res = DB::table('damaged_declare_goods_wd')->insertGetid($ddgw);

        //供应链残损处理表
        $dare['dare_shop_id'] = $user_info->adm_shop_id;//门店id
        $dare['dare_cid'] = $user_info->adm_cid;//所属企业/品牌方id
        $dare['dare_number'] = $odd;//门店id
        $dare['dare_type'] = 1;//1渠道处理  2门店处理
        $dare['dare_state'] = 1;//状态1待审核2未完成3已完成4已驳回
        $dare['dare_spoiled_quantity'] = 1;//残损数量
        $dare['dare_belongs_bill'] = $request['belongs_bill'];//所属配送账单号
        $dare['dare_replenishment_bills_number'] = $request['belongs_bill'];//所属配送账单号
        $dare_id = DB::connection('mysql_scm')
                ->table('damage_record')
                ->insertGetid($dare);
        //残损处理商品表
        $dago['dago_dare_id'] = $dare_id;
        $dago['dago_goo_img'] = $img;
        $dago['dago_storage_code'] = $request['ddgw_storage_code'] ?:'';//电瓶码号

        $dago_res = DB::connection('mysql_scm')
                ->table('damage_goods')
                ->insert($dago);
        if ($res && $dadw_id && $dago_res && $dare_id) {
            Common::addLog($user_info, getRealIp($request), '残损申报', '残损申报', '添加残损单:'.$odd);
            DB::commit();
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'申报成功']);
        } else{
            DB::rollBack();
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'申报失败']);
        }
    }

    //残损单备注
    public function remark(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyDamagedReportsController;
        $error_message = $verify_data->remarkValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $damaged_number = DB::table('damaged_declare_wd')
            ->where('dadw_id',$request['dadw_id'])
            ->value('dadw_damaged_number');

        $res = DB::table('damaged_declare_wd')
            ->where('dadw_id',$request['dadw_id'])
            ->update(['dadw_update_time'=>date('Y-m-d H:i:s'),'dadw_remark'=>$request['remark']]);
        if ($res) {
            Common::addLog($user_info, getRealIp($request), '残损申报', '备注', '残损单:'.$damaged_number.'添加备注:'.$request['remark']);
            DB::commit();
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'更新备注成功']);
        } else{
            DB::rollBack();
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'更新备注失败']);
        }
    }

    //详情
    public function details(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyDamagedReportsController;
        $error_message = $verify_data->detailsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $data_info = DB::table('damaged_declare_goods_wd as dg')
            ->leftjoin('damaged_declare_wd as dd','dg.ddgw_dadw_id','=','dd.dadw_id')
            ->where('ddgw_dadw_id',$request['dadw_id'])
            ->first(['ddgw_goo_name', 'ddgw_goo_encode', 'ddgw_goo_img', 'ddgw_storage_code', 'ddgw_cate_name', 'ddgw_bra_name', 'ddgw_actual_amount','dadw_belongs_bill']);
        if($data_info) {
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$data_info]);
        }else{
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
    }

    //编辑
    public function edit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyDamagedReportsController;
        $error_message = $verify_data->editValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $img = []; 
        foreach ($request['img'] as $key => $value) {
            if (substr($value,0,11) == 'data:image/') {
                $img[$key] = uploadBase64Img($value);
            }else{
                $img[$key] = $value;
            }
        }
        DB::beginTransaction();
        DB::connection('mysql_scm')->beginTransaction();
        $img = implode(',',$img);

        $damaged_number = DB::table('damaged_declare_wd')
            ->where('dadw_id',$request['dadw_id'])
            ->value('dadw_damaged_number');
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $ddgw['ddgw_goo_img'] = $img;//商品图片
        $ddgw['ddgw_storage_code'] = $request['ddgw_storage_code'] ?:'';//商品图片
        $ddgw['ddgw_update_time'] = date('Y-m-d H:i:s');//商品图片
        
        $res = DB::table('damaged_declare_goods_wd')
            ->where('ddgw_dadw_id', $request['dadw_id'])
            ->update($ddgw);
        $dadw_update_res = DB::table('damaged_declare_wd')
                ->where('dadw_id',$request['dadw_id'])
                ->update(['dadw_state'=>1,'dadw_update_time'=>date('Y-m-d H:i:s')]);
        $dare_id = DB::connection('mysql_scm')
                ->table('damage_record')
                ->where('dare_number',$damaged_number)
                ->value('dare_id');
        //残损处理商品表
        $dago['dago_dare_id'] = $dare_id;
        $dago['dago_goo_img'] = $img;
        $dago['dago_update_time'] = date('Y-m-d H:i:s');

        $dago_res = DB::connection('mysql_scm')
                ->table('damage_goods')
                ->where('dago_dare_id',$dare_id)
                ->update($dago);
        $dare_update_res = DB::connection('mysql_scm')
            ->table('damage_record')
            ->where('dare_id',$dare_id)
            ->update(['dare_state'=>1,'dare_update_time'=>date('Y-m-d H:i:s')]);
        if ($res && $dago_res && $dare_update_res && $dadw_update_res) {
            DB::commit();
            DB::connection('mysql_scm')->commit();
            Common::addLog($user_info, getRealIp($request), '残损申报', '编辑', '编辑残损单:'.$damaged_number);
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'编辑成功']);
        } else {
            DB::rollBack();
            DB::connection('mysql_scm')->rollBack();
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'编辑失败']);
        }
    }

    //撤回
    public function revocation(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyDamagedReportsController;
        $error_message = $verify_data->revocationValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $dadw_data = DB::table('damaged_declare_wd')
            ->where('dadw_id',$request['dadw_id'])
            ->first(['dadw_damaged_number','dadw_state']);

        if($dadw_data->dadw_state != 1){
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'状态不是待审核状态不能撤销']);
        }
                // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $dadw_res = DB::table('damaged_declare_wd')
            ->where('dadw_id',$request['dadw_id'])
            ->update(['dadw_state'=>2,'dadw_update_time'=>date('Y-m-d H:i:s')]);

        $dare_del = DB::connection('mysql_scm')
                ->table('damage_record as dr')
                ->leftjoin('damage_goods as dg','dr.dare_id','=','dg.dago_dare_id')
                ->where('dare_number',$dadw_data->dadw_damaged_number)
                ->update(['dr.dare_state'=>5]);
        if ($dadw_res) {
            Common::addLog($user_info, getRealIp($request), '残损申报', '撤回', '撤回残损单:'.$dadw_data->dadw_damaged_number);
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'撤回成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'撤回失败']);
        }
    }

    //删除
    public function delete(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyDamagedReportsController;
        $error_message = $verify_data->deleteValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $dadw_data = DB::table('damaged_declare_wd')
            ->where('dadw_id',$request['dadw_id'])
            ->first(['dadw_damaged_number','dadw_state']);

        if($dadw_data->dadw_state == 3 || $dadw_data->dadw_state == 4){
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'未完成,已完成 状态下不能撤销']);
        }
        DB::beginTransaction();
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $dadw_res = DB::table('damaged_declare_wd as ddw')
            ->leftjoin('damaged_declare_goods_wd as ddgw','ddw.dadw_id','ddgw.ddgw_dadw_id')
            ->where('dadw_id',$request['dadw_id'])
            ->delete();

        $dare_del = DB::connection('mysql_scm')
                ->table('damage_record as dr')
                ->leftjoin('damage_goods as dg','dr.dare_id','=','dg.dago_dare_id')
                ->where('dare_number',$dadw_data->dadw_damaged_number)
                ->delete();
        if ($dadw_res && $dare_del) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '残损申报', '删除', '删除残损单:'.$dadw_data->dadw_damaged_number);
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'删除成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'删除失败']);
        }
    }
}
