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

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\DistributorsManages\VerifyDispatchingBillsController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\Export;
use Illuminate\Support\Facades\Crypt;

//渠道配送账单
class DispatchingBillsController 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('deliver_bill_wd as dbw')
                        ->leftjoin('shop as s', 'dbw.debw_bs_shop_id', '=', 's.shop_id')
                        ->where('debw_cid', $user_info->adm_cid)
                        ->where('debw_superior_shop_id', $shop_id)
                        ->where(function($query) use($search_data) {
                        //如果选择开始时间并且选择结束时间
                            if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                            $query->whereBetween('debw_create_time', [$search_data['start_time'], $search_data['end_time'].' 23:59:59']);
                            } else{
                                // 如果选择开始时间
                                if (!empty($search_data['start_time'])) {
                                    $query->where('debw_create_time', '>=',$search_data['start_time']);
                                } else{
                                    // 如果选择结束时间
                                    if (!empty($search_data['end_time'])) {
                                        $query->where('debw_create_time', '<=',$search_data['end_time'].' 23:59:59');
                                    }
                                }
                            }
                        }) //添加时间
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['debw_shipping_number'])) {
                                $query->where('debw_shipping_number', 'like', $search_data['debw_shipping_number'].'%');
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['state'])) {
                                $query->where('debw_state', $search_data['state']);
                            }
                        })//账单状态1未确认2待审核3未完成4已完成5已驳回
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['shop_store_name'])) {
                                $query->where('shop_store_name', 'like', $search_data['shop_store_name'].'%');
                            }
                        })//门店名称
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['debw_replenish_state'])) {
                                $query->where('debw_replenish_state', $search_data['debw_replenish_state']);
                            }
                        })//补货进度
                        ->select('debw_id', 'debw_shipping_number', 'shop_store_name', 'debw_bill_amount', 'debw_delivery_amount', 'debw_no_replenishment', 'debw_delivery_order_quantity', 'debw_total_money', 'debw_remark', 'debw_replenish_state', 'debw_state', 'debw_create_time')
                        ->orderBy('debw_id', 'desc')
                        ->paginate($this->show_count);
        $state_count = DB::table('deliver_bill_wd')
            ->where('debw_cid', $user_info->adm_cid)
            ->where('debw_shop_id', $shop_id)
            ->select(DB::raw('count(*) as count, debw_state'))
            ->groupBy('debw_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 indexExport(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('deliver_bill_wd as dbw')
                        ->where('debw_cid', $user_info->adm_cid)
                        ->where('debw_superior_shop_id', $shop_id)
                        ->leftjoin('shop as s', 'dbw.debw_bs_shop_id', '=', 's.shop_id')
                        ->where(function($query) use($search_data) {
                        //如果选择开始时间并且选择结束时间
                            if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                            $query->whereBetween('debw_create_time', [$search_data['start_time'], $search_data['end_time'].' 23:59:59']);
                            } else{
                                // 如果选择开始时间
                                if (!empty($search_data['start_time'])) {
                                    $query->where('debw_create_time', '>=',$search_data['start_time']);
                                } else{
                                    // 如果选择结束时间
                                    if (!empty($search_data['end_time'])) {
                                        $query->where('debw_create_time', '<=',$search_data['end_time'].' 23:59:59');
                                    }
                                }
                            }
                        }) //添加时间
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['debw_shipping_number'])) {
                                $query->where('debw_shipping_number', 'like', $search_data['debw_shipping_number'].'%');
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['shop_store_name'])) {
                                $query->where('shop_store_name', 'like', $search_data['shop_store_name'].'%');
                            }
                        })//门店名称
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['debw_replenish_state'])) {
                                $query->where('debw_replenish_state', $search_data['debw_replenish_state']);
                            }
                        })//补货进度
                        ->select('debw_shipping_number', 'shop_store_name', 'debw_bill_amount', 'debw_delivery_amount', 'debw_no_replenishment', 'debw_delivery_order_quantity', 'debw_total_money', 'debw_remark', 'debw_replenish_state', 'debw_state', 'debw_create_time','debw_id')
                        ->orderBy('debw_id', 'desc')
                        ->get();
        if ($list_data) {
            // 将对象转化为数组
            $list_data = json_decode(json_encode($list_data),true);
            $debw_id = [];

            foreach ($list_data as $key => $value) {
                if ($value['debw_replenish_state'] == 1) {
                    $list_data[$key]['debw_replenish_state'] = '未补';
                } elseif ($value['debw_replenish_state'] == 2) {
                    $list_data[$key]['debw_replenish_state'] = '部分';
                } elseif ($value['debw_replenish_state'] == 3) {
                    $list_data[$key]['debw_replenish_state'] = '补全';
                }
                if ($value['debw_state'] == 1) {
                    $list_data[$key]['debw_state'] = '未确认';
                } else if ($value['debw_state'] == 2) {
                    $list_data[$key]['debw_state'] = '待审核';
                } else if ($value['debw_state'] == 3) {
                    $list_data[$key]['debw_state'] = '未完成';
                } else if ($value['debw_state'] == 4) {
                    $list_data[$key]['debw_state'] = '已完成';
                } else if ($value['debw_state'] == 5) {
                    $list_data[$key]['debw_state'] = '已驳回';
                }
                $list_data[$key]['degw_shipping_fee'] = $value['debw_total_money'] / 100;
                $debw_id[] = $value['debw_id'];
                unset($list_data[$key]['debw_id']);
            }

            $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      //导出数据
            );
            Common::addLog($user_info, getRealIp($request), '补货管理->配送账单', '导出', '导出id是:'.trim(', ',implode(',',$debw_id)));
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'storage/excel/'.$streamFileRand]);
        } else{
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    //配送账单添加备注
    public function remark(Request $request) 
    {
        // 验证数据
        $verify_data = new VerifyDispatchingBillsController;
        $error_message = $verify_data->remarkValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $data['debw_remark'] = $request['remark'];//备注
        $data['debw_update_time'] = date('Y-m-d H:i:s');//时间

        $res = DB::table('deliver_bill_wd')
            ->where('debw_id',$request['debw_id'])
            ->update($data);
        if (empty($res)) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'备注提交失败']);
        } else{
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            //配送账单号
            $debw_shipping_number = DB::table('deliver_bill_wd')
                ->where('debw_id',$request['debw_id'])
                ->value('debw_shipping_number');

            Common::addLog($user_info, getRealIp($request), '配送账单', '备注', '配送账单:'.$debw_shipping_number.' '.$request['remark'].'提交成功');
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'备注提交成功']); 
        }
    }

    //配送账单详情
    public function details(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyDispatchingBillsController;
        $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['list'] = DB::table('deliver_goods_wd')
                        ->where('degw_debw_id', $request['debw_id'])
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['degw_goo_name'])) {
                                $query->where('degw_goo_name', 'like', $search_data['degw_goo_name'].'%');
                            }
                        })//商品名称
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['degw_goo_encode'])) {
                                $query->where('degw_goo_encode', 'like', $search_data['degw_goo_encode'].'%');
                            }
                        })//补货进度
                        ->select('degw_goo_name', 'degw_goo_encode', 'degw_bra_name', 'degw_cate_name', 'degw_shipping_fee', 'degw_replenishment_quantity', 'degw_id','degw_shipment_state')
                        ->orderBy('degw_id', 'desc')
                        ->get();
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $list_data['shipping_name'] = DB::table('shop')
            ->where('shop_id',$user_info->adm_shop_id)
            ->value('shop_store_name');
        if(!empty($list_data['list'])){
            foreach ($list_data['list'] as $key => $value) {
                $list_data['list'][$key]->degw_shipping_fee = $value->degw_shipping_fee / 100;
            }
        }
        if ($list_data) {
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>$list_data]);
        } else{
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    //配送账单详情导出
    public function detailsExport(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyDispatchingBillsController;
        $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('deliver_goods_wd')
                        ->where('degw_debw_id', $request['debw_id'])
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['degw_goo_name'])) {
                                $query->where('degw_goo_name', 'like', $search_data['degw_goo_name'].'%');
                            }
                        })//商品名称
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['degw_goo_encode'])) {
                                $query->where('degw_goo_encode', 'like', $search_data['degw_goo_encode'].'%');
                            }
                        })//补货进度
                        ->select('degw_goo_name', 'degw_goo_encode', 'degw_bra_name', 'degw_cate_name', 'degw_shipping_fee', 'degw_replenishment_quantity')
                        ->orderBy('degw_id', 'desc')
                        ->get();

        if ($list_data) {
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            // 将对象转化为数组
            $list_data = json_decode(json_encode($list_data),true);
            $degw_id = [];
            foreach ($list_data as $key => $value) {
                $list_data[$key]['degw_shipping_fee'] = $value['degw_shipping_fee'] / 100;
                $degw_id[] = $value['degw_id'];
            }
            $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      //导出数据
            );
            Common::addLog($user_info, getRealIp($request), '补货管理->详情', '导出', '导出id是:'.trim(', ',implode(',',$degw_id)));
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'storage/excel/'.$streamFileRand]);
        } else{
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    //配送账单列表详情配送状态修改(账单确认)
    public function shipmentState(Request $request) 
    {
        // 验证数据
        $verify_data = new VerifyDispatchingBillsController;
        $error_message = $verify_data->shipmentStateShowValidator($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('deliver_goods_wd')
                            ->where('degw_debw_id', $request['debw_id'])
                            ->where(function($query) use($search_data) {
                                if (!empty($search_data['degw_goo_name'])) {
                                    $query->where('degw_goo_name', 'like', $search_data['degw_goo_name'].'%');
                                }
                            })//商品名称
                            ->where(function($query) use($search_data) {
                                if (!empty($search_data['degw_goo_encode'])) {
                                    $query->where('degw_goo_encode', 'like', $search_data['degw_goo_encode'].'%');
                                }
                            })//补货进度
                            ->select('degw_goo_name', 'degw_goo_encode', 'degw_bra_name', 'degw_cate_name', 'degw_shipping_fee', 'degw_replenishment_quantity', 'degw_shipment_state', 'degw_id')
                            ->orderBy('degw_id', 'desc')
                            ->get();
            if ($list_data) {
                foreach ($list_data as $key => $value) {
                    $list_data[$key]->degw_shipping_fee = $value->degw_shipping_fee / 100;
                }
                return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>$list_data]);
            } else{
                return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'暂无数据']);
            }
        }

        // 验证数据
        $verify_data = new VerifyDispatchingBillsController;
        $error_message = $verify_data->shipmentStateValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $time = date('Y-m-d H:i:s');

        //配送账单单号
        $debw_data = DB::table('deliver_bill_wd')
            ->where('debw_id',$request['debw_id'])
            ->first(['debw_shipping_number','debw_state']);
        if($debw_data->debw_state == 2 || $debw_data->debw_state == 3 || $debw_data->debw_state == 4){
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'此账单不是未确认或者已驳回状态']);
        }
        DB::beginTransaction();
        DB::connection('mysql_scm')->beginTransaction();

        $data_degw['degw_shipment_state'] = 1;
        $data_degw['degw_update_time'] = date('Y-m-d H:i:s');
        $update_state = DB::table('deliver_goods_wd')
            ->where('degw_debw_id',$request['debw_id'])
            ->where('degw_shipment_state',2)
            ->update($data_degw);

        //供应链补货账单
        $rebi_id = DB::connection('mysql_scm')
                ->table('relationship_bill')
                ->where('rebi_sd_replenishment_number',$debw_data->debw_shipping_number)
                ->value('rebi_id');

        if(!empty($request['degw_id']))
        {
            //修改账单状态
            $rebi_res = DB::connection('mysql_scm')
                ->table('relationship_bill')
                ->where('rebi_sd_replenishment_number',$debw_data->debw_shipping_number)
                ->update(['rebi_state'=>2,'rebi_update_time'=>$time]);

            $data['degw_shipment_state'] = 2;
            $data['degw_update_time'] = date('Y-m-d H:i:s');
            $update_state = DB::table('deliver_goods_wd')
                ->whereIn('degw_id',$request['degw_id'])
                ->update($data);
            $sd_goo_id = DB::table('deliver_goods_wd')
                ->whereIn('degw_id',$request['degw_id'])
                ->pluck('degw_sd_goo_id','degw_id');
            //供应链补货账单
            $rebi_state_on = DB::connection('mysql_scm')
                ->table('relationship_bill_goods')
                ->where('rebg_rebi_id',$rebi_id)
                ->where('rebg_replenishment_state',2)
                ->update(['rebg_replenishment_state'=>1,'rebg_update_time'=>$time]);
            $rebi_state_off = DB::connection('mysql_scm')
                ->table('relationship_bill_goods')
                ->where('rebg_rebi_id',$rebi_id)
                ->whereIn('rebg_sd_goo_id',$sd_goo_id)
                ->update(['rebg_replenishment_state'=>2,'rebg_update_time'=>$time]);

            //渠道配送账单状态
            $debw_res = DB::table('deliver_bill_wd')
                ->where('debw_id',$request['debw_id'])
                ->update(['debw_state'=>2,'debw_update_time'=>$time]);
        }else{
            $update_state = true;
            $rebi_state_off = true;
            //修改账单状态
            $rebi_res = DB::connection('mysql_scm')
                ->table('relationship_bill')
                ->where('rebi_sd_replenishment_number',$debw_data->debw_shipping_number)
                ->update(['rebi_state'=>3,'rebi_update_time'=>$time]);
            //渠道配送账单状态
            $debw_res = DB::table('deliver_bill_wd')
                ->where('debw_id',$request['debw_id'])
                ->update(['debw_state'=>3,'debw_update_time'=>$time]);
        }
        if ($update_state && $debw_res && $rebi_res  && $rebi_state_off) {
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            Common::addLog($user_info, getRealIp($request), '补货管理->配送账单', '账单确认', '配送账单:'.$debw_data->debw_shipping_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 deliveryList(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyDispatchingBillsController;
        $error_message = $verify_data->deliveryListValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $search_data = $request->all();
        $list_data = DB::table('deliver_record_wd')
                        ->where('derw_debw_id', $request['dewd_id'])
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['derw_number'])) {
                                $query->where('derw_number', 'like', $search_data['derw_number'].'%');
                            }
                        })//商品名称
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['derw_state'])) {
                                $query->where('derw_state', $search_data['derw_state']);
                            }
                        })//补货进度
                        ->where(function($query) use($search_data) {
                        //如果选择开始时间并且选择结束时间
                            if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                            $query->whereBetween('derw_create_time',[$search_data['start_time'],$search_data['end_time'].' 23:59:59']);
                            } else{
                                // 如果选择开始时间
                                if (!empty($search_data['start_time'])) {
                                    $query->where('derw_create_time', '>=',$search_data['start_time']);
                                } else{
                                    // 如果选择结束时间
                                    if (!empty($search_data['end_time'])) {
                                        $query->where('derw_create_time', '<=',$search_data['end_time'].' 23:59:59');
                                    }
                                }
                            }
                        }) //添加时间
                        ->select('derw_create_time', 'derw_number', 'derw_total_shipping_fee', 'derw_plan_send_amount', 'derw_actual_send_amount', 'derw_remark', 'derw_state', 'derw_id')
                        ->orderBy('derw_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 deliveryDetails(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyDispatchingBillsController;
        $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('deliver_record_goods_wd')
                        ->where('drgw_derw_id', $request['derw_id'])
                        ->select('drgw_goo_name', 'drgw_goo_encode', 'drgw_cate_name', 'drgw_bra_name', 'drgw_actual_send_quantity', 'drgw_plan_send_quantity', 'drgw_shipping_fee')
                        ->orderBy('drgw_id', 'desc')
                        ->get();
        if ($list_data) {
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>$list_data]);
        } else{
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    //配送账单送货单添加备注
    public function deliveryRemark(Request $request) 
    {
        // 验证数据
        $verify_data = new VerifyDispatchingBillsController;
        $error_message = $verify_data->deliveryRemarkValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $data['derw_remark'] = $request['remark'];//备注
        $data['derw_update_time'] = date('Y-m-d H:i:s');//时间

        $res = DB::table('deliver_record_wd')
            ->where('derw_id',$request['derw_id'])
            ->update($data);
        if (empty($res)) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'添加备注失败']);
        } else{
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            //送货账单号
            $derw_number = DB::table('deliver_record_wd')
                ->where('derw_id',$request['derw_id'])
                ->value('derw_number'); 
            Common::addLog($user_info, getRealIp($request), '配送账单->送货单', '备注', '配送账单:'.$derw_number.' '.$request['remark'].'提交成功');
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'备注提交成功']);
        }
    }

    //账单撤回确认
    public function recall(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyDispatchingBillsController;
        $error_message = $verify_data->recallValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        //配送单信息
        $debw_info = DB::table('deliver_bill_wd')
                ->where('debw_id',$request['debw_id'])
                ->first(['debw_shipping_number', 'debw_state']);
        if ($debw_info->debw_state != 2) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'该账单不是待审核状态']);
        }

        DB::beginTransaction();
        $time = date('Y-m-d H:i:s');
        $debw_data['debw_state'] = 1;//待审核
        $debw_data['debw_update_time'] = $time;//待审核
        //配送单状态
        $debw_state = DB::table('deliver_bill_wd')
                ->where('debw_id',$request['debw_id'])
                ->update($debw_data);
        $degw_state = DB::table('deliver_goods_wd')
            ->where('degw_debw_id',$request['debw_id'])
            ->update(['degw_shipment_state'=>1,'degw_update_time'=>$time]);

         //供应链补货账单id
        $rebi_id = DB::connection('mysql_scm')
                ->table('relationship_bill')
                ->where('rebi_sd_replenishment_number',$debw_info->debw_shipping_number)
                ->value('rebi_id');
        //供应链补货账单
        $rebi_res = DB::connection('mysql_scm')
                ->table('relationship_bill')
                ->where('rebi_id',$rebi_id)
                ->update(['rebi_state'=>1,'rebi_update_time'=>$time]);

        $rebg_res = DB::connection('mysql_scm')
                ->table('relationship_bill_goods')
                ->where('rebg_rebi_id',$rebi_id)
                ->update(['rebg_replenishment_state'=>1,'rebg_update_time'=>$time]);
        if (empty($debw_state) || empty($rebi_res) || empty($degw_state) || empty($rebg_res)) {
            DB::rollBack();
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'配送账单撤销失败']);
        } else{
            Common::addLog($user_info, getRealIp($request), '补货管理', '配送账单', '配送账单:'.$debw_info->debw_shipping_number.'撤销确认');
            DB::commit();
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'配送账单撤销成功']);
        }
    }

    //配送账单送货单列表新增送货单
    public function deliveryAdd(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyDispatchingBillsController;
        $error_message = $verify_data->deliveryAddShowValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        //配送单状态
        $debw_data = DB::table('deliver_bill_wd')
            ->where('debw_id',$request['debw_id'])
            ->first(['debw_state','debw_bill_amount','debw_shipping_number','debw_bs_shop_id']);
        if ($debw_data->debw_state != 3) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'账单不是未完成状态不能添加发货单']);
        }
        //获取信息
        if ($request['type'] == 1) {
            $degw_data = DB::table('deliver_goods_wd')
                ->where('degw_debw_id',$request['debw_id'])
                ->where('degw_shipment_state',1)//配送状态可以配送
                ->get(['degw_goo_name', 'degw_goo_encode', 'degw_bra_name', 'degw_replenishment_quantity', 'degw_id', 'degw_cate_name','degw_shipping_fee','degw_already_quantity']);
            if(!empty($degw_data)){
                foreach ($degw_data as $key => $value) {
                    $num = $value->degw_replenishment_quantity - $value->degw_already_quantity;
                    if($num == 0){
                        unset($degw_data[$key]);
                    }else{
                        $degw_data[$key]->degw_replenishment_quantity = $num;
                        $degw_data[$key]->degw_shipping_fee = $value->degw_shipping_fee / 100;
                    }
                }
            }
            $data = [];
            foreach ($degw_data as $key => $value) {
                $data[] = $value;
            }
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>$data]);
        }
        // 验证数据
        $verify_data = new VerifyDispatchingBillsController;
        $error_message = $verify_data->deliveryAddValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        //验证数据
        foreach ($request['degw_id'] as $key => $value) {
            if(!is_numeric($value) || !is_numeric($request['quantity'][$key])){
                return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误']);
            }
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        DB::beginTransaction();
        DB::connection('mysql_scm')->beginTransaction();
        $degw_data = DB::table('deliver_goods_wd')
            ->whereIn('degw_id',$request['degw_id'])
            ->get(['degw_goo_name', 'degw_goo_encode', 'degw_bra_name', 'degw_replenishment_quantity', 'degw_id', 'degw_cate_name', 'degw_shipping_fee', 'degw_goo_id','degw_sd_goo_id']);
        if (empty($degw_data)) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误']);
        }
        $sql = 'UPDATE `faster_deliver_goods_wd` SET ';
        $quantity = '';//已送
        $update_time = '';
        $ids = implode(',',$request['degw_id']);
        foreach ($request['degw_id'] as $key => $value) {
            //在途数量
            $quantity .= ' WHEN '.$value.' THEN `degw_already_quantity` + '.$request['quantity'][$key];
            // 更改时间
            $update_time .= ' WHEN '.$value.' THEN "'.date('Y-m-d H:i:s').'"';
        }
        if(!empty($quantity)){
            $sql .= ' `degw_already_quantity`=  CASE `degw_id` '.$quantity.' END,';
            $sql .= ' `degw_update_time`=  CASE `degw_id` '.$update_time.' END';
            $sql .= ' WHERE  `degw_id` IN ('.trim($ids,',').')';
            $degw_update = DB::update($sql);
        }else{
            $degw_update = true;
        }

        $plan_total_num = 0;//计划数量
        $total_shipping_fee = 0;//配送费
        $actual_total_num = 0;//实际数量
        $goods_id = []; 

        foreach ($degw_data as $key => $value) {
            // 渠道配送账单送货单商品表
            $drgw_data[$key]['drgw_goo_id'] = $value->degw_goo_id;
            $drgw_data[$key]['drgw_sd_goo_id'] = $value->degw_sd_goo_id;
            $drgw_data[$key]['drgw_goo_name'] = $value->degw_goo_name;
            $drgw_data[$key]['drgw_goo_encode'] = $value->degw_goo_encode;
            $drgw_data[$key]['drgw_cate_name'] = $value->degw_cate_name;
            $drgw_data[$key]['drgw_bra_name'] = $value->degw_bra_name;
            // $drgw_data[$key]['drgw_actual_send_quantity'] = $request['quantity'][$key];//实际数量
            $drgw_data[$key]['drgw_shipping_fee'] = $value->degw_shipping_fee;
            $drgw_data[$key]['drgw_plan_send_quantity'] = $request['quantity'][$key];//计划数量
            $drgw_data[$key]['drgw_state'] = 1;
            $actual_total_num += $request['quantity'][$key]; 
            $total_shipping_fee += $value->degw_shipping_fee * $request['quantity'][$key]; 
            $plan_total_num += $value->degw_replenishment_quantity;

            // 门店补货账单商品表
            $regb_data[$key]['regb_goo_id'] = $value->degw_goo_id;
            $regb_data[$key]['regb_sd_goo_id'] = $value->degw_sd_goo_id;
            $regb_data[$key]['regb_goo_name'] = $value->degw_goo_name;
            $regb_data[$key]['regb_goo_encode'] = $value->degw_goo_encode;
            $regb_data[$key]['regb_cate_name'] = $value->degw_cate_name;
            $regb_data[$key]['regb_bra_name'] = $value->degw_bra_name;
            $regb_data[$key]['regb_goo_quantity'] = $request['quantity'][$key];

            // 门店补货账单收货单商品信息
            $rrgb_data[$key]['rrgb_goo_id'] = $value->degw_goo_id;
            $rrgb_data[$key]['rrgb_sd_goo_id'] = $value->degw_sd_goo_id;
            $rrgb_data[$key]['rrgb_goo_name'] = $value->degw_goo_name;
            $rrgb_data[$key]['rrgb_goo_encode'] = $value->degw_goo_encode;
            $rrgb_data[$key]['rrgb_cate_name'] = $value->degw_cate_name;
            $rrgb_data[$key]['rrgb_bra_name'] = $value->degw_bra_name;
            $rrgb_data[$key]['rrgb_plan_send_quantity'] = $request['quantity'][$key];
            // $rrgb_data[$key]['rrgb_actual_send_quantity'] = ;
            $rrgb_data[$key]['rrgb_shipping_fee'] = $value->degw_shipping_fee;
            $rrgb_data[$key]['rrgb_state'] = 1;
            //用于添加新商品
            $goods_id[] = $value->degw_goo_id;
            $sd_goods_id[] = $value->degw_sd_goo_id;
            $goo_name[] = $value->degw_goo_name;
            $goo_encode[] = $value->degw_goo_encode;
            $cate_name[] = $value->degw_cate_name;
            $bra_name[] = $value->degw_bra_name;
        }
        $number = 'SH'.date('YmdHis').rand(1000,9999);//待定
        $derw['derw_debw_id'] = $request['debw_id'];//渠道配送账单送货单id
        $derw['derw_number'] = $number;//渠道配送账单送货单号
        $derw['derw_plan_send_amount'] = $actual_total_num;//发送量
        $derw['derw_total_shipping_fee'] = $total_shipping_fee;
        $derw['derw_state'] = 1;
        $derw['derw_create_adm_id'] = $user_info->adm_id;
        // 渠道配送账单送货单表
        $derw_id = DB::table('deliver_record_wd')->insertGetid($derw);
        foreach ($drgw_data as $key => $value) {
            $drgw_data[$key]['drgw_derw_id'] = $derw_id;
        }
        //渠道配送账单送货单商品表
        $res = DB::table('deliver_record_goods_wd')->insert($drgw_data);

        // 判断账单是否补全  已送货数量 = 账单总量
        if($debw_data->debw_bill_amount == $actual_total_num){
            $debw_replenish_state = 3;
        }else{
            $debw_replenish_state = 2;
        }
        // 修改配送账单数量
        $debw_sql = 'UPDATE `faster_deliver_bill_wd` SET  `debw_delivery_amount`= `debw_delivery_amount`+' . $actual_total_num .' ,`debw_no_replenishment`=`debw_no_replenishment`-'.$actual_total_num.',`debw_delivery_order_quantity`= `debw_delivery_order_quantity`+1, `debw_replenish_state`= '.$debw_replenish_state.' WHERE `debw_id` ='.$request['debw_id'];
        $debw_increment = DB::update($debw_sql);

        //商品id字符串
        $goods_id_str = implode(',',$goods_id);
        // //渠道补货商品表
        // $sql = 'UPDATE `faster_replenishment_goods_wd` SET ';
        // $stock_quantity = '';//库存数量
        // $delivery_amount = '';//累计数量
        // $update_time = '';//修改时间
        // $stock_type = '';//库存正负

        // //获取待补商品数据
        // $regw_data = collect(DB::table('replenishment_goods_wd')
        //     ->whereIn('regw_goo_id',$goods_id)
        //     ->where('regw_shop_id',$user_info->adm_shop_id)
        //     ->get(['regw_stock_type', 'regw_stock_quantity', 'regw_goo_id']))
        //     ->keyBy('regw_goo_id')
        //     ->toArray();

        // foreach ($goods_id as $key => $value) {
        //     //如果待补商品里有此数据
        //     if(isset($regw_data[$value])){
        //         $num = $request['quantity'][$key];
        //         // 判断库存是为负数
        //         if($regw_data[$value]->regw_stock_type == 3){
        //             $stock_quantity .= ' WHEN '.$value.' THEN `regw_stock_quantity` + '.$num;
        //         //库存数量为平
        //         }else if($regw_data[$value]->regw_stock_type == 1){
        //             //库存数量
        //             $stock_quantity .= ' WHEN '.$value.' THEN `regw_stock_quantity` + '.$num;
        //             $stock_type .= ' WHEN '.$value.' THEN 2';
        //         //库存数量为正
        //         }else if($regw_data[$value]->regw_stock_type == 2){
        //             if($regw_data[$value]->regw_stock_quantity > $num){
        //                 //库存数量
        //                 $stock_quantity .= ' WHEN '.$value.' THEN `regw_stock_quantity` - '.$num;
        //             }
        //             if($regw_data[$value]->regw_stock_quantity == $num){
        //                 //库存数量
        //                 $stock_quantity .= ' WHEN '.$value.' THEN `regw_stock_quantity` - '.$num;
        //                 $stock_type .= ' WHEN '.$value.' THEN 1';
        //             }
        //             if($regw_data[$value]->regw_stock_quantity < $num){
        //                 $num = $num - $regw_data[$value]->regw_stock_quantity - $regw_data[$value]->regw_stock_quantity;
        //                 //库存数量
        //                 $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').'"';
        //     }
        // }
        // if(!empty($stock_quantity)){
        //     $sql .= ' `regw_stock_quantity`=  CASE `regw_goo_id` '.$stock_quantity.' 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_update_time`=  CASE `regw_goo_id` '.$update_time.' END';
        //     $sql .= ' WHERE  `regw_goo_id` IN ('.trim($goods_id_str,',').') AND  `regw_shop_id` = '.$user_info->adm_shop_id;
        //     $regw_update = DB::update($sql);
        // }else{
        //     $regw_update = true;
        // }

        //门店相关数据修改  
        //渠道信息
        $channel_data = DB::connection('mysql_scm')
                ->table('channel')
                ->where('chan_shop_id',$debw_data->debw_bs_shop_id)
                ->first(['chan_cid','chan_shop_id']);
        //获取门店信息
        $shop_data = DB::table('shop')
            ->where('shop_id',$channel_data->chan_shop_id)
            ->where('shop_cid',$channel_data->chan_cid)
            ->first(['shop_cid', 'shop_superior_id', 'shop_id']);
        if(empty($shop_data)){
            return response()->json(["code"=>500, 'msg'=>'error', 'data'=>'配送门店中没有此门店']);
        }
        $shop_id = $shop_data->shop_superior_id ? $shop_data->shop_superior_id : $shop_data->shop_id;
        $shop_wd_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
                //查询门店补货账单是否有此收货单
        $rebb_id = DB::table('replenish_bill_bs')
            ->where('rebb_number',$debw_data->debw_shipping_number)
            ->value('rebb_id');
        if (empty($rebb_id)) {
            $rebb_data['rebb_shop_id'] = $shop_data->shop_id;//门店id
            $rebb_data['rebb_shop_superior_id'] = $shop_id;//总店id
            $rebb_data['rebb_cid'] = $shop_data->shop_cid;//公司id
            $rebb_data['rebb_shipping_number'] = $debw_data->debw_shipping_number;//补货账单号
            $rebb_data['rebb_number'] = $debw_data->debw_shipping_number;//配送账单号
            $rebb_data['rebb_bill_amount'] = $debw_data->debw_bill_amount;//账单总量
            $rebb_data['rebb_delivery_amount'] = $actual_total_num;//已送货数量
            $rebb_data['rebb_no_replenishment'] = $debw_data->debw_bill_amount;//未补货数量
            $rebb_data['rebb_delivery_order_quantity'] = 1;//送货单数量
            $rebb_data['rebb_replenish_state'] = 1;//补货进度1未补2部分3补全
            $rebb_data['rebb_state'] = 1;//账单状态1未完成2已完成3已核销
            $rebb_data['rebb_total_money'] = $total_shipping_fee;//配送费
            $rebb_id = DB::table('replenish_bill_bs')->insertGetid($rebb_data);

            foreach ($regb_data as $key => $value) {
                $regb_data[$key]['regb_rebb_id'] = $rebb_id;
            }
            $regb_res = DB::table('replenish_goods_bs')->insert($regb_data);

            $rerb_data['rerb_rebb_id'] = $rebb_id;//补货账单id
            $rerb_data['rerb_number'] = $number;//补货账单id
            $rerb_data['rerb_wd_shop_id'] = $user_info->adm_shop_id;//门店的配送商id
            $rerb_data['rerb_plan_send_amount'] = $actual_total_num;//计划总数量
            $rerb_data['rerb_total_shipping_fee'] = $total_shipping_fee;//计划总数量
            $rerb_data['rerb_state'] = 1;//状态1待收货2已完成3已撤销
            $rerb_data['rerb_deliver_type'] = 2;//发货类型1速电发货2配送商发货
            $rerb_id = DB::table('replenish_record_bs')->insertGetid($rerb_data);
            foreach ($rrgb_data as $key => $value) {
                $rrgb_data[$key]['rrgb_rerb_id'] = $rerb_id;
            }
            $rrgb_res = DB::table('replenish_record_goods_bs')->insert($rrgb_data);
            $rebb_update = true;
            $regb_insert_res = true;
        } else{
            //门店补货账单商品表
            $regb_info = collect(DB::table('replenish_goods_bs')
                ->whereIn('regb_goo_id',$goods_id)
                ->where('regb_rebb_id',$rebb_id)
                ->get(['regb_goo_id', 'regb_goo_quantity']))
                ->keyBy('regb_goo_id')
                ->toArray();
            // 门店补货账单表
            $rebb_sql = 'UPDATE `faster_replenish_bill_bs` SET `rebb_delivery_amount` = `rebb_delivery_amount` + '.$actual_total_num.',`rebb_total_money` = `rebb_total_money`+'.$total_shipping_fee.',`rebb_delivery_order_quantity`= `rebb_delivery_order_quantity` + 1, `rebb_replenish_state`= 2 WHERE `rebb_id` ='.$rebb_id;
            $rebb_update = DB::update($rebb_sql);
            $regb_goo_id = [];
            $i = 0;
            $goo_quantity = '';
            $sql = 'UPDATE `faster_replenish_goods_bs` SET ';
            foreach ($regb_data as $key => $value) {
                if (isset($regb_info[$value['regb_goo_id']])) {
                    $goo_quantity .= ' WHEN '.$value['regb_goo_id'].' THEN `regb_goo_quantity` + '.$value['regb_goo_quantity'];
                    $regb_goo_id[] = $value['regb_goo_id'];
                } else {
                    $regb_insert_data[$i] = $value;
                    $i++;
                }
            }
            if (!empty($regb_goo_id)) {
                $sql .= ' `regb_goo_quantity`=  CASE `regb_goo_id` '.$goo_quantity.' END';
                $sql .= ' WHERE  `regb_goo_id` IN ('.implode($regb_goo_id, ', ').') AND  `regb_rebb_id` = '.$rebb_id;
                $regb_res = DB::update($sql);
            }else{
                $regb_res = true;
            }

            if(!empty($regb_insert_data)){
                $regb_insert_res = DB::table('replenish_goods_bs')->insert($regb_insert_data);
            }else{
                $regb_insert_res = true;
            }
            $rerb_data['rerb_rebb_id'] = $rebb_id;//补货账单id
            $rerb_data['rerb_number'] = $number;//补货账单id
            // $rerb_data['rerb_actual_send_amount'] = $actual_total_num;//发送总数量
            $rerb_data['rerb_plan_send_amount'] = $actual_total_num;//计划总数量
            $rerb_data['rerb_total_shipping_fee'] = $total_shipping_fee;//计划总数量
            $rerb_data['rerb_state'] = 1;//状态1待收货2已完成3已撤销
            $rerb_data['rerb_deliver_type'] = 2;//发货类型1速电发货2配送商发货
            $rerb_data['rerb_wd_shop_id'] = $user_info->adm_shop_id;//门店的配送商id
            $rerb_id = DB::table('replenish_record_bs')->insertGetid($rerb_data);
            foreach ($rrgb_data as $key => $value) {
                $rrgb_data[$key]['rrgb_rerb_id'] = $rerb_id;
            }
            $rrgb_res = DB::table('replenish_record_goods_bs')->insert($rrgb_data);
        }
        //门店待补货商品表
        $regb_info = collect(DB::table('replenishment_goods_bs')
            ->whereIn('regb_goo_id',$goods_id)
            ->where('regb_shop_id',$channel_data->chan_shop_id)
            ->get(['regb_goo_id', 'regb_enroute_amount','regb_sd_goo_id']))
            ->keyBy('regb_goo_id')
            ->toArray();
        //门店待补商品更新
        $sql = 'UPDATE `faster_replenishment_goods_bs` SET ';
        $enroute_amount = '';//在途数量 
        $stock_quantity = '';//待补数量 
        $repl_data = [];

        foreach ($rrgb_data as $key => $value) {
            if (!isset($regb_info[$value['rrgb_goo_id']])) {
                $repl_data[$key]['regb_cid'] = $shop_data->shop_cid;//公司id
                $repl_data[$key]['regb_shop_id'] = $shop_data->shop_id;//门店id
                $repl_data[$key]['regb_shop_superior_id'] = $shop_id;//总店id
                $repl_data[$key]['regb_goo_id'] = $value['rrgb_goo_id'];//商品id
                $repl_data[$key]['regb_sd_goo_id'] = $value['rrgb_sd_goo_id'];//商品id
                $repl_data[$key]['regb_goo_name'] = $value['rrgb_goo_name'];//商品名称
                $repl_data[$key]['regb_goo_encode'] = $value['rrgb_goo_encode'];//检索编号
                $repl_data[$key]['regb_cate_name'] = $value['rrgb_cate_name'];//品类名称
                $repl_data[$key]['regb_bra_name'] = $value['rrgb_bra_name'];//品牌名称
                $repl_data[$key]['regb_bra_name'] = $value['rrgb_bra_name'];//品牌名称
                $repl_data[$key]['regb_enroute_amount'] = $value['rrgb_plan_send_quantity'];//在途数量
                $repl_data[$key]['regb_stock_type'] = 1;//库存类型1平2正3负
            } else {
                //在途数量
                $enroute_amount .= ' WHEN '.$value['rrgb_goo_id'].' THEN `regb_enroute_amount` + '.$value['rrgb_plan_send_quantity'];
            }
        }
        if (!empty($enroute_amount)) {
            $sql .= ' `regb_enroute_amount`=  CASE `regb_goo_id` '.$enroute_amount.' END';
            $sql .= ' WHERE  `regb_goo_id` IN ('.trim($goods_id_str, ', ').') AND  `regb_shop_id` = '.$debw_data->debw_bs_shop_id;
            $repl_res = DB::update($sql);
        }else{
            $repl_res = true;
        }
        if(!empty($repl_data)){
            //待补商品里没有此商品新增
            $repl_insert_res = DB::table('replenishment_goods_bs')->insert($repl_data);
        }else{
            $repl_insert_res = true;
        }

        // 供应链配送商库存相关数据
        $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']);
        //配送商库存商品表
        $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平
        $enroute_quantity = '';//在途数量
        $insert_reid = [];
        foreach ($goods_id as $key => $value) {
            $num = $request['quantity'][$key];
            if(!isset($reid_data[$value]->reid_type)){
                $insert_reid[$key]['reid_sd_goo_id'] = $sd_goods_id[$key];//商品id
                $insert_reid[$key]['reid_rego_id'] = $value;//商品id
                $insert_reid[$key]['reid_rein_id'] = $rein_data->rein_id;//补货库存id
                $insert_reid[$key]['reid_goo_name'] = $goo_name[$key];//商品名称
                $insert_reid[$key]['reid_goo_encode'] = $goo_encode[$key];//商品编码
                $insert_reid[$key]['reid_cate_name'] = $cate_name[$key];//品类名称
                $insert_reid[$key]['reid_bra_name'] = $bra_name[$key];//品牌名称
                $insert_reid[$key]['reid_type'] = 3;//品牌名称
                $insert_reid[$key]['reid_enroute_quantity'] = $request['quantity'][$key];//在途数量
                // $insert_reid[$key]['reid_stock_quantity'] = $request['quantity'][$key];//库存数量
                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;
            //     }
            //     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 == 2){
            //     $stock_quantity .= ' WHEN '.$value.' THEN `reid_stock_quantity` + '.$num;
            // }
            //在途数量
            $enroute_quantity .= ' WHEN '.$value.' THEN `reid_enroute_quantity` + '.$num;
        }
        if(!empty($enroute_quantity)){
            if(!empty($stock_type)){
                $sql .= ' `reid_type`=  CASE `reid_rego_id` '.$stock_type.' END,';
            }
            $sql .= ' `reid_enroute_quantity`=  CASE `reid_rego_id` '.$enroute_quantity.' 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(!empty($insert_reid)){
            $insert_reid_res = DB::connection('mysql_scm')
                                ->table('relationship_inventory_detail')
                                ->insert($insert_reid);
        }else{
            $insert_reid_res = true;
        }

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

        //wd补货商品数据
        $regw_info = collect(DB::table('replenishment_goods_wd')
            ->whereIn('regw_goo_id',$goods_id)
            ->where('regw_shop_id',$user_info->adm_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 = '';//待补数量
        $enroute_amount = '';//在途数量
        $update_time = '';//修改时间
        $stock_type = '';//库存正负
        $ids = '';
        $insert_goo_data = [];
        foreach ($rrgb_data as $key => $value) {
            //如果待补商品里有此数据
            if(isset($regw_info[$value['rrgb_goo_id']])){
                $num = $value['rrgb_plan_send_quantity'];
                //在途数量
                $enroute_amount .= ' WHEN '.$value['rrgb_goo_id'].' THEN `regw_enroute_amount` + '.$num;
                // 更改时间
                $update_time .= ' WHEN '.$value['rrgb_goo_id'].' THEN "'.date('Y-m-d H:i:s').'"';
            }else{
                $insert_goo_data[$key]['regw_goo_id'] = $value['rrgb_goo_id'];
                $insert_goo_data[$key]['regw_goo_name'] = $value['rrgb_goo_name'];
                $insert_goo_data[$key]['regw_goo_encode'] = $value['rrgb_goo_encode'];
                $insert_goo_data[$key]['regw_cate_name'] = $value['rrgb_cate_name'];
                $insert_goo_data[$key]['regw_bra_name'] = $value['rrgb_bra_name'];
                $insert_goo_data[$key]['regw_enroute_amount'] = $value['rrgb_plan_send_quantity'];
                $insert_goo_data[$key]['regw_stock_type'] = 1;
                $insert_goo_data[$key]['regw_shop_superior_id'] = $shop_wd_id;
                $insert_goo_data[$key]['regw_shop_id'] = $user_info->adm_shop_id;
                $insert_goo_data[$key]['regw_cid'] = $user_info->adm_cid;
            }
        }
        if(!empty($enroute_amount)){
            $sql .= ' `regw_enroute_amount`=  CASE `regw_goo_id` '.$enroute_amount.' 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` = '.$user_info->adm_shop_id;
            $rrgw_update = DB::update($sql);
        }else{
            $rrgw_update = true;
        }
        //待补商品里没有此商品新增
        if(!empty($insert_goo_data)){
            $insert_res = DB::table('replenishment_goods_wd')->insert($insert_goo_data);
        }else{
            $insert_res = true;
        }

        if ($res && $derw_id && $debw_increment && $rebb_update && $rrgb_res && $regb_res && $repl_res && $repl_insert_res && $regb_insert_res && $scm_rebi_res && $reid_update && $insert_reid_res && $insert_res && $rrgw_update && $degw_update) {
            DB::commit();
            DB::connection('mysql_scm')->commit();
            Common::addLog($user_info, getRealIp($request), '补货管理', '配送账单', '配送账单：'.$debw_data->debw_shipping_number.'添加送货单('.$number.')');
            return response()->json(["code"=>200, 'msg'=>'success', 'data'=>'添加送货单成功']);
        } else {
            DB::rollBack();
            DB::connection('mysql_scm')->rollBack();
            return response()->json(["code"=>500, 'msg'=>'error', 'data'=>'添加送货单失败']);
        } 
    }

    //配送账单撤回
    public function detailsRevocation(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyDispatchingBillsController;
        $error_message = $verify_data->detailsRevocationValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $derw_data = DB::table('deliver_record_wd')
            ->where('derw_id',$request['derw_id'])
            ->first(['derw_number','derw_debw_id']);
        $rerb_state = DB::table('replenish_record_bs')
            ->where('rerb_number',$derw_data->derw_number)
            ->value('rerb_state');
        if ($rerb_state == 2 || $rerb_state == 3) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'门店收货单已完成']);
        }
        DB::beginTransaction();
        DB::connection('mysql_scm')->beginTransaction();
        $derw_res = DB::table('deliver_record_wd')
            ->where('derw_id',$request['derw_id'])
            ->update(['derw_state'=>3,'derw_update_time'=>date('Y-m-d H:i:s')]);

        //送货单商品数据
        $drgw_data = DB::table('deliver_record_goods_wd')
            ->where('drgw_derw_id',$request['derw_id'])
            ->get(['drgw_goo_id','drgw_plan_send_quantity','drgw_shipping_fee','drgw_goo_id']);

        $total_shipping_fee = 0;//配送费
        $actual_total_num = 0;//实际数量
        $goods_id = [];
        foreach ($drgw_data as $key => $value) {
            $actual_total_num += $value->drgw_plan_send_quantity;
            $goods_id[] = $value->drgw_goo_id;
            $quantity[] = $value->drgw_plan_send_quantity;
        }

        $sql = 'UPDATE `faster_deliver_goods_wd` SET ';
        $quantity_str = '';//已送
        $update_time = '';
        $goods_str_id = 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').'"';
        }
        if(!empty($quantity_str)){
            $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_str_id,',').') AND degw_debw_id ='.$derw_data->derw_debw_id;
            $degw_update = DB::update($sql);
        }else{
            $degw_update = true;
        }

        // // 判断账单是否补全  已送货数量 = 账单总量
        // if($debw_data->debw_bill_amount == $actual_total_num){
        //     $debw_replenish_state = 3;
        // }else{
        //     $debw_replenish_state = 2;
        // }

        // 修改配送账单数量
        $debw_sql = 'UPDATE `faster_deliver_bill_wd` SET  `debw_delivery_amount`= `debw_delivery_amount`-' . $actual_total_num .' ,`debw_no_replenishment`=`debw_no_replenishment`+'.$actual_total_num.', `debw_replenish_state`= 2 WHERE `debw_id` ='.$derw_data->derw_debw_id;
        $debw_decrement = DB::update($debw_sql);

        //修改配送账单数量
        $debw_data = DB::table('deliver_bill_wd')
            ->where('debw_id',$derw_data->derw_debw_id)
            ->first(['debw_delivery_amount','debw_shipping_number','debw_bs_shop_id']);
        if($debw_data->debw_delivery_amount == 0){
            //修改配送账单数量
            $debw_res = DB::table('deliver_bill_wd')
                ->where('debw_id',$derw_data->derw_debw_id)
                ->update(['debw_replenish_state'=>1,
                            'debw_update_time'=>date('Y-m-d H:i:s')
                        ]);
        }else{
            $debw_res = true;
        }

        //修改送货单门店收货单状态
        $rerb_data = DB::table('replenish_record_bs')
            ->where('rerb_number',$derw_data->derw_number)
            ->first(['rerb_id','rerb_actual_send_amount']);
        $rerb_res = DB::table('replenish_record_bs')
            ->where('rerb_number',$derw_data->derw_number)
            ->delete();
        $rrgb_res = DB::table('replenish_record_goods_bs')
            ->where('rrgb_rerb_id',$rerb_data->rerb_id)
            ->delete();

        // 门店补货账单表
        $rebi_sql = 'UPDATE `faster_replenish_bill_bs` SET  `rebb_delivery_order_quantity` = rebb_delivery_order_quantity - 1,`rebb_delivery_amount`= `rebb_delivery_amount`-' . $actual_total_num .' , `rebb_no_replenishment`= `rebb_no_replenishment` + '.$actual_total_num."  WHERE `rebb_shipping_number` = '".$debw_data->debw_shipping_number."'";
        $rebb_res = DB::update($rebi_sql);

        $rebb_id = DB::table('replenish_bill_bs')
            ->where('rebb_shipping_number',$debw_data->debw_shipping_number)
            ->value('rebb_id');
        //门店补货账单商品表
        $sql = 'UPDATE `faster_replenish_goods_bs` SET ';
        $quantity_str = '';//已送
        $update_time = '';
        $goods_str_id = implode(',',$goods_id);
        foreach ($goods_id as $key => $value) {
            //商品数量
            $quantity_str .= ' WHEN '.$value.' THEN `regb_goo_quantity` - '.$quantity[$key];
            // 更改时间
            $update_time .= ' WHEN '.$value.' THEN "'.date('Y-m-d H:i:s').'"';
        }
        $sql .= ' `regb_goo_quantity`=  CASE `regb_goo_id` '.$quantity_str.' END,';
        $sql .= ' `regb_update_time`=  CASE `regb_goo_id` '.$update_time.' END';
        $sql .= ' WHERE  `regb_goo_id` IN ('.trim($goods_str_id,',').') AND regb_rebb_id ='.$rebb_id;
        $regb_res = DB::update($sql);


        //门店待补商品更新
        $goods_id_str = implode(', ',$goods_id);
        $sql = 'UPDATE `faster_replenishment_goods_bs` SET ';
        $enroute_amount = '';//在途数量 
        $stock_quantity = '';//待补数量 
        foreach ($drgw_data as $key => $value) {
            //在途数量
            $enroute_amount .= ' WHEN '.$value->drgw_goo_id.' THEN `regb_enroute_amount` - '.$value->drgw_plan_send_quantity;
            //待补数量
            // $stock_quantity .= ' WHEN '.$value->drgw_goo_id.' THEN `regb_stock_quantity` + '.$value->drgw_plan_send_quantity;
        }
        if (!empty($enroute_amount)) {
            $sql .= ' `regb_enroute_amount`=  CASE `regb_goo_id` '.$enroute_amount.' END ';
            // $sql .= ' `regb_stock_quantity`=  CASE `regb_goo_id` '.$stock_quantity.' END';
            $sql .= ' WHERE  `regb_goo_id` IN ('.trim($goods_id_str, ', ').') AND  `regb_shop_id` = '.$debw_data->debw_bs_shop_id;
            $repl_res = DB::update($sql);
        }else{
            $repl_res = true;
        }
        // 供应链补货账单表
        $rebi_sql = 'UPDATE `scm_relationship_bill` SET  `rebi_delivery_quantity`= `rebi_delivery_quantity`-' . $actual_total_num .' , `rebi_no_replenishment`= `rebi_no_replenishment` + '.$actual_total_num."  WHERE `rebi_sd_replenishment_number` = '".$debw_data->debw_shipping_number."'";
        $scm_rebi_res = DB::connection('mysql_scm')->update($rebi_sql);

        // 供应链配送商库存相关数据
        $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']);
        //配送商库存商品表
        $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平
        $enroute_quantity = '';//在途数量
        $insert_reid = [];
        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;
            //     $stock_type .= ' WHEN '.$value.' THEN 1';
            // //库存数量为正
            // }else if($reid_data[$value]->reid_type == 1){
            //     $stock_quantity .= ' WHEN '.$value.' THEN `reid_stock_quantity` + '.$num;
            // //库存数量为负数
            // }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;
            //     }
            //     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';
            //     }
            // }
            //在途数量
            $enroute_quantity .= ' WHEN '.$value.' THEN `reid_enroute_quantity` - '.$num;
        }
        if(!empty($enroute_quantity)){
            if(!empty($stock_type)){
                $sql .= ' `reid_type`=  CASE `reid_rego_id` '.$stock_type.' END,';
            }
            $sql .= ' `reid_enroute_quantity`=  CASE `reid_rego_id` '.$enroute_quantity.' 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;
        }

        //wd补货商品数据
        $regw_info = collect(DB::table('replenishment_goods_wd')
            ->whereIn('regw_goo_id',$goods_id)
            ->where('regw_shop_id',$user_info->adm_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 = '';//待补数量
        $enroute_amount = '';//在途数量
        $update_time = '';//修改时间
        $stock_type = '';//库存正负
        $ids = '';
        $insert_goo_data = [];
        foreach ($goods_id as $key => $value) {
            //如果待补商品里有此数据
            if(isset($regw_info[$value])){
                $num = $quantity[$key];
                //在途数量
                $enroute_amount .= ' WHEN '.$value.' THEN `regw_enroute_amount` - '.$num;
                // 更改时间
                $update_time .= ' WHEN '.$value.' THEN "'.date('Y-m-d H:i:s').'"';
            }else{
                return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'送货单撤销失败']);
            }
        }
        $sql .= ' `regw_enroute_amount`=  CASE `regw_goo_id` '.$enroute_amount.' 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` = '.$user_info->adm_shop_id;
        $rrgw_update = DB::update($sql);

        if ($rerb_res && $scm_rebi_res && $repl_res && $debw_res && $debw_decrement && $derw_res && $rrgb_res && $degw_update && $reid_update && $rrgw_update && $rebb_res && $regb_res) {
            Common::addLog($user_info, getRealIp($request), '补货管理', '配送账单', '送货单:'.$derw_data->derw_number.'撤销');
            DB::commit();
            DB::connection('mysql_scm')->commit();
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'送货单撤销成功']); 
        } else{
            DB::rollBack();
            DB::connection('mysql_scm')->commit();
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'送货单撤销失败']);
        }
    }

    //编辑发货单接口
    public function deliveryEdit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyDispatchingBillsController;
        $error_message = $verify_data->deliveryEditValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $derw_id = DB::table('deliver_record_goods_wd')
            ->where('drgw_id',$request['drgw_id'][0])
            ->value('drgw_derw_id');
        $derw = DB::table('deliver_record_wd')
            ->where('derw_id',$derw_id)
            ->first(['derw_state', 'derw_number']);
        if ($derw->derw_state != 3) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'此单送货单不是已撤销状态']);
        }
        $drgw_id_str = implode(', ',$request['drgw_id']);
        $sql = 'UPDATE `faster_deliver_record_goods_wd` SET ';
        $amount = '';//已配送数量
        foreach ($request['drgw_id'] as $key => $value) {
            //在途数量
            $amount .= ' WHEN '.$value.' THEN '.$request['amount'][$key];
        }
        $sql .= ' `drgw_actual_send_quantity`=  CASE `drgw_id` '.$amount.' END';
        $sql .= ' WHERE  `drgw_id` IN ('.trim($drgw_id_str, ', ').')';
        $drgw_update = DB::update($sql);

        if ($drgw_update) {
            Common::addLog($user_info, getRealIp($request), '补货管理', '配送账单', '送货单:'.$derw->derw_number.'编辑');
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'确认成功']);
        } else {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'确认失败']);
        }
    }

    //获取配送账单信息
    public function getDeliveryBills(Request $request)
    {
        return response()->json(['code'=> 200,'msg'=>'回传成功']);
        // // 接收数据流
        // $request= file_get_contents("php://input");
        // //解析
        // $request = json_decode($request,true);
        // if(empty($request['ser_id']) || empty($request['wat_num']) || empty($request['good_list']))
        // {
        //     return response()->json(['code'=> 202,'msg'=>'参数错误']);
        // }
        // $good_list = $request['good_list'];
        // $token = md5(md5($request['time'].'c883e5e641818d993a2d8d966ca450bf'));
        // if($request['token'] !== $token){
        //     return response()->json(['code'=>203,'msg'=>'token校验失败']);
        // }
        // // 门店信息
        // $bs_data = DB::connection('mysql_scm')
        //     ->table('channel')
        //     ->where('chan_bound_id',$request['ser_id'])
        //     ->first(['chan_shop_id','chan_id','chan_cid']);
        // if(empty($bs_data)){
        //     return response()->json(['code'=>203,'msg'=>'门店信息错误']);
        // }
        // //配送商id
        // $distributors_chan_id = DB::connection('mysql_scm')
        //     ->table('channel_relationship')
        //     ->where('chre_id',$bs_data->chan_id)
        //     ->value('chre_distributors_chan_id');
        // //配送商信息
        // $chan_data = DB::connection('mysql_scm')
        //     ->table('channel')
        //     ->where('chan_id',$distributors_chan_id)
        //     ->first(['chan_cid','chan_shop_id','chan_id']);
        // if(empty($chan_data)){
        //     return response()->json(['code'=>203,'msg'=>'没有此配送商']);
        // }
        // $debw_id = DB::table('deliver_bill_wd')
        //     ->where('debw_shipping_number',$request['wat_num'])
        //     ->value('debw_id');
        // if(!empty($debw_id)){
        //     return response()->json(['code'=>203,'msg'=>'此账单已存在']);
        // }
        // DB::beginTransaction();
        // //商品id
        // $goods_id = array_column($request['good_list'],'pg_id');
        // //补货商品表
        // $rego_data = collect(DB::connection('mysql_scm')
        //     ->table('relationship_goods as rego')
        //     ->leftjoin('replenishment_goods_details as regd', 'regd.regd_rego_id', '=', 'rego.rego_id')
        //     ->get(['regd_shipping_fee', 'rego_id', 'rego_sd_goo_id']))
        //     ->keyBy('rego_sd_goo_id')
        //     ->toArray();
        // //残损数据
        // $spgo_data = collect(DB::table('spoiled_goods')
        //     ->where('spgo_cid', $bs_data->chan_cid)
        //     ->where('spgo_shop_id', $bs_data->chan_shop_id)
        //     ->where('spgo_state', 1)
        //     ->where('spgo_type', 2)
        //     ->get(['spgo_goo_id', 'spgo_sd_goo_id','spgo_goo_name', 'spgo_spoiled_quantity','spgo_goo_encode']))
        //     ->keyBy('spgo_goo_id')
        //     ->toArray();

        // //获取门店信息
        // $shop_data = DB::table('shop')
        //     ->where('shop_id',$chan_data->chan_shop_id)
        //     ->first(['shop_cid', 'shop_superior_id', 'shop_id']);
        // $shop_id = $shop_data->shop_superior_id ? $shop_data->shop_superior_id : $shop_data->shop_id;

        // $goods_num = 0;//总商品数量
        // $shipping_fee = 0;//商品配送费
        // $good_list = array_values($request['good_list']);
        // foreach ($good_list as $key => $value) {
        //     if(!is_numeric((int)$value['pg_id']) || empty($value['good_name']) || !is_numeric((int)$value['good_num'])){
        //         return response()->json(['code'=> 202,'msg'=>'参数错误']);
        //     }
        //     //判断补货商品是否已经被设置
        //     if(isset($rego_data[$value['pg_id']])){
        //         $goods_data[$key]['degw_sd_goo_id'] = $value['pg_id'];//商品id
        //         $goods_data[$key]['degw_goo_id'] = $rego_data[$value['pg_id']]->rego_id;//商品id
        //         $goods_data[$key]['degw_goo_name'] = $value['good_name'];//商品名称
        //         $goods_data[$key]['degw_goo_encode'] = $value['product_version'];//商品编号
        //         $goods_num += $value['good_num'];
        //         $goods_data[$key]['degw_shipping_fee'] = $rego_data[$value['pg_id']]->regd_shipping_fee;//商品配送费数量
        //         // $goods_data[$key]['degw_one_shipping_fee'] = $rego_data[$value['pg_id']]->regd_shipping_fee;//单个商品配送费数量
        //         $shipping_fee += $rego_data[$value['pg_id']]->regd_shipping_fee * $value['good_num'];
        //         $goods_data[$key]['degw_replenishment_quantity'] = $value['good_num'];//商品数量
        //     }else{
        //         continue;
        //     }
        // }
        // $not_goods = [];
        // $in_goods = [];
        // //如果有残损数据
        // if(!empty($spgo_data)){
        //     foreach ($goods_data as $key => $value) {
        //         if(isset($spgo_data[$value['degw_goo_id']])){
        //             $goods_data[$key]['degw_replenishment_quantity'] = $spgo_data[$value['degw_goo_id']]->spgo_spoiled_quantity + $value['degw_replenishment_quantity'];
        //             //重新计算商品数量
        //             $goods_num += $spgo_data[$value['degw_goo_id']]->spgo_spoiled_quantity;
        //             //重新计算配送费
        //             $shipping_fee += $goods_data[$key]['degw_shipping_fee'] * $spgo_data[$value['degw_goo_id']]->spgo_spoiled_quantity;
        //             $goods_data[$key]['degw_shipping_fee'] = $value['degw_shipping_fee'];
        //             $not_goods[] = $value['degw_goo_id'];
        //         }else{
        //             $in_goods[] = $value['degw_goo_id'];
        //         }
        //     }
        // }
        // if ($in_goods) {
        //     foreach ($spgo_data as $key => $value) {
        //         if(!in_array($key,$not_goods)){
        //             $insert['degw_goo_name'] = $value->spgo_goo_name;
        //             $insert['degw_goo_encode'] = $value->spgo_goo_encode;
        //             $insert['degw_replenishment_quantity'] = $value->spgo_spoiled_quantity;
        //             $insert['degw_sd_goo_id'] = $value->spgo_sd_goo_id;
        //             $insert['degw_goo_id'] = $value->spgo_goo_id;
        //             $insert['degw_shipping_fee'] = $rego_data[$value->spgo_sd_goo_id]->regd_shipping_fee;
        //             $shipping_fee += $insert['degw_shipping_fee'] * $value->spgo_spoiled_quantity;
        //             $goods_num += $value->spgo_spoiled_quantity;
        //             $goods_data[] = $insert;
        //         }
        //     }
        // }
        // if(!empty($spgo_data)){
        //     $spgo_id = [];
        //     foreach ($spgo_data as $key => $value) {
        //         $spgo_id[] = $value->spgo_goo_id;
        //     }
        //     $spgo_res = DB::table('spoiled_goods')
        //         ->whereIn('spgo_id', $spgo_id)
        //         ->update(['spgo_state'=>2]);
        // }else{
        //     $spgo_res = true;
        // }
        // $debw['debw_cid'] = $chan_data->chan_cid;//所属企业id
        // $debw['debw_bill_amount'] = $goods_num;//账单总量
        // $debw['debw_shop_id'] = $chan_data->chan_shop_id;//配送商id
        // $debw['debw_superior_shop_id'] = $shop_id;//总店id
        // $debw['debw_shipping_number'] = $request['wat_num'];//配送账单号
        // $debw['debw_bs_shop_id'] = $bs_data->chan_shop_id;//安装门店id
        // $debw['debw_no_replenishment'] = $goods_num;//未补货数量
        // $debw['debw_total_money'] = $shipping_fee;//配送费
        // $debw['debw_replenish_state'] = 1;//补货进度1未补2部分3补全
        // $debw['debw_state'] = 1;//账单状态1未确认2待审核3未完成4已完成5已驳回
        // $debw_id = DB::table('deliver_bill_wd')->insertGetid($debw);
        // foreach ($goods_data as $key => $value) {
        //     $goods_data[$key]['degw_debw_id'] = $debw_id;
        // }
        // $degw_res = DB::table('deliver_goods_wd')->insert($goods_data);
        // if(empty($debw_id) || empty($degw_res) || empty($spgo_res)){
        //     DB::rollBack();
        //     return response()->json(['code'=> 201,'msg'=>'回传失败']);
        // }
        // DB::commit();
        // return response()->json(['code'=> 200,'msg'=>'回传成功']);
    }
}
