<?php
namespace App\Http\Controllers\Api\SupplyChains;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\SupplyChains\VerifySupplyBillsController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\Export;
use App\Http\Models\Api\Supply;
use App\Http\Models\Api\PushSd;

//门店补货账单
class SupplyBillsController 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_bs')
                        ->where('rebb_cid', $user_info->adm_cid)
                        ->where('rebb_shop_id', $user_info->adm_shop_id)
                        // ->where('rebb_state','!=',3)
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['rebb_number'])) {
                                $query->where('rebb_number', 'like',$search_data['rebb_number'].'%');
                            }
                        })//补货账单
                        ->where(function($query) use($search_data) {
                        //如果选择开始时间并且选择结束时间
                            if (!empty($search_data['start_time']) && !empty($search_data['end_time'])){
                            $query->whereBetween('rebb_create_time',[$search_data['start_time'],$search_data['end_time'].' 23:59:59']);
                            }else{
                                // 如果选择开始时间
                                if (!empty($search_data['start_time'])){
                                    $query->where('rebb_create_time','>=',$search_data['start_time']);
                                }else{
                                    // 如果选择结束时间
                                    if (!empty($search_data['end_time'])) {
                                        $query->where('rebb_create_time','<=',$search_data['end_time'].' 23:59:59');
                                    }
                                }
                            }
                        }) //添加时间
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['rebb_replenish_state'])) {
                                $query->where('rebb_replenish_state', $search_data['rebb_replenish_state']);
                            }
                        })//补货进度
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['state'])) {
                                $query->where('rebb_state', $search_data['state']);
                            }
                        })//账单状态1未完成2已完成
                        ->select('rebb_number', 'rebb_bill_amount', 'rebb_delivery_amount', 'rebb_no_replenishment', 'rebb_delivery_order_quantity','rebb_remark','rebb_replenish_state','rebb_state','rebb_create_time','rebb_id')
                        ->orderBy('rebb_id', 'desc')
                        ->paginate($this->show_count);
        $state_count = DB::table('replenish_bill_bs')
            ->where('rebb_cid', $user_info->adm_cid)
            ->where('rebb_shop_id', $user_info->adm_shop_id)
            // ->where('rebb_state','!=',3)
            ->select(DB::raw('count(*) as count, rebb_state'))
            ->groupBy('rebb_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 export(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_bs')
                        ->where('rebb_cid', $user_info->adm_cid)
                        ->where('rebb_shop_id', $user_info->adm_shop_id)
                        // ->where('rebb_state','!=',3)
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['rebb_number'])) {
                                $query->where('rebb_number','like', $search_data['rebb_number'].'%');
                            }
                        })//补货账单
                        ->where(function($query) use($search_data) {
                        //如果选择开始时间并且选择结束时间
                            if (!empty($search_data['start_time']) && !empty($search_data['end_time'])){
                            $query->whereBetween('rebb_create_time',[$search_data['start_time'],$search_data['end_time'].' 23:59:59']);
                            }else{
                                // 如果选择开始时间
                                if (!empty($search_data['start_time'])){
                                    $query->where('rebb_create_time','>=',$search_data['start_time']);
                                }else{
                                    // 如果选择结束时间
                                    if (!empty($search_data['end_time'])) {
                                        $query->where('rebb_create_time','<=',$search_data['end_time'].' 23:59:59');
                                    }
                                }
                            }
                        }) //添加时间
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['rebb_replenish_state'])) {
                                $query->where('rebb_replenish_state', $search_data['rebb_replenish_state']);
                            }
                        })//补货进度
                        ->select('rebb_number', 'rebb_bill_amount', 'rebb_delivery_amount', 'rebb_no_replenishment', 'rebb_delivery_order_quantity','rebb_remark','rebb_replenish_state','rebb_state','rebb_create_time')
                        ->orderBy('rebb_id', 'desc')
                        ->get();

        if($list_data) {
            // 将对象转化为数组
            $list_data = json_decode(json_encode($list_data),true);
            foreach ($list_data as $key => $value) {
                if($value['rebb_replenish_state'] == 1){
                    $list_data[$key]['rebb_replenish_state'] = '未补';
                }elseif($value['rebb_replenish_state'] == 2){
                    $list_data[$key]['rebb_replenish_state'] = '部分';
                }elseif($value['rebb_replenish_state'] == 3){
                    $list_data[$key]['rebb_replenish_state'] = '补全';
                }
                if($value['rebb_state'] == 1){
                    $list_data[$key]['rebb_state'] = '未完成';
                }else if($value['rebb_state'] == 2){
                    $list_data[$key]['rebb_state'] = '已完成';
                }else if($value['rebb_state'] == 3){
                    $list_data[$key]['rebb_state'] = '已核销';
                }
            }

            $pathName = storage_path()."/app/public/excel";//获取上传excel路径
            // 创建文件夹
            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      //导出数据
            );
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'storage/excel/'.$streamFileRand]);
        }else{
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
    }

    //补货账单详情
    public function details(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySupplyBillsController;
        $error_message = $verify_data->detailsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $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_goods_bs')
                        ->where('regb_rebb_id', $request['rebb_id'])
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['regb_goo_name'])) {
                                $query->where('regb_goo_name','like', $search_data['regb_goo_name'].'%');
                            }
                        })//商品名称
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['regb_goo_encode'])) {
                                $query->where('regb_goo_encode','like', $search_data['regb_goo_encode'].'%');
                            }
                        })//补货进度
                        ->select('regb_goo_name', 'regb_goo_encode', 'regb_bra_name', 'regb_cate_name','regb_goo_quantity')
                        ->orderBy('regb_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($list_data) {
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$data_info]);
        }else{
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
    }

    //补货备注接口
    public function remark(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySupplyBillsController;
        $error_message = $verify_data->remarkValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $rebb = DB::table('replenish_bill_bs')
            ->where('rebb_id',$request['rebb_id'])
            ->first(['rebb_number']);

        $res = DB::table('replenish_bill_bs')
            ->where('rebb_id',$request['rebb_id'])
            ->update(['rebb_remark'=>$request['remark'],'rebb_update_time'=>date('Y-m-d H:i:s')]);
        if(empty($res)) {
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'添加备注失败']);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        Common::addLog($user_info, getRealIp($request), '我的补货','补货账单','补货账单:'.$rebb->rebb_number.'添加备注为:'.$request['rerb_remark']);
        return response()->json(['code'=> 200,'msg'=>'success','data'=>'添加备注成功']);
    }

    //核销
    public function cancel(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySupplyBillsController;
        $error_message = $verify_data->cancelValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        DB::beginTransaction();
        DB::connection('mysql_scm')->beginTransaction();

        $rebb = DB::table('replenish_bill_bs')
            ->where('rebb_id',$request['rebb_id'])
            ->first(['rebb_state','rebb_number']);
        if($rebb->rebb_state == 1){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'未完成的账单不能核销']);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        //推送速电商品
        $supply_res = (new PushSd)->pushs(
            $user_info,
            $request['rebb_id']
        );
        $res = DB::table('replenish_bill_bs')
            ->where('rebb_id',$request['rebb_id'])
            ->update(['rebb_state'=>3]);
        if(empty($res)) {
            DB::rollBack();
            DB::connection('mysql_scm')->rollBack();
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'核销失败']);
        }
        DB::commit();
        DB::connection('mysql_scm')->commit();
        Common::addLog($user_info, getRealIp($request), '我的补货','补货账单','补货账单:'.$rebb->rebb_number.'核销');
        return response()->json(['code'=> 200,'msg'=>'success','data'=>'核销成功']);
    }

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

        // 验证数据
        $verify_data = new VerifySupplyBillsController;
        $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_bs')
                        ->where('rerb_rebb_id',$request['rebb_id'])
                        ->where(function($query) use($search_data) {
                        //如果选择开始时间并且选择结束时间
                            if (!empty($search_data['start_time']) && !empty($search_data['end_time'])){
                            $query->whereBetween('rerb_create_time',[$search_data['start_time'],$search_data['end_time'].' 23:59:59']);
                            }else{
                                // 如果选择开始时间
                                if (!empty($search_data['start_time'])){
                                    $query->where('rerb_create_time','>=',$search_data['start_time']);
                                }else{
                                    // 如果选择结束时间
                                    if (!empty($search_data['end_time'])) {
                                        $query->where('rerb_create_time','<=',$search_data['end_time'].' 23:59:59');
                                    }
                                }
                            }
                        }) //添加时间
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['rerb_number'])) {
                                $query->where('rerb_number','like', $search_data['rerb_number'].'%');
                            }
                        })//补货进度
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['rerb_state'])) {
                                $query->where('rerb_state', $search_data['rerb_state']);
                            }
                        })//补货进度
                        ->select('rerb_number', 'rerb_actual_send_amount', 'rerb_plan_send_amount', 'rerb_total_shipping_fee', 'rerb_remark','rerb_state','rerb_create_time','rerb_id')
                        ->orderBy('rerb_id', 'desc')
                        ->paginate($this->show_count);
                // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        $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($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 deliveryDetails(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 验证数据
        $verify_data = new VerifySupplyBillsController;
        $error_message = $verify_data->deliveryDetailsValidator($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_goods_bs')
                        ->where('rrgb_rerb_id',$request['rerb_id'])
                        ->select('rrgb_goo_name', 'rrgb_goo_encode', 'rrgb_cate_name', 'rrgb_bra_name', 'rrgb_plan_send_quantity','rrgb_shipping_fee','rrgb_id')
                        ->orderBy('rrgb_id', 'desc')
                        ->get();
        if(empty($list_data)) {
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
        return response()->json(['code'=> 200,'msg'=>'success','data'=>$list_data]);
    }

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

        // 验证数据
        $verify_data = new VerifySupplyBillsController;
        $error_message = $verify_data->getTakeDeliveryValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        if($request['type'] == 1){
            $search_data = $request->all();
            $list_data = DB::table('replenish_record_goods_bs')
                            ->where('rrgb_rerb_id',$request['rerb_id'])
                            ->select('rrgb_goo_name', 'rrgb_goo_encode', 'rrgb_cate_name', 'rrgb_bra_name', 'rrgb_actual_send_quantity','rrgb_plan_send_quantity','rrgb_id')
                            ->orderBy('rrgb_id', 'desc')
                            ->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();                //返回数据

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

        // 验证数据
        $verify_data = new VerifySupplyBillsController;
        $error_message = $verify_data->takeDeliveryValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'111', 'error_message'=>$error_message]);
        }
        //验证数据
        foreach ($request['rrgb_id'] as $key => $value) {
            if(!is_numeric($value) || !is_numeric($request['amount'][$key])){
                return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误']);
            }
        }
        // php数组合并两个数组(一个数组做键名，另一个做值)
        $submit = array_combine($request['rrgb_id'],$request['amount']);
        DB::beginTransaction();
        DB::connection('mysql_scm')->beginTransaction();
        $list_data = DB::table('replenish_record_goods_bs')
                ->where('rrgb_rerb_id',$request['rerb_id'])
                ->whereIn('rrgb_id',$request['rrgb_id'])
                ->get(['rrgb_actual_send_quantity','rrgb_plan_send_quantity','rrgb_update_time','rrgb_goo_id','rrgb_goo_name','rrgb_goo_encode','rrgb_cate_name','rrgb_bra_name','rrgb_id','rrgb_sd_goo_id','rrgb_id']);
        if(count($list_data) != count($request['amount'])){
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误']);
        }

        $rrgb_ids = implode(',',$request['rrgb_id']);
        $sql = 'UPDATE `faster_replenish_record_goods_bs` SET ';
        $send_quantity = '';//已补送量
        $rrgb_update_time = '';
        $ids = '';
        $amount = [];
        foreach ($list_data as $key => $value) {
            $goods_id[] = $value->rrgb_goo_id;//商品id
            $amount[] = $submit[$value->rrgb_id];//数量
            $goo_name[] = $value->rrgb_goo_name;//商品名称
            $goo_encode[] = $value->rrgb_goo_encode;//检索编号
            $cate_name[] = $value->rrgb_cate_name;//商品分类
            $bra_name[] = $value->rrgb_bra_name;//商品品牌
            //如果已补送量 + 本次签收量大于计划配送量
            if($submit[$value->rrgb_id] != $value->rrgb_plan_send_quantity){
                return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'签收数量必须等于送货数量']);
            }
            $send_quantity .= ' WHEN '.$request['rrgb_id'][$key].' THEN `rrgb_actual_send_quantity` + '.$request['amount'][$key];
            $rrgb_update_time .= ' WHEN '.$request['rrgb_id'][$key].' THEN "'.date('Y-m-d H:i:s').'"'; // 更改时间
        }
        $sql .= ' `rrgb_actual_send_quantity`=  CASE `rrgb_id` '.$send_quantity.' END,';
        $sql .= ' `rrgb_update_time`=  CASE `rrgb_id` '.$rrgb_update_time.' END';
        $sql .= ' WHERE  `rrgb_id` IN ('.trim($rrgb_ids,',').')';

        $rrgb_update = DB::update($sql);
        // php数组合并两个数组(一个数组做键名，另一个做值)
        $amount_menu = array_combine($goods_id,$amount);
        //修改待补商品数量
        $supply_res = Supply::inventory(
            $user_info,
            $goods_id,
            $amount_menu,
            $goo_name,
            $goo_encode,
            $cate_name,
            $bra_name
        );
        //本次发送总数量
        $actual_send_amount = array_sum($request['amount']);

        //门店补货收货单数据
        $rerb_info = DB::table('replenish_record_bs')
                ->where('rerb_id',$request['rerb_id'])
                ->first(['rerb_rebb_id', 'rerb_rebb_number', 'rerb_number', 'rerb_id' ,'rerb_wd_shop_id', 'rerb_deliver_type']);
        $consignee['rerb_state'] = 2;
        //收货人id
        $consignee['rerb_consignee']  = $user_info->adm_id;//收货人id
        $rerb_res = DB::table('replenish_record_bs')
            ->where('rerb_id',$request['rerb_id'])
            ->increment('rerb_actual_send_amount',$actual_send_amount,$consignee);

        $rebb_data = DB::table('replenish_bill_bs')
            ->where('rebb_id',$rerb_info->rerb_rebb_id)
            ->first(['rebb_replenish_state', 'rebb_state', 'rebb_bill_amount' ,'rebb_no_replenishment']);
        //如果账单总量 == 送货数量
        if($rebb_data->rebb_no_replenishment <= $actual_send_amount){
            $sql = '`rebb_replenish_state` = 3,`rebb_state` = 2,';//补货进度1未补2部分3补全
        }else{
            $sql = '`rebb_replenish_state` = 2,`rebb_state` = 1,';//账单状态1未完成2已完成3已核销
        }
        // 修改门店补货账单
        $update_rebb = DB::update('UPDATE `faster_replenish_bill_bs` SET `rebb_no_replenishment`=`rebb_no_replenishment`-'.$actual_send_amount.' ,'.$sql.'`rebb_update_time`= "'.date('Y-m-d H:i:s').'" WHERE `rebb_id`=?',[$rerb_info->rerb_rebb_id]);
        //如果是配送商发货
        if($rerb_info->rerb_deliver_type == 2){
            //供应链配送商库存相关修改
            $rein_data = DB::connection('mysql_scm')
                    ->table('relationship_inventory')
                    ->where('rein_shop_id',$rerb_info->rerb_wd_shop_id)
                    ->first(['rein_id','rein_credit_amount','rein_credit_type']);
            if(empty($rein_data)){
                return response()->json(['code'=> 500,'msg'=>'error','data'=>'没有此配送商库存']);
            }
            //渠道送货单状态
            $derw_data['derw_state'] = 2;
            $derw_data['derw_update_time'] = date('Y-m-d H:i:s');
            $derw_res = DB::table('deliver_record_wd')
            ->where('derw_number',$rerb_info->rerb_number)
            ->increment('derw_actual_send_amount',$actual_send_amount,$derw_data);

            $derw_debw_id = DB::table('deliver_record_wd')
                ->where('derw_number',$rerb_info->rerb_number)
                ->value('derw_debw_id');
            $debw_data = DB::table('deliver_bill_wd')
                ->where('debw_id',$derw_debw_id)
                ->first(['debw_no_replenishment','debw_shipping_number']);
            if($debw_data->debw_no_replenishment == 0){
                $debw_res = DB::table('deliver_bill_wd')
                ->where('debw_id',$derw_debw_id)
                ->update(['debw_replenish_state'=>3,'debw_state'=>4,'debw_update_time'=>date('Y-m-d H:i:s')]);

                $rebi_no = DB::connection('mysql_scm')
                    ->table('relationship_bill')
                    ->where('rebi_sd_replenishment_number',$debw_data->debw_shipping_number)
                    ->value('rebi_no_replenishment');
                if($rebi_no == 0){
                    $rebi_res = DB::connection('mysql_scm')
                        ->table('relationship_bill')
                        ->where('rebi_sd_replenishment_number',$debw_data->debw_shipping_number)
                        ->update(['rebi_replenish_state'=>3,'rebi_state'=>4,'rebi_update_time'=>date('Y-m-d H:i:s')]);
                }else{
                    $rebi_res = true;
                }
            }else{
                $rebi_res = true;
                $debw_res = true;
            }

            //配送商库存商品表
            $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 = '';//库存数量
            $quantity_type = '';//库存类型1正2负3平
            $enroute_quantity = '';//在途数量
            $delivery_quantity = '';//累计配送量
            foreach ($goods_id as $key => $value) {
                $num = $amount[$key];
                if(!isset($reid_data[$value]->reid_type)){
                    return response()->json(['code'=> 500,'msg'=>'error','data'=>'此配送商没有该商品']);
                }
                //库存数量为平
                if($reid_data[$value]->reid_type == 3){
                    //库存数量
                    $stock_quantity .= ' WHEN '.$value.' THEN `reid_stock_quantity` + '.$num;
                    $quantity_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;
                        $quantity_type .= ' WHEN '.$value.' THEN 1';
                    }
                    if($reid_data[$value]->reid_stock_quantity == $num){
                        //库存数量
                        $stock_quantity .= ' WHEN '.$value.' THEN `reid_stock_quantity` - '.$num;
                        $quantity_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;
                        $quantity_type .= ' WHEN '.$value.' THEN 2';
                    }
                //库存数量为负数
                }else if($reid_data[$value]->reid_type == 2){
                    $stock_quantity .= ' WHEN '.$value.' THEN `reid_stock_quantity` + '.$num;
                    $quantity_type .= ' WHEN '.$value.' THEN 2';
                }
                //在途数量
                $enroute_quantity .= ' WHEN '.$value.' THEN `reid_enroute_quantity` - '.$num;
                //累计配送量
                $delivery_quantity .= ' WHEN '.$value.' THEN `reid_delivery_quantity` + '.$num;
            }
            if(!empty($stock_quantity)){
                if(!empty($quantity_type)){
                    $sql .= ' `reid_type`=  CASE `reid_rego_id` '.$quantity_type.' END,';
                }
                $sql .= ' `reid_stock_quantity`=  CASE `reid_rego_id` '.$stock_quantity.' END,';
                $sql .= ' `reid_enroute_quantity`=  CASE `reid_rego_id` '.$enroute_quantity.' END,';
                $sql .= ' `reid_delivery_quantity`=  CASE `reid_rego_id` '.$delivery_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;
            }

            //wd补货商品数据
            $regw_info = collect(DB::table('replenishment_goods_wd')
                ->whereIn('regw_goo_id',$goods_id)
                ->where('regw_shop_id',$rerb_info->rerb_wd_shop_id)
                ->get(['regw_stock_type','regw_stock_quantity','regw_goo_id']))
                ->keyBy('regw_goo_id')
                ->toArray();

            $sql = 'UPDATE `faster_replenishment_goods_wd` SET ';
            $stock_quantity = '';//待补数量
            $delivery_amount = '';//累计数量
            $enroute_amount = '';//在途数量
            $update_time = '';//修改时间
            $stock_type = '';//库存正负
            $ids = '';
            $insert_goo_data = [];
            foreach ($goods_id as $key => $value) {
                //如果待补商品里有此数据
                if(isset($regw_info[$value])){
                    $num = $amount[$key];
                    // 判断库存是为负数
                    if($regw_info[$value]->regw_stock_type == 3){
                        $stock_quantity .= ' WHEN '.$value.' THEN `regw_stock_quantity` + '.$num;
                        $stock_type .= ' WHEN '.$value.' THEN 3';
                    //库存数量为平
                    }else if($regw_info[$value]->regw_stock_type == 1){
                        //待补数量
                        $stock_quantity .= ' WHEN '.$value.' THEN `regw_stock_quantity` + '.$num;
                        $stock_type .= ' WHEN '.$value.' THEN 3';
                    //库存数量为正
                    }else if($regw_info[$value]->regw_stock_type == 2){
                        if($regw_info[$value]->regw_stock_quantity > $num){
                            //待补数量
                            $stock_quantity .= ' WHEN '.$value.' THEN `regw_stock_quantity` - '.$num;
                            $stock_type .= ' WHEN '.$value.' THEN 3';
                        }
                        if($regw_info[$value]->regw_stock_quantity == $num){
                            //待补数量
                            $stock_quantity .= ' WHEN '.$value.' THEN `regw_stock_quantity` - '.$num;
                            $stock_type .= ' WHEN '.$value.' THEN 1';
                        }
                        if($regw_info[$value]->regw_stock_quantity < $num){
                            $num = $num - $regw_info[$value]->regw_stock_quantity - $regw_info[$value]->regw_stock_quantity;
                            //待补数量
                            $stock_quantity .= ' WHEN '.$value.' THEN `regw_stock_quantity` + '.$num;
                            $stock_type .= ' WHEN '.$value.' THEN 3';
                        }
                    }
                    //在途数量
                    $enroute_amount .= ' WHEN '.$value.' THEN `regw_enroute_amount` - '.$num;
                    //累计数量
                    $delivery_amount .= ' WHEN '.$value.' THEN `regw_delivery_amount` + '.$num;
                    // 更改时间
                    $update_time .= ' WHEN '.$value.' THEN "'.date('Y-m-d H:i:s').'"';
                }else{
                    return response()->json(["code"=>500,'msg'=>'success','data'=>'数据错误']);
                }
            }
            if(!empty($enroute_amount)){
                $sql .= ' `regw_enroute_amount`=  CASE `regw_goo_id` '.$enroute_amount.' END,';
                if(!empty($stock_type)){
                    $sql .= ' `regw_stock_type`=  CASE `regw_goo_id` '.$stock_type.' END,';
                }
                $sql .= ' `regw_delivery_amount`=  CASE `regw_goo_id` '.$delivery_amount.' END,';
                $sql .= ' `regw_stock_quantity`=  CASE `regw_goo_id` '.$stock_quantity.' END,';
                $sql .= ' `regw_update_time`=  CASE `regw_goo_id` '.$update_time.' END';
                $sql .= ' WHERE  `regw_goo_id` IN ('.trim($goods_id_str,',').') AND  `regw_shop_id` = '.$rerb_info->rerb_wd_shop_id;
                $regw_update = DB::update($sql);
            }else{
                $regw_update = true;
            }
        }else{
            // 修改配送账单数量
            $dere_sql = 'UPDATE `scm_delivery_record` SET  `dere_actual_send_amount`= `dere_actual_send_amount`+' . $actual_send_amount .' ,`dere_state`= 3, `dere_update_time`= "'.date('Y-m-d H:i:s').'" WHERE `dere_number` ="'.$rerb_info->rerb_number.'"';
            $derw_res = DB::connection('mysql_scm')->update($dere_sql);

            $shbi_id = DB::connection('mysql_scm')
                ->table('delivery_record')
                ->where('dere_number',$rerb_info->rerb_number)
                ->value('dere_shbi_id');
            $shbi_data = DB::connection('mysql_scm')
                ->table('shipping_bill')
                ->where('shbi_id',$shbi_id)
                ->first(['shbi_no_replenishment','shbi_sd_replenishment_number']);
            if($shbi_data->shbi_no_replenishment == 0){
                $debw_res = DB::connection('mysql_scm')
                    ->table('shipping_bill')
                    ->where('shbi_id',$shbi_id)
                    ->update(['shbi_replenish_state'=>3,'shbi_state'=>3,'shbi_update_time'=>date('Y-m-d H:i:s')]);

                $rebi_no = DB::connection('mysql_scm')
                    ->table('relationship_bill')
                    ->where('rebi_sd_replenishment_number',$shbi_data->shbi_sd_replenishment_number)
                    ->value('rebi_no_replenishment');
                if($rebi_no == 0){
                    $reid_update = DB::connection('mysql_scm')
                        ->table('relationship_bill')
                        ->where('rebi_sd_replenishment_number',$shbi_data->shbi_sd_replenishment_number)
                        ->update(['rebi_replenish_state'=>3,'rebi_state'=>4]);
                }else{
                    $reid_update = true;
                }
            }else{
                $debw_res = true;
                $reid_update = true;
            }
            $reid_update = true;
            $rebi_res = true;
        } 
        if($update_rebb && $rerb_res && $rrgb_update && $supply_res && $derw_res && $reid_update && $debw_res && $rebi_res) {
            Common::addLog($user_info, getRealIp($request), '我的补货','补货账单','收货单:'.$rerb_info->rerb_rebb_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 deliveryRemark(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySupplyBillsController;
        $error_message = $verify_data->deliveryRemarkValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
                // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $data['rerb_remark'] = $request['rerb_remark'];
        $data['rerb_update_time'] = date('Y-m-d H:i:s');
        $search_data = $request->all();
        $rerb_update = DB::table('replenish_record_bs')
                        ->where('rerb_id',$request['rerb_id'])
                        ->update($data);

        $rerb_number = DB::table('replenish_record_bs')
                        ->where('rerb_id',$request['rerb_id'])
                        ->value('rerb_number');
        if(empty($rerb_update)) {
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'添加备注失败']);
        }
        Common::addLog($user_info, getRealIp($request), '我的补货','补货账单','送货单:'.$rerb_number.'添加备注为:'.$request['rerb_remark']);
        return response()->json(['code'=> 200,'msg'=>'success','data'=>'添加备注成功']);
    }

    // 收货单撤销收货
    public function revocation(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySupplyBillsController;
        $error_message = $verify_data->revocationValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        DB::beginTransaction();
        DB::connection('mysql_scm')->beginTransaction();

        $rerb_info = DB::table('replenish_record_bs')
            ->where('rerb_id',$request['rerb_id'])
            ->first(['rerb_number','rerb_rebb_id','rerb_actual_send_amount','rerb_wd_shop_id','rerb_deliver_type']);
        $rrgb_info = DB::table('replenish_record_goods_bs')
                ->where('rrgb_rerb_id',$request['rerb_id'])
                ->get(['rrgb_goo_id','rrgb_actual_send_quantity']);
        foreach ($rrgb_info as $key => $value) {
            $goods_id[] = $value->rrgb_goo_id;
            $quantity[] = $value->rrgb_actual_send_quantity;
        }

        $rebb_data = DB::table('replenish_bill_bs')
            ->where('rebb_id',$rerb_info->rerb_rebb_id)
            ->first(['rebb_replenish_state','rebb_state','rebb_bill_amount','rebb_shipping_number','rebb_number']);

        if($rebb_data->rebb_bill_amount == $rerb_info->rerb_actual_send_amount){
            $sql = '`rebb_replenish_state` = 1,`rebb_state` = 1,';
        }else{
            $sql = '`rebb_replenish_state` = 2,`rebb_state` = 1,';
        }
        //门店补货账单表状态
        $update_rebb = DB::update('UPDATE `faster_replenish_bill_bs` SET `rebb_no_replenishment`=`rebb_no_replenishment`+'.$rerb_info->rerb_actual_send_amount.' ,'.$sql.'`rebb_update_time`= "'.date('Y-m-d H:i:s').'" WHERE `rebb_id`=?',[$rerb_info->rerb_rebb_id]);

        $rerb_data['rerb_actual_send_amount'] = 0;
        $rerb_data['rerb_state'] = 3;
        $rerb_data['rerb_update_time'] = date('Y-m-d H:i:s');
        //门店补货账单收货单表
        $rerb_res = DB::table('replenish_record_bs')
            ->where('rerb_id',$request['rerb_id'])
            ->update($rerb_data);

        //修改待补商品数量
        $supply_res = Supply::revocation(
            $user_info,
            $request['rerb_id']
        );

        // 供应链补货账单表
        $rebi_sql = 'UPDATE `scm_relationship_bill` SET  `rebi_delivery_quantity`= `rebi_delivery_quantity`-' . $rerb_info->rerb_actual_send_amount .' , `rebi_no_replenishment`= `rebi_no_replenishment` + '.$rerb_info->rerb_actual_send_amount." WHERE `rebi_sd_replenishment_number` = '".$rebb_data->rebb_number."'";
        $scm_rebi_res = DB::connection('mysql_scm')->update($rebi_sql);

        $rebi_res = DB::connection('mysql_scm')
            ->table('relationship_bill')
            ->where('rebi_sd_replenishment_number',$rebb_data->rebb_number)
            ->update(['rebi_replenish_state'=>2,'rebi_state'=>3,'rebi_update_time'=>date('Y-m-d H:i:s')]);

        // 门店补货账单收货单商品表
        $rrgb_data['rrgb_actual_send_quantity'] = 0;
        $rrgb_data['rrgb_state'] = 3;
        $rrgb_data['rrgb_update_time'] = date('Y-m-d H:i:s');
        $rrgb_res = DB::table('replenish_record_goods_bs')
            ->where('rrgb_rerb_id',$request['rerb_id'])
            ->update($rrgb_data);
        //发货类型1速电发货2配送商发货
        if($rerb_info->rerb_deliver_type == 2){
            //渠道送货单状态
            $derw_data['derw_state'] = 3;
            $derw_data['derw_update_time'] = date('Y-m-d H:i:s');
            $derw_res = DB::table('deliver_record_wd')
                ->where('derw_number',$rerb_info->rerb_number)
                ->decrement('derw_actual_send_amount',$rerb_info->rerb_actual_send_amount,$derw_data);
            $debw_id = DB::table('deliver_record_wd')
                ->where('derw_number',$rerb_info->rerb_number)
                ->first(['derw_debw_id']);

            $debw_info = DB::table('deliver_bill_wd')
                ->where('debw_id',$debw_id->derw_debw_id)
                ->first(['debw_bill_amount','debw_no_replenishment']);
            $debw_data['debw_update_time'] = date('Y-m-d H:i:s');
            if($debw_info->debw_bill_amount == $rerb_info->rerb_actual_send_amount){
                $debw_data['debw_replenish_state'] = 1;
            }else{
                $debw_data['debw_replenish_state'] = 2;
            }
            $debw_data['debw_state'] = 3;
            $debw_data['debw_no_replenishment'] = $debw_info->debw_no_replenishment + $rerb_info->rerb_actual_send_amount;
            $debw_res = DB::table('deliver_bill_wd')
                ->where('debw_id',$debw_id->derw_debw_id)
                ->decrement('debw_delivery_amount',$rerb_info->rerb_actual_send_amount,$debw_data);

            $sql = 'UPDATE `faster_deliver_goods_wd` SET ';
            $quantity_str = '';//已送
            $update_time = '';
            $goods_id_str = implode(',',$goods_id);
            foreach ($goods_id as $key => $value) {
                //已发送数量
                $quantity_str .= ' WHEN '.$value.' THEN `degw_already_quantity` - '.$quantity[$key];
                // 更改时间
                $update_time .= ' WHEN '.$value.' THEN "'.date('Y-m-d H:i:s').'"';
            }
            $sql .= ' `degw_already_quantity`=  CASE `degw_goo_id` '.$quantity_str.' END,';
            $sql .= ' `degw_update_time`=  CASE `degw_goo_id` '.$update_time.' END';
            $sql .= ' WHERE  `degw_goo_id` IN ('.trim($goods_id_str,',').') AND degw_debw_id ='.$debw_id->derw_debw_id;
            $degw_update = DB::update($sql);
                
            //供应链配送商库存相关修改
            $rein_data = DB::connection('mysql_scm')
                    ->table('relationship_inventory')
                    ->where('rein_shop_id',$rerb_info->rerb_wd_shop_id)
                    ->first(['rein_id','rein_credit_amount','rein_credit_type']);
            if(empty($rein_data)){
                return response()->json(['code'=> 500,'msg'=>'error','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 = '';//库存数量
            $quantity_type = '';//库存类型1正2负3平
            $enroute_quantity = '';//在途数量
            $delivery_quantity = '';//累计配送量
            foreach ($goods_id as $key => $value) {
                $num = $quantity[$key];
                if(!isset($reid_data[$value]->reid_type)){
                    return response()->json(['code'=> 500,'msg'=>'error','data'=>'此配送商没有该商品']);
                }
                //库存数量为平
                if($reid_data[$value]->reid_type == 3){
                    //库存数量
                    $stock_quantity .= ' WHEN '.$value.' THEN `reid_stock_quantity` + '.$num;
                    $quantity_type .= ' WHEN '.$value.' THEN 1';
                //库存数量为正
                }else if($reid_data[$value]->reid_type == 1){
                    $stock_quantity .= ' WHEN '.$value.' THEN `reid_stock_quantity` + '.$num;
                    $quantity_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;
                        $quantity_type .= ' WHEN '.$value.' THEN 2';
                    }
                    if($reid_data[$value]->reid_stock_quantity == $num){
                        //库存数量
                        $stock_quantity .= ' WHEN '.$value.' THEN `reid_stock_quantity` - '.$num;
                        $quantity_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;
                        $quantity_type .= ' WHEN '.$value.' THEN 1';
                    }
                }
                // //在途数量
                // $enroute_quantity .= ' WHEN '.$value.' THEN `reid_enroute_quantity` + '.$num;
                //累计配送量
                $delivery_quantity .= ' WHEN '.$value.' THEN `reid_delivery_quantity` - '.$num;
            }
            if(!empty($stock_quantity)){
                if(!empty($quantity_type)){
                    $sql .= ' `reid_type`=  CASE `reid_rego_id` '.$quantity_type.' END,';
                }
                $sql .= ' `reid_stock_quantity`=  CASE `reid_rego_id` '.$stock_quantity.' END,';
                // $sql .= ' `reid_enroute_quantity`=  CASE `reid_rego_id` '.$enroute_quantity.' END,';
                $sql .= ' `reid_delivery_quantity`=  CASE `reid_rego_id` '.$delivery_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;
            }
            //wd补货商品数据
            $regw_info = collect(DB::table('replenishment_goods_wd')
                ->whereIn('regw_goo_id',$goods_id)
                ->where('regw_shop_id',$rerb_info->rerb_wd_shop_id)
                ->get(['regw_stock_type','regw_stock_quantity','regw_goo_id']))
                ->keyBy('regw_goo_id')
                ->toArray();

            $sql = 'UPDATE `faster_replenishment_goods_wd` SET ';
            $stock_quantity = '';//待补数量
            $delivery_amount = '';//累计数量
            $enroute_amount = '';//在途数量
            $update_time = '';//修改时间
            $stock_type = '';//库存正负
            $ids = '';
            $insert_goo_data = [];
            foreach ($goods_id as $key => $value) {
                //如果待补商品里有此数据
                if(isset($regw_info[$value])){
                    $num = $quantity[$key];
                    // 判断库存是为负数
                    if($regw_info[$value]->regw_stock_type == 3){
                        if($regw_info[$value]->regw_stock_quantity > $num){
                            //待补数量
                            $stock_quantity .= ' WHEN '.$value.' THEN `regw_stock_quantity` - '.$num;
                            $stock_type .= ' WHEN '.$value.' THEN 3';
                        }
                        if($regw_info[$value]->regw_stock_quantity == $num){
                            //待补数量
                            $stock_quantity .= ' WHEN '.$value.' THEN `regw_stock_quantity` - '.$num;
                            $stock_type .= ' WHEN '.$value.' THEN 1';
                        }
                        if($regw_info[$value]->regw_stock_quantity < $num){
                            $num = $num - $regw_info[$value]->regw_stock_quantity - $regw_info[$value]->regw_stock_quantity;
                            //待补数量
                            $stock_quantity .= ' WHEN '.$value.' THEN `regw_stock_quantity` + '.$num;
                            $stock_type .= ' WHEN '.$value.' THEN 2';
                        }
                    //库存数量为平
                    }else if($regw_info[$value]->regw_stock_type == 1){
                        //待补数量
                        $stock_quantity .= ' WHEN '.$value.' THEN `regw_stock_quantity` + '.$num;
                        $stock_type .= ' WHEN '.$value.' THEN 2';
                    //库存数量为正
                    }else if($regw_info[$value]->regw_stock_type == 2){
                        $stock_quantity .= ' WHEN '.$value.' THEN `regw_stock_quantity` + '.$num;
                        $stock_type .= ' WHEN '.$value.' THEN 2';
                    }
                    //累计数量
                    $delivery_amount .= ' WHEN '.$value.' THEN `regw_delivery_amount` - '.$num;
                    // 更改时间
                    $update_time .= ' WHEN '.$value.' THEN "'.date('Y-m-d H:i:s').'"';
                }else{
                    return response()->json(["code"=>500,'msg'=>'success','data'=>'数据错误']);
                }
            }
            if(!empty($delivery_amount)){
                // $sql .= ' `regw_enroute_amount`=  CASE `regw_goo_id` '.$enroute_amount.' END,';
                if(!empty($stock_type)){
                    $sql .= ' `regw_stock_type`=  CASE `regw_goo_id` '.$stock_type.' END,';
                }
                $sql .= ' `regw_delivery_amount`=  CASE `regw_goo_id` '.$delivery_amount.' END,';
                $sql .= ' `regw_stock_quantity`=  CASE `regw_goo_id` '.$stock_quantity.' END,';
                $sql .= ' `regw_update_time`=  CASE `regw_goo_id` '.$update_time.' END ';
                $sql .= ' WHERE  `regw_goo_id` IN ('.trim($goods_id_str,',').') AND  `regw_shop_id` = '.$rerb_info->rerb_wd_shop_id;
                $regw_update = DB::update($sql);
            }else{
                $regw_update = true;
            }
            $dere_res = true;
        }else{
            // $reid_update = true;
            $derw_res = true;
            $debw_res = true;
            $regw_update = true;

            $shbi_id = DB::connection('mysql_scm')
                ->table('shipping_bill')
                ->where('shbi_shipping_number',$rebb_data->rebb_number)
                ->value('shbi_id');
            // 供应链补货账单表
            $shbi_sql = 'UPDATE `scm_shipping_bill` SET  `shbi_delivery_quantity`= `shbi_delivery_quantity`-' . $rerb_info->rerb_actual_send_amount .' , `shbi_no_replenishment`= `shbi_no_replenishment` + '.$rerb_info->rerb_actual_send_amount." ,shbi_replenish_state = 1,shbi_state =2 WHERE `shbi_id` = '".$shbi_id."'";
            $reid_update = DB::connection('mysql_scm')->update($shbi_sql);
            $sql = 'UPDATE `scm_shipping_bill_goods` SET ';
            $quantity_str = '';//已送
            $update_time = '';
            $ids = implode(',',$goods_id);
            foreach ($goods_id as $key => $value) {
                //已发送数量
                $quantity_str .= ' WHEN '.$value.' THEN `shbg_already_quantity` - '.$quantity[$key];
                // 更改时间
                $update_time .= ' WHEN '.$value.' THEN "'.date('Y-m-d H:i:s').'"';
            }
            $sql .= ' `shbg_already_quantity`=  CASE `shbg_rego_id` '.$quantity_str.' END,';
            $sql .= ' `shbg_update_time`=  CASE `shbg_rego_id` '.$update_time.' END';
            $sql .= ' WHERE  `shbg_rego_id` IN ('.trim($ids,',').') AND shbg_shbi_id ='.$shbi_id;
            $degw_update = DB::connection('mysql_scm')->update($sql);

            $dere_res = DB::connection('mysql_scm')
                ->table('delivery_record')
                ->where('dere_number',$rerb_info->rerb_number)
                ->update(['dere_state'=>4,'dere_update_time'=>date('Y-m-d H:i:s')]);
        }

        if($rrgb_res && $rerb_res && $supply_res && $derw_res && $debw_res && $reid_update && $regw_update && $degw_update && $rebi_res && $dere_res) {
            Common::addLog($user_info, getRealIp($request), '我的补货','补货账单','收货单:'.$rerb_info->rerb_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 scanCode(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        //扫码缓存
        if($request['type'] == 1){
            // 验证数据
            $verify_data = new VerifySupplyBillsController;
            $error_message = $verify_data->scanCodeValidator($request->all());
            if ($error_message) {
                return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
            }
            $data['sccb_rerb_id'] = $request['rerb_id'];
            $data['sccb_create_adm_id'] = $user_info->adm_id;
            $data['sccb_rebb_id'] = $request['rebb_id'];
            $data['sccb_cid'] = $user_info->adm_cid;
            $data['sccb_shop_id'] = $user_info->adm_shop_id;
            $data['sccb_code'] = $request['code'][0];
            $data['sccb_create_time'] = date('Y-m-d H:i:s');
            $insert_res = DB::table('scan_code_cache_bs')->insert($data);
            if(empty($insert_res)){
                return response()->json(['code'=> 500,'msg'=>'error','data'=>'扫描失败']);
            }
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'扫描成功']);
        }
        //提交
        if($request['type'] == 2){
            // 验证数据
            $verify_data = new VerifySupplyBillsController;
            $error_message = $verify_data->scanCodeValidator($request->all());
            if ($error_message) {
                return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
            }
            foreach ($request['code'] as $key => $value) {
                $data[$key]['sccb_rerb_id'] = $request['rerb_id'];
                $data[$key]['sccb_shop_id'] = $user_info->adm_shop_id;
                $data[$key]['sccb_code'] = $request['code'][$key];
                $data[$key]['sccb_create_time'] = date('Y-m-d H:i:s');
                $data['sccb_create_adm_id'] = $user_info->adm_id;
                $data['sccb_rebb_id'] = $request['rebb_id'];
                $data['sccb_cid'] = $user_info->adm_cid;
            }
            $insert_res = DB::table('scan_code_bs')->insert($data);
            if(empty($insert_res)){
                return response()->json(['code'=> 500,'msg'=>'error','data'=>'扫码收货失败']);
            }
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'扫码收货成功']);
        }
    }
}
