<?php

namespace App\Http\Controllers\Api\DistributorsManages;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\DistributorsManages\VerifyReplenishBillsController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\Export;
use App\Http\Models\Api\Replenish;
use App\Http\Models\Api\PushSd;

//渠道补货账单
class ReplenishBillsController 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('replenish_bill_wd')
                        ->where('rebw_cid', $user_info->adm_cid)
                        ->where('rebw_superior_shop_id', $shop_id)
                        // ->where('rebw_state','!=', 6)
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['rebw_state'])) {
                                $query->where('rebw_state', $search_data['rebw_state']);
                            }
                        })
                        ->where(function($query) use($search_data) {
                        //如果选择开始时间并且选择结束时间
                            if (!empty($search_data['start_time']) && !empty($search_data['end_time'])){
                            $query->whereBetween('rebw_create_time',[$search_data['start_time'],$search_data['end_time'].' 23:59:59']);
                            }else{
                                // 如果选择开始时间
                                if (!empty($search_data['start_time'])){
                                    $query->where('rebw_create_time','>=',$search_data['start_time']);
                                }else{
                                    // 如果选择结束时间
                                    if (!empty($search_data['end_time'])) {
                                        $query->where('rebw_create_time','<=',$search_data['end_time'].' 23:59:59');
                                    }
                                }
                            }
                        }) //添加时间
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['rebw_number'])) {
                                $query->where('rebw_number','like', $search_data['rebw_number'].'%');
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['state'])) {
                                $query->where('rebw_state', $search_data['state']);
                            }
                        })//账单状态1未确认2未完成3待审核4已完成5已驳回6已核销
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['rebw_replenish_state'])) {
                                $query->where('rebw_replenish_state', $search_data['rebw_replenish_state']);
                            }
                        })//补货进度1未补2部分3补全
                        ->select('rebw_create_time', 'rebw_number', 'rebw_bill_amount', 'rebw_delivery_amount', 'rebw_remark', 'rebw_no_replenishment','rebw_state', 'rebw_cash_amount', 'rebw_cash_total_money', 'rebw_delivery_order_quantity', 'rebw_replenish_state', 'rebw_id')
                        ->orderBy('rebw_id', 'desc')
                        ->paginate($this->show_count);

        $state_count = DB::table('replenish_bill_wd')
            ->where('rebw_cid', $user_info->adm_cid)
            ->where('rebw_superior_shop_id', $shop_id)
            // ->where('rebw_state','!=','6')
            ->select(DB::raw('count(*) as count, rebw_state'))
            ->groupBy('rebw_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 remark(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyReplenishBillsController;
        $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']);
        //补货账单号
        $rebw_number = DB::table('replenish_bill_wd')
            ->where('rebw_id',$request['rebw_id'])
            ->value('rebw_number');

        $data['rebw_remark'] = $request['remark'];
        $data['rebw_update_time'] = date('Y-m-d H:i:s');

        $rebw_res = DB::table('replenish_bill_wd')
            ->where('rebw_id',$request['rebw_id'])
            ->update($data);
        if(empty($rebw_res)) {
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'添加备注失败']);
        }else{
            Common::addLog($user_info, getRealIp($request), '补货管理','补货账单','补货账单:'.$rebw_number.'添加备注为:'.$request['remark']);
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'添加备注成功']); 
        }
    }

    //账单核销
    public function verification(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyReplenishBillsController;
        $error_message = $verify_data->verificationValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        //补货账单号
        $rebw_data = DB::table('replenish_bill_wd')
            ->where('rebw_id',$request['rebw_id'])
            ->first(['rebw_number','rebw_shop_id','rebw_total_money']);
        DB::beginTransaction(); 
        $data['rebw_state'] = 6;//核销状态
        $data['rebw_update_time'] = date('Y-m-d H:i:s');

        $rerw_number = DB::table('replenish_record_wd')
            ->where('rerw_rebw_id',$request['rebw_id'])
            ->pluck('rerw_number','rerw_id')->toArray();
        //键值交换
        $rerw_id = array_flip($rerw_number);
        $rebw_res = DB::table('replenish_bill_wd')
            ->where('rebw_id',$request['rebw_id'])
            ->update($data);
        if(empty($rebw_res)) {
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'核销失败']);
        }else{
            $bound_id = DB::connection('mysql_scm')
                ->table('channel')
                ->where('chan_shop_id',$rebw_data->rebw_shop_id)
                ->value('chan_bound_id');

            $rrgw_data = DB::table('replenish_record_goods_wd')
                ->whereIn('rrgw_rerw_id',$rerw_id)
                ->get(['rrgw_goo_id','rrgw_goo_name','rrgw_goo_encode','rrgw_actual_send_quantity']);
            $goods_id = [];
            foreach ($rrgw_data as $key => $value) {
                $goods_id[] = $value->rrgw_goo_id;
            }

            $sd_goo = DB::connection('mysql_scm')
                ->table('relationship_goods')
                ->whereIn('rego_id',$goods_id)
                ->pluck('rego_sd_goo_id','rego_id')->toArray();
           
            foreach ($rrgw_data as $key => $value) {
                $goods[$key]['pg_id'] = $sd_goo[$value->rrgw_goo_id];
                $goods[$key]['good_name'] = $value->rrgw_goo_name;
                $goods[$key]['product_version'] = $value->rrgw_goo_encode;
                $goods[$key]['good_num'] = $value->rrgw_actual_send_quantity;
            }
            $goods_list = [];
            foreach ($goods as $key => $value) {
                if(isset($goods_list[$value['pg_id']])){
                    $goods_list[$value['pg_id']]['good_num'] += $value['good_num'];
                    $goods_list[$value['pg_id']]['pg_id'] = $value['pg_id'];
                    $goods_list[$value['pg_id']]['good_name'] = $value['good_name'];
                    $goods_list[$value['pg_id']]['product_version'] = $value['product_version'];
                }else{
                    $goods_list[$value['pg_id']] = $value;
                }
            }
            $goods_data = [];
            foreach ($goods_list as $key => $value) {
                $goods_data[] = $value;
            }
            $list['ser_id'] = $bound_id;
            $list['wd_id'] = 0;
            $list['all_price'] = $rebw_data->rebw_total_money;//物流费
            $list['good_list'] = $goods_data;//商品数据
            $list['distri_num'] = implode(',',$rerw_number);
            $param['sd_list'] = $list;
            $param['wat_num'] = $rebw_data->rebw_number;
            $param['store_list'] = [];
            $param['time'] = date('Y-m-d H:i:s');//收货时间
            $param['token'] = md5(md5($param['time'].'c883e5e641818d993a2d8d966ca450bf'));//token
            $url = config('apisystem.sd_server_name').'/index.php/get_supply_chain';
            $doPost_res = Common::doPost($param,$url);
            $doPost_res = json_decode($doPost_res);
            if($doPost_res->code != 200){
                DB::rollBack(); 
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'失败']);
            }
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '补货管理->补货账单','核销','补货账单:'.$rebw_data->rebw_number.'核销');
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'核销成功']); 
        }
    }

    //补货账单详情
    public function details(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyReplenishBillsController;
        $error_message = $verify_data->detailsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $search_data = $request->all();
        $list_data = DB::table('replenish_goods_wd')
                ->where('regw_rebw_id',$request['rebw_id'])
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['regw_goo_name'])) {
                        $query->where('regw_goo_name','like', $search_data['regw_goo_name'].'%');
                    }
                })
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['regw_goo_encode'])) {
                        $query->where('regw_goo_encode','like', $search_data['regw_goo_encode'].'%');
                    }
                })
                ->select('regw_goo_name', 'regw_goo_encode', 'regw_bra_name', 'regw_cate_name', 'regw_goo_quantity','regw_shipping_fee','regw_delivery_state','regw_id','regw_cash_quantity','regw_cash_money')
                ->orderBy('regw_id', 'desc')
                ->paginate($this->show_count);
        $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();                //返回数据

        if($data_info) {
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$data_info]);
        }else{
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
    }

    //补货账单详情导出
    public function detailsExport(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyReplenishBillsController;
        $error_message = $verify_data->detailsExportValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $search_data = $request->all();
        $list_data = DB::table('replenish_goods_wd')
                ->whereIn('regw_id',$request['regw_id'])
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['regw_goo_name'])) {
                        $query->where('regw_goo_name','like', $search_data['regw_goo_name'].'%');
                    }
                })
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['regw_goo_encode'])) {
                        $query->where('regw_goo_encode','like', $search_data['regw_goo_encode'].'%');
                    }
                })
                ->select('regw_goo_name', 'regw_goo_encode', 'regw_bra_name', 'regw_cate_name', 'regw_goo_quantity','regw_shipping_fee','regw_delivery_state','regw_rebw_id')
                ->orderBy('regw_id', 'desc')
                ->get();
        if($list_data) {
            // 将对象转化为数组
            $list_data = json_decode(json_encode($list_data),true);

            $rebw_number = DB::table('replenish_bill_wd')
                ->where('rebw_id',$list_data[0]['regw_rebw_id'])
                ->value('rebw_number');
            $pathName = storage_path()."/app/public/excel";//获取上传excel路径

            foreach ($list_data as $key => $value) {
                $list_data[$key]['regw_shipping_fee'] = $value['regw_shipping_fee'] / 100;
                if($value['regw_delivery_state'] == 1){
                    $list_data[$key]['regw_delivery_state'] = '是';
                }else{
                    $list_data[$key]['regw_delivery_state'] = '否';
                }
                unset($value['regw_rebw_id']);
            }
            // 创建文件夹
            if (!file_exists($pathName)) {
                mkdir($pathName,0775,true);
                chmod($pathName,0775);
            }

            $streamFileRand = time() . rand(10000,99999).'.xls';//
            // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
            $streamFilename = $pathName . '/' .$streamFileRand;

            $where['action_name'] = '补货账单详情'; 
            $where['field_name'] = ['商品名称','商品编号','商品品牌','商品品类','商品数量','商品配送费','能否补货']; 
            // 调用导出的公共方法
            export::publicExport(
                $streamFilename, //路径
                $where,    //sheet名及其每一行的标题
                $list_data      //导出数据
            );
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            Common::addLog($user_info, getRealIp($request), '补货管理','补货账单','补货账单:'.$rebw_number.'导出');
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'storage/excel/'.$streamFileRand]);
        }else{
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
    }

    //补货账单送货单列表
    public function deliveryList(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyReplenishBillsController;
        $error_message = $verify_data->deliveryListValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $search_data = $request->all();
        $list_data = DB::table('replenish_record_wd')
                ->where('rerw_rebw_id',$request['rebw_id'])
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['rerw_number'])) {
                        $query->where('rerw_number','like', $search_data['rerw_number'].'%');
                    }
                })
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['rerw_state'])) {
                        $query->where('rerw_state', $search_data['rerw_state']);
                    }
                })
                ->where(function($query) use($search_data) {
                //如果选择开始时间并且选择结束时间
                    if (!empty($search_data['start_time']) && !empty($search_data['end_time'])){
                    $query->whereBetween('rerw_create_time',[$search_data['start_time'],$search_data['end_time'].' 23:59:59']);
                    }else{
                        // 如果选择开始时间
                        if (!empty($search_data['start_time'])){
                            $query->where('rerw_create_time','>=',$search_data['start_time']);
                        }else{
                            // 如果选择结束时间
                            if (!empty($search_data['end_time'])) {
                                $query->where('rerw_create_time','<=',$search_data['end_time'].' 23:59:59');
                            }
                        }
                    }
                }) //添加时间
                ->select('rerw_number', 'rerw_create_time', 'rerw_plan_send_amount', 'rerw_actual_send_amount', 'rerw_total_shipping_fee','rerw_remark','rerw_state','rerw_id')
                ->orderBy('rerw_id', 'desc')
                ->paginate($this->show_count);
        $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();                //返回数据

        // 获取当前列表下的按钮
        $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 deliveryRemark(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyReplenishBillsController;
        $error_message = $verify_data->deliveryRemarkValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $res = DB::table('replenish_record_wd')
            ->where('rerw_id',$request['rerw_id'])
            ->update(['rerw_update_time'=>date('Y-m-d H:i:s'),
                      'rerw_remark'=>$request['remark']
                    ]);
        if($res) {
            $rerw_number = DB::table('replenish_record_wd')
            ->where('rerw_id',$request['rerw_id'])
            ->value('rerw_number');
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            Common::addLog($user_info, getRealIp($request), '补货管理->补货账单->送货单','备注','送货单:'.$rerw_number.'添加备注为:'.$request['rerw_id']);
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'添加备注成功']);
        }else{
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'添加备注失败']);
        }
    }

    //补货账单送货单列表详情
    public function deliveryDetails(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyReplenishBillsController;
        $error_message = $verify_data->deliveryDetailsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $data = DB::table('replenish_record_goods_wd')
            ->where('rrgw_rerw_id',$request['rerw_id'])
            ->get(['rrgw_goo_name','rrgw_goo_encode','rrgw_cate_name','rrgw_bra_name','rrgw_actual_send_quantity','rrgw_id']);

        if($data) {
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$data]);
        }else{
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
    }

    //补货账单列表送货单收货接口
    public function takeDelivery(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyReplenishBillsController;
        $error_message = $verify_data->showTakeDeliveryValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        if($request['type'] == 1){
            $data = DB::table('replenish_record_goods_wd')
            ->where('rrgw_rerw_id',$request['rerw_id'])
            ->get(['rrgw_goo_name','rrgw_goo_encode','rrgw_cate_name','rrgw_bra_name','rrgw_plan_send_quantity as rrgw_actual_send_quantity','rrgw_id']);
            if($data) {
                return response()->json(['code'=> 200,'msg'=>'success','data'=>$data]);
            }else{
                return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
            }
        }
        
        // 验证数据
        $verify_data = new VerifyReplenishBillsController;
        $error_message = $verify_data->takeDeliveryValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        //验证数据
        foreach ($request['rrgw_id'] as $key => $value) {
            if(!is_numeric($value) || !is_numeric($request['amount'][$key])){
                return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误']);
            }
        }
        
        DB::beginTransaction();
        DB::connection('mysql_scm')->beginTransaction();
        $rrgw_data = DB::table('replenish_record_goods_wd')
            ->whereIn('rrgw_id',$request['rrgw_id'])
            ->get(['rrgw_goo_name','rrgw_goo_encode','rrgw_cate_name','rrgw_bra_name','rrgw_actual_send_quantity','rrgw_id','rrgw_goo_id','rrgw_plan_send_quantity']);
        if(count($rrgw_data) != count($request['amount'])){
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误']);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $rrgw_ids = implode(',',$request['rrgw_id']);
        $sql = 'UPDATE `faster_replenish_record_goods_wd` SET ';
        $send_quantity = '';//已补送量
        $update_time = '';
        $ids = '';
        $count_amount = 0;
        $state = 1;

        foreach ($rrgw_data as $key => $value) {
            $goods_id[] = $value->rrgw_goo_id;//商品id
            $goo_name[] = $value->rrgw_goo_name;//商品名称
            $goo_encode[] = $value->rrgw_goo_encode;//检索编号
            $cate_name[] = $value->rrgw_cate_name;//商品分类
            $bra_name[] = $value->rrgw_bra_name;//商品品牌
            $count_amount += $request['amount'][$key];
            $gross = $value->rrgw_actual_send_quantity + $request['amount'][$key];
            //如果已补送量 + 本次签收量大于计划配送量
            if($gross > $value->rrgw_plan_send_quantity){
                return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'签收量加送货量不能大于商品数量']);
            }
            //判断货是否补齐 1补齐   2未补齐
            if($gross < $value->rrgw_plan_send_quantity && $state == 1){
                $state = 2;   
            }
            $send_quantity .= ' WHEN '.$request['rrgw_id'][$key].' THEN `rrgw_actual_send_quantity` + '.$request['amount'][$key];
            $update_time .= ' WHEN '.$request['rrgw_id'][$key].' THEN "'.date('Y-m-d H:i:s').'"'; // 更改时间
        }
        $sql .= ' `rrgw_actual_send_quantity`=  CASE `rrgw_id` '.$send_quantity.' END,';
        $sql .= ' `rrgw_update_time`=  CASE `rrgw_id` '.$update_time.' END';
        $sql .= ' WHERE  `rrgw_id` IN ('.trim($rrgw_ids,',').')';
        $rrgw_update = DB::update($sql);

        //修改待补商品数量
        $replenish_res = Replenish::inventory(
            $user_info,
            $goods_id,
            $request['amount'],
            $goo_name,
            $goo_encode,
            $cate_name,
            $bra_name
        );
        //收货人id
        $consignee['rerw_consignee']  = $user_info->adm_id;//收货人id
        //本次发送总数量
        $actual_send_amount = array_sum($request['amount']);
        $rerw_res = DB::table('replenish_record_wd')
            ->where('rerw_id',$request['rerw_id'])
            ->increment('rerw_actual_send_amount',$actual_send_amount,$consignee);

        //门店补货账单id
        $rerw_info = DB::table('replenish_record_wd')
                ->where('rerw_id',$request['rerw_id'])
                ->first(['rerw_rebw_id','rerw_number','rerw_rebw_number']);
        if($state == 1){
            //如果补齐修改完成状态
            $rerw_update['rerw_update_time'] = date('Y-m-d H:i:s');
            $rerw_update['rerw_state'] = 2;
            $rerw_state = DB::table('replenish_record_wd')
                ->where('rerw_id',$request['rerw_id'])
                ->update($rerw_update);
        }else{
            $rerw_state = true;
        }
        // 修改门店补货账单
        $update_rebw = DB::update('UPDATE `faster_replenish_bill_wd` SET `rebw_no_replenishment`=`rebw_no_replenishment`-'.$actual_send_amount.' ,`rebw_update_time`= "'.date('Y-m-d H:i:s').'" WHERE `rebw_id`=?',[$rerw_info->rerw_rebw_id]);
        $rebw_data['rebw_update_time'] = date('Y-m-d H:i:s');

        $rebw_info = DB::table('replenish_bill_wd')
            ->where('rebw_id',$rerw_info->rerw_rebw_id)
            ->first(['rebw_delivery_amount','rebw_bill_amount']);
        //如果账单总量 == 已送货数量
        if($rebw_info->rebw_delivery_amount == $rebw_info->rebw_bill_amount){
            $rebw_data['rebw_replenish_state']  = 3;//补货进度1未补2部分3补全
            $rebw_data['rebw_state']  = 4;//账单状态1未确认2未完成3待审核4已完成5已驳回6已核销
        }else{
            $rebw_data['rebw_replenish_state']  = 2;//补货进度1未补2部分3补全
            $rebw_data['rebw_state']  = 2;//账单状态1未确认2未完成3待审核4已完成5已驳回6已核销
        }

        //修改账单状态
        $rebw_update = DB::table('replenish_bill_wd')
            ->where('rebw_id',$rerw_info->rerw_rebw_id)
            ->update($rebw_data);
        if($rebw_update || $rebw_update===0){
        }else{
            DB::rollBack();
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'收货失败']);
        }
        //供应链配送商库存相关修改
        $rein_data = DB::connection('mysql_scm')
                ->table('relationship_inventory')
                ->where('rein_shop_id',$user_info->adm_shop_id)
                ->first(['rein_id','rein_surplus_type','rein_surplus_amount']);
        //修改门店配送账单状态
        $dere_data['dere_actual_send_amount'] = $count_amount;//签收量
        $dere_data['dere_state'] = 3;//状态1未发货2待收货3已完成4已撤销
        $dere_data['dere_update_time'] = date('Y-m-d H:i:s');

        $dere_id = DB::connection('mysql_scm')
            ->table('delivery_record')
            ->where('dere_number',$rerw_info->rerw_number)
            ->value('dere_id');
        if(empty($dere_id)){
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'送货单记录数据错误']);
        }
        $dere_res = DB::connection('mysql_scm')
            ->table('delivery_record')
            ->where('dere_id',$dere_id)
            ->update($dere_data);

        //配送商库存商品表
        $dego_data = collect(DB::connection('mysql_scm')
            ->table('delivery_goods')
            ->whereIn('dego_rego_id',$goods_id)
            ->where('dego_dere_id',$dere_id)
            ->get(['dego_plan_send_quantity','dego_rego_id']))
            ->keyBy('dego_rego_id')
            ->toArray();
        $goods_id_str = implode(',',$goods_id);
        $sql = 'UPDATE `scm_delivery_goods` SET ';
        $stock_quantity = '';//库存数量
        foreach ($goods_id as $key => $value) {
            if(!isset($dego_data[$value]->dego_rego_id)){
                return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'送货单记录数据错误']);
            }
            //库存数量
            $stock_quantity .= ' WHEN '.$value.' THEN `dego_actual_send_quantity` + '.$request['amount'][$key];
        }
        $sql .= ' `dego_actual_send_quantity`=  CASE `dego_rego_id` '.$stock_quantity.' END';
        $sql .= ' WHERE  `dego_rego_id` IN ('.trim($goods_id_str,',').') AND  `dego_dere_id` = '.$dere_id;
        $dego_update = DB::connection('mysql_scm')->update($sql);

        //配送商库存商品表
        $reid_data = collect(DB::connection('mysql_scm')
            ->table('relationship_inventory_detail')
            ->whereIn('reid_rego_id',$goods_id)
            ->where('reid_rein_id',$rein_data->rein_id)
            ->get(['reid_type','reid_stock_quantity','reid_rego_id']))
            ->keyBy('reid_rego_id')
            ->toArray();
        
        $sql = 'UPDATE `scm_relationship_inventory_detail` SET ';
        $stock_quantity = '';//库存数量
        $stock_type = '';//库存类型1正2负3平
        foreach ($goods_id as $key => $value) {
            $num = $request['amount'][$key];
            if(!isset($reid_data[$value]->reid_type)){
                continue;
            }
            // 库存类型平
            if($reid_data[$value]->reid_type == 3){
                $stock_quantity .= ' WHEN '.$value.' THEN `reid_stock_quantity` + '.$num;
                $stock_type .= ' WHEN '.$value.' THEN 1';
            //库存数量负数
            }else if($reid_data[$value]->reid_type == 2){
                if($reid_data[$value]->reid_stock_quantity > $num){
                    //库存数量
                    $stock_quantity .= ' WHEN '.$value.' THEN `reid_stock_quantity` - '.$num;
                    $stock_type .= ' WHEN '.$value.' THEN 2';
                }
                if($reid_data[$value]->reid_stock_quantity == $num){
                    //库存数量
                    $stock_quantity .= ' WHEN '.$value.' THEN `reid_stock_quantity` - '.$num;
                    $stock_type .= ' WHEN '.$value.' THEN 3';
                }
                if($reid_data[$value]->reid_stock_quantity < $num){
                    $num = $num - $reid_data[$value]->reid_stock_quantity - $reid_data[$value]->reid_stock_quantity;
                    //库存数量
                    $stock_quantity .= ' WHEN '.$value.' THEN `reid_stock_quantity` + '.$num;
                    $stock_type .= ' WHEN '.$value.' THEN 1';
                }
            //库存数量为正数
            }else if($reid_data[$value]->reid_type == 1){
                //库存数量
                $stock_quantity .= ' WHEN '.$value.' THEN `reid_stock_quantity` + '.$num;
                $stock_type .= ' WHEN '.$value.' THEN 1';
            }
        }
        if(!empty($stock_quantity)){
            if(!empty($stock_type)){
                $sql .= ' `reid_type`=  CASE `reid_rego_id` '.$stock_type.' END,';
            }
            $sql .= ' `reid_stock_quantity`=  CASE `reid_rego_id` '.$stock_quantity.' END';
            $sql .= ' WHERE  `reid_rego_id` IN ('.trim($goods_id_str,',').') AND  `reid_rein_id` = '.$rein_data->rein_id;
            $reid_update = DB::connection('mysql_scm')
                                ->update($sql);
        }else{
            $reid_update = true;
        }
        if($update_rebw && $rerw_state && $rerw_res && $rrgw_update && $replenish_res && $reid_update && $dego_update) {
            Common::addLog($user_info, getRealIp($request), '我的补货','补货账单','收货单:'.$rerw_info->rerw_rebw_number.'确认收货');
            DB::commit();
            DB::connection('mysql_scm')->commit();
            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 detailsRevocation(Request $request)
    {
                // 验证数据
        $verify_data = new VerifyReplenishBillsController;
        $error_message = $verify_data->detailsRevocationValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $rrgw_data = DB::table('replenish_record_goods_wd')
            ->where('rrgw_rerw_id',$request['rerw_id'])
            ->get(['rrgw_goo_name','rrgw_goo_encode','rrgw_cate_name','rrgw_bra_name','rrgw_actual_send_quantity','rrgw_id','rrgw_goo_id'])
            ->keyBy('rrgw_goo_id')
            ->toArray();

        $actual_send_quantity = 0;
        $goods_id = [];
        foreach ($rrgw_data as $key => $value) {
            $goods_id[] = $value->rrgw_goo_id;
            $actual_send_quantity += $value->rrgw_actual_send_quantity;
        }
        //渠道补货账单送货单表数据
        $rerw_info = DB::table('replenish_record_wd')
            ->where('rerw_id',$request['rerw_id'])
            ->first(['rerw_rebw_id','rerw_number']);

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        DB::beginTransaction();
        $time = date('Y-m-d H:i:s');    
        //修改收货单表
        $rerw_update['rerw_state'] = 3;
        $rerw_update['rerw_consignee'] = 0;
        $rerw_update['rerw_actual_send_amount'] = 0;
        $rerw_update['rerw_update_time'] = $time;
        $rerw_res = DB::table('replenish_record_wd')
            ->where('rerw_id',$request['rerw_id'])
            ->update($rerw_update);
        //修改收货单商品表
        $rrgw_update['rrgw_state'] = 3;
        $rrgw_update['rrgw_actual_send_quantity'] = 0;
        $rrgw_update['rrgw_update_time'] = $time;
        $rrgw_res = DB::table('replenish_record_goods_wd')
            ->where('rrgw_rerw_id',$request['rerw_id'])
            ->update($rrgw_update);

        // 修改门店补货账单
        $update_rebw = DB::update('UPDATE `faster_replenish_bill_wd` SET `rebw_delivery_amount`=`rebw_delivery_amount`-'.$actual_send_quantity.', `rebw_no_replenishment`=`rebw_no_replenishment`+'.$actual_send_quantity.' ,`rebw_update_time`= "'.date('Y-m-d H:i:s').'" WHERE `rebw_id`=?',[$rerw_info->rerw_rebw_id]);
        $rebw_data['rebw_update_time'] = $time;

        $rebw_info = DB::table('replenish_bill_wd')
            ->where('rebw_id',$rerw_info->rerw_rebw_id)
            ->first(['rebw_delivery_amount','rebw_bill_amount']);
        //如果账单总量 == 已送货数量
        if($rebw_info->rebw_delivery_amount == 0){
            $rebw_data['rebw_replenish_state']  = 1;//补货进度1未补2部分3补全
            $rebw_data['rebw_state']  = 1;//账单状态1未完成2已完成3已核销
        }else{
            $rebw_data['rebw_replenish_state']  = 2;//补货进度1未补2部分3补全
        }
        //修改账单状态
        $rebw_update = DB::table('replenish_bill_wd')
            ->where('rebw_id',$rerw_info->rerw_rebw_id)
            ->update($rebw_data);
        if($rebw_update || $rebw_update===0){
        }else{
            DB::rollBack();
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'收货失败']);
        }

        //供应链配送商库存相关修改
        $rein_data = DB::connection('mysql_scm')
                ->table('relationship_inventory')
                ->where('rein_chan_id',$user_info->adm_shop_id)
                ->first(['rein_id','rein_surplus_type','rein_surplus_amount']);
        if($rein_data->rein_surplus_type == 2){
            if($rein_data->rein_surplus_amount > $actual_send_quantity){
                $data['rein_surplus_amount'] = $rein_data->rein_surplus_amount - $actual_send_quantity;
            }else if($rein_data->rein_surplus_amount < $actual_send_quantity){
                $data['rein_surplus_type'] = 1;//盈亏类型1正2负3平
                $data['rein_surplus_amount'] = $actual_send_quantity - $rein_data->rein_surplus_amount;
            }else{
                $data['rein_surplus_type'] = 3;//盈亏类型1正2负3平
                $data['rein_surplus_amount'] = $actual_send_quantity - $rein_data->rein_surplus_amount;
            }
        }else if($rein_data->rein_surplus_type == 3){
            $data['rein_surplus_type'] = 1;
            $data['rein_surplus_amount'] = $actual_send_quantity;
        }else{
            $data['rein_surplus_amount'] = $actual_send_quantity + $rein_data->rein_surplus_amount;
        }
        $scm_rein_res = DB::connection('mysql_scm')
                ->table('relationship_inventory')
                ->where('rein_id',$rein_data->rein_id)
                ->update($data);

        //配送商库存商品表
        $reid_data = collect(DB::connection('mysql_scm')
            ->table('relationship_inventory_detail')
            ->whereIn('reid_rego_id',$goods_id)
            ->where('reid_rein_id',$rein_data->rein_id)
            ->get(['reid_type','reid_stock_quantity','reid_rego_id']))
            ->keyBy('reid_rego_id')
            ->toArray();

        $goods_id_str = implode(',',$goods_id);
        $sql = 'UPDATE `scm_relationship_inventory_detail` SET ';
        $stock_quantity = '';//库存数量
        $stock_type = '';//库存类型1正2负3平
        foreach ($goods_id as $key => $value) {
            if(isset($reid_data[$value])){
                $num = $rrgw_data[$value]->rrgw_actual_send_quantity;
            }else{
                continue;
            }
            // 库存类型平
            if($reid_data[$value]->reid_type == 3){
                $stock_quantity .= ' WHEN '.$value.' THEN `reid_stock_quantity` + '.$num;
                $stock_type .= ' WHEN '.$value.' THEN 2';
            //库存数量为正
            }else if($reid_data[$value]->reid_type == 1){
                if($reid_data[$value]->reid_stock_quantity > $num){
                    //库存数量
                    $stock_quantity .= ' WHEN '.$value.' THEN `reid_stock_quantity` - '.$num;
                    $stock_type .= ' WHEN '.$value.' THEN 1';
                }
                if($reid_data[$value]->reid_stock_quantity == $num){
                    //库存数量
                    $stock_quantity .= ' WHEN '.$value.' THEN `reid_stock_quantity` - '.$num;
                    $stock_type .= ' WHEN '.$value.' THEN 3';
                }
                if($reid_data[$value]->reid_stock_quantity < $num){
                    $num = $num - $reid_data[$value]->reid_stock_quantity - $reid_data[$value]->reid_stock_quantity;
                    //库存数量
                    $stock_quantity .= ' WHEN '.$value.' THEN `reid_stock_quantity` + '.$num;
                    $stock_type .= ' WHEN '.$value.' THEN 2';
                }
            //库存数量为负数
            }else if($reid_data[$value]->reid_type == 2){
                //库存数量
                $stock_quantity .= ' WHEN '.$value.' THEN `reid_stock_quantity` + '.$num;
                $stock_type .= ' WHEN '.$value.' THEN 2';
            }
        }
        if(!empty($stock_quantity)){
            if(!empty($stock_type)){
                $sql .= ' `reid_type`=  CASE `reid_rego_id` '.$stock_type.' END,';
            }
            $sql .= ' `reid_stock_quantity`=  CASE `reid_rego_id` '.$stock_quantity.' END';
            $sql .= ' WHERE  `reid_rego_id` IN ('.trim($goods_id_str,',').') AND  `reid_rein_id` = '.$rein_data->rein_id;
            $reid_update = DB::connection('mysql_scm')
                                ->update($sql);
        }else{
            $reid_update = true;
        }
        if($update_rebw && $rerw_res && $rrgw_res && $scm_rein_res && $reid_update) {
            Common::addLog($user_info, getRealIp($request), '我的补货','撤销','收货单:'.$rerw_info->rerw_number.'确认收货');
            DB::commit();
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'撤销成功']);
        }else{
            DB::rollBack();
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'撤销失败']);
        }
    }
}
