<?php
namespace App\Http\Controllers\WeChatApplet\AppletWarehouseManage;

use Illuminate\Http\Request;
use App\Http\Models\Api\Common;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Http\Controllers\WeChatApplet\Verify\AppletWarehouseManage\VerifyAppletDispatchController;
use App\Http\Models\Services\Dispatch;
use App\Http\Models\Api\ReceivableBill;
use App\Http\Models\Api\WorkOrder;

// 仓储系统 -- 发货单
class AppletDispatchController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::wechatGetUserInfo($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('dispatch_bill as dibi')
            ->leftjoin('work_order as wor', 'wor.wor_id', '=', 'dibi.dego_wor_id')
            ->where('dego_cid', $user_info->adm_cid)
            ->where('dego_superior_shop_id', $shop_id)
            ->where('dego_type', '<>', 3)
            ->where(function ($query) use ($search_data) { //类型：1未出库2已出库3作废4锁定
                if (!empty($search_data['dego_type'])) {
                    $query->where('dego_type', $search_data['dego_type']);
                }
            })
            ->where(function ($query) use ($search_data) { //创建时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                    $query->whereBetween('dego_create_time', [$search_data['start_time'], $search_data['end_time'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['start_time'])) {
                        $query->where('dego_create_time', '>=', $search_data['start_time']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['end_time'])) {
                            $query->where('dego_create_time', '<=', $search_data['end_time'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) { //门店id
                if (!empty($search_data['dego_service_shop_id'])) {
                    $query->where('dego_service_shop_id', $search_data['dego_service_shop_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //供货仓库
                if (!empty($search_data['dego_out_ware_id'])) {
                    $query->where('dego_out_ware_id', $search_data['dego_out_ware_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //原始单号，发货单的关联单号
                if (!empty($search_data['dego_original_number'])) {
                    $query->where('wor_order_number', 'like', '%' . $search_data['dego_original_number'] . '%')
                        ->where('dego_order_type', 2)
                        ->orwhere('dego_original_number', 'like', '%' . $search_data['dego_original_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //发货单号
                if (!empty($search_data['dego_number'])) {
                    $query->where('dego_number', 'like', '%' . $search_data['dego_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //领货人
                if (!empty($search_data['dego_service_adm_id'])) {
                    $query->where('dego_service_adm_id', $search_data['dego_service_adm_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //客户id
                if (!empty($search_data['dego_client_id'])) {
                    $query->where('dego_client_id', $search_data['dego_client_id']);
                }
            })
            ->select('dego_id', 'wor_order_number', 'dego_create_time', 'dego_number', 'dego_original_number', 'dego_count', 'dego_service_shop_id', 'dego_out_ware_id', 'dego_service_adm_id', 'dego_type', 'dego_wor_id', 'dego_order_type')
            ->orderBy('dego_id', 'desc')
            ->paginate($this->show_count);

        $list_items = $list_data->items();
        if ($list_items) {
            $order_id = [];
            $wor_id = [];
            $after_id = [];
            $shop_id = array_unique(array_column($list_items, 'dego_service_shop_id')); //服务门店id
            $ware_id = array_unique(array_column($list_items, 'dego_out_ware_id')); //出库仓库id
            $adm_id = array_unique(array_column($list_items, 'dego_service_adm_id')); //服务技师id
            $dego_client_id = array_unique(array_column($list_items, 'dego_client_id')); //选择的客户id,会员id/单位id
            foreach ($list_items as $key => $value) {
                // 订单发货
                if ($value->dego_order_type == 1) {
                    $order_id[] = $value->dego_wor_id;
                }
                // 工单发货
                if ($value->dego_order_type == 2) {
                    $wor_id[] = $value->dego_wor_id;
                }
                // 售后单发货
                if ($value->dego_order_type == '3') {
                    $after_id[] = $value->dego_wor_id;
                }
            }

            // 查找门店id对应的门店名称
            $shop_id = array_unique($shop_id);
            $find_shop = DB::table('shop')
                ->whereIn('shop_id', $shop_id)
                ->select('shop_id', 'shop_store_name')
                ->get()->toArray();
            // 查找仓库id对应的仓库名称 / 负责人
            $ware_id = array_unique($ware_id);
            // $find_ware = DB::table('warehouse as w')
            //     ->leftJoin('admin as a', 'w.ware_leader_id', '=', 'a.adm_id')
            //     ->whereIn('ware_id', $ware_id)
            //     ->select('ware_id', 'ware_name', 'ware_type', 'adm_name')
            //     ->get()->toArray();
            $find_ware = DB::table('warehouse as w')
                ->whereIn('ware_id', $ware_id)
                ->select('ware_id', 'ware_name', 'ware_type', 'ware_leader_id')
                ->get()->toArray();
            foreach ($find_ware as $key => $value) {
                $adm_id = explode(',',$value->ware_leader_id);
                $adm_name = DB::table('admin')
                    ->whereIn('adm_id', $adm_id)
                    ->select('adm_name', 'adm_phone')
                    ->get()->toArray();
                $adm_name = array_column($adm_name, 'adm_name');
                $adm_name =  implode(',', $adm_name);
                $find_ware[$key]->adm_name = $adm_name;
                $adm_phone = array_column($adm_phone, 'adm_phone');
                $adm_phone =  implode(',', $adm_phone);
                $find_ware[$key]->adm_phone = $adm_phone;
            }
            // 查询客户单位
            $channel = DB::table('channel_unit')
                ->whereIn('chun_id', $dego_client_id)
                ->where('chun_shop_id', $shop_id)
                ->where('chun_state', '1')
                ->pluck('chun_id', 'chun_unit_name')
                ->toArray();
            // 查找工单客户信息
            $work_client = DB::table('work_order as wor')
                ->leftjoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wor.wor_id')
                ->whereIn('wocl_wor_id', $wor_id)
                ->select('wocl_wor_id', 'wocl_channel_unit', 'wocl_name', 'wor_type', 'wor_service_state', 'wocl_standby_battery_type', 'wor_order_number', 'wocl_client_id')
                ->get()->toArray();
            foreach ($work_client as $key => $value) {
                // 客户单位名称
                if (isset($channel[$value->wocl_client_id])) {
                    $work_client[$key]->wocl_channel_unit = $channel[$value->wocl_client_id];
                } else {
                    $work_client[$key]->wocl_channel_unit = $value->wocl_channel_unit ? $value->wocl_channel_unit : $value->wocl_name;
                }
                if ($value->wor_type == 3) {
                    $work_client[$key]->wocl_channel_unit = config('apisystem.sd_chan_info')['name'];
                }
            }
            // 查找订单客户信息
            $order_client = DB::table('order as ord')
                ->leftjoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
                ->whereIn('orcl_ord_id', $order_id)
                ->select('orcl_ord_id', 'orcl_channel_unit', 'orcl_name', 'ord_type', 'orcl_standby_battery_type', 'ord_order_number', 'orcl_client_id')
                ->get()->toArray();
            foreach ($order_client as $key => $value) {
                // 客户单位名称
                if (isset($channel[$value->orcl_client_id])) {
                    $order_client[$key]->orcl_channel_unit = $channel[$value->orcl_client_id];
                } else {
                    $order_client[$key]->orcl_channel_unit = $value->orcl_channel_unit ? $value->orcl_channel_unit : $value->orcl_name;
                }
                if ($value->ord_type == 3) {
                    $order_client[$key]->orcl_channel_unit = config('apisystem.sd_chan_info')['name'];
                }
            }
            // 查找售后单客户信息
            $after_client = DB::table('order_after as oraf')
                ->leftjoin('order_after_client as orac', 'orac.orac_oraf_id', '=', 'oraf.oraf_id')
                ->whereIn('orac_oraf_id', $after_id)
                ->select('orac_oraf_id', 'orac_channel_unit', 'orac_name', 'oraf_type', 'orac_standby_battery_type')
                ->get()->toArray();

            // 查找技师id对应的领货人姓名
            $adm_id = array_unique($adm_id);
            $find_admin = DB::table('admin')
                ->whereIn('adm_id', $adm_id)
                ->select('adm_id', 'adm_name')
                ->get()->toArray();
            // 查询当前账号所拥有的仓库权限
            $find_admin_set = DB::table('admin_set')
                ->where('adms_adm_id', $user_info->adm_id)
                ->where('adms_shop_id', $user_info->adm_shop_id)
                ->value('adms_ware_id');
        } else {
            $find_shop = [];
            $find_ware = [];
            $find_admin = [];
            $order_client = [];
            $work_client = [];
            $after_client = [];
            $find_admin_set = '';
        }

        $state_count = DB::table('dispatch_bill')
            ->where('dego_cid', $user_info->adm_cid)
            ->where('dego_shop_id', $user_info->adm_shop_id)
            ->select(DB::raw('count(*) as count, dego_type'))
            ->groupBy('dego_type')
            ->get();

        // 查询门店打印模板
        $shpt_id = DB::table('shop_print_template')
            ->where('shpt_shop_id', $user_info->adm_shop_id)
            ->where('shpt_print_type', 1)
            ->where('shpt_delete', 1)
            ->value('shpt_id');
        if (empty($shpt_id)) {
            $shpt_id = 0;
        }

        $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;
        $data_info['find_shop'] = $find_shop;                   //返回门店名称
        $data_info['find_ware'] = $find_ware;                   //返回仓库名称
        $data_info['find_admin'] = $find_admin;                 //返回领货人姓名
        $data_info['order_client'] = $order_client;             //订单客户名称
        $data_info['work_client'] = $work_client;               //工单客户名称
        $data_info['after_client'] = $after_client;             //售后单客户名称
        $data_info['find_admin_set'] = $find_admin_set;         //当前账号所拥有的仓库权限
        $data_info['shpt_id'] = $shpt_id;                       //当前账号所拥有的仓库权限

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

    // 发货
    // 订单生成的发货单,状态改为已出库,扣固定仓库存,订单状态改为已完成
    // 工单生成的发货单,状态改为已出库,扣固定仓库存,加移动仓库存
    public function shipments(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyAppletDispatchController;
        $error_message = $verify_data->shipmentsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 验证已经发货的不能再次发货
        $dis_data = DB::table('dispatch_bill')
            ->where('dego_id', $request['dego_id'])
            ->select('dego_type', 'dego_cid', 'dego_shop_id', 'dego_out_ware_id', 'dego_service_adm_id', 'dego_number', 'dego_order_type', 'dego_wor_id', 'dego_original_number', 'dego_service_shop_id', 'dego_count', 'dego_create_adm_id', 'dego_id')
            ->first();
        if (empty($dis_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前发货单不存在！']);
        }
        if ($dis_data->dego_type == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前发货单已发货！']);
        }
        if ($dis_data->dego_type == 3) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前发货单已作废！']);
        }
        if ($dis_data->dego_type == 4) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前发货单已锁定，无法发货！']);
        }

        $service_ware_id = 0; //领货人技师库id
        // dego_order_type类型：1.订单发货 2.工单发货3售后单发货
        if ($dis_data->dego_order_type == 1) {
            // 订单发货，如果是订单类型为发货单的判断此订单是否审核
            $ord_wor_state = DB::table('order')
                ->where('ord_id', $dis_data->dego_wor_id)
                ->where('ord_order_number', $dis_data->dego_original_number)
                ->value('ord_wor_state');
            if ($ord_wor_state == 12) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'此客户单位超出可欠金额、天数,请到订单列表进行审核！']);
            }

            $find_ord_id = $dis_data->dego_wor_id; //订单id
            $find_order_number = $dis_data->dego_original_number; //订单编号
        } elseif ($dis_data->dego_order_type == 2) {
            // 工单发货验证技师是否绑定了技师库
            // $service_ware_id = DB::table('warehouse')
            //     ->where('ware_type', 2) //类型：1固定仓2技师库
            //     ->where('ware_leader_id', $dis_data->dego_service_adm_id)
            //     ->value('ware_id');
            // if (empty($service_ware_id)) {
            //     return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前技师未绑定技师库,请先绑定技师库']);
            // }
            // 查询当前工单技师的服务状态
            $wor_service_state = DB::table('work_order')
                ->where('wor_id', $dis_data->dego_wor_id)
                ->value('wor_service_state');
            // 如果技师尚未接单，不允许发货
            // 服务状态：1待接单2已接单3预约4出发5抵达6完成待审核7完成已驳回8完成通过9终止10锁定11速电撤销回收
            if ($wor_service_state < 2) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前技师尚未接单！']);
            }

            $find_order_data = DB::table('work_order as wor')
                ->leftjoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wor.wor_id')
                ->where('wor_id', $dis_data->dego_wor_id)
                ->select('wor_type', 'wocl_client_id', 'wor_order_id', 'wor_order_number')
                ->first();
            $find_ord_id = $find_order_data->wor_order_id; //订单id
            $find_order_number = $find_order_data->wor_order_number; //订单编号
        } elseif ($dis_data->dego_order_type == 3) {
            // 售后单发货验证
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'售后单发货功能暂未开通！']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'发货失败！']);
        }

        // 获取当前操作账号信息
        $user_info = Common::wechatGetUserInfo($request['api_token']);

        if ($request['type'] == '1') { //获取页面数据
            $digo_data = DB::table('dispatch_goods as digo')
                ->leftjoin('goods as goo', 'goo.goo_id', '=', 'digo.digo_goo_id')
                ->where('digo_dego_id', $request['dego_id'])
                ->where('digo_state', '!=', '2')
                ->select('digo_id', 'digo_wago_class', 'digo_goo_id', 'digo_goo_type', 'digo_goo_name', 'digo_goo_goods_encode', 'digo_goo_price', 'digo_goo_quantity', 'digo_is_recycle', 'digo_goo_inventory', 'digo_state', 'digo_tem_goo_name', 'goo_bra_name', 'goo_brse_id', 'goo_class', 'digo_wago_id', 'digo_orgo_id')
                ->get()->toArray();
            // 查询系列数据
            $goo_brse_id = array_column($digo_data, 'goo_brse_id');
            $brse_data = DB::table('brand_serie')
                ->whereIn('brse_id', $goo_brse_id)
                ->pluck('brse_name', 'brse_id')
                ->toArray();
            // 查询仓位商品锁定表
            $find_wfgl_data = DB::table('warehouse_freight_goods_lock as w')
                ->leftJoin('warehouse_freight as wf', 'w.wfgl_wafr_id', '=', 'wf.wafr_id')
                ->where('wfgl_shop_id', $user_info->adm_shop_id)
                ->where('wfgl_type', 1)
                ->where('wfgl_state', 1)
                ->where('wfgl_original_id', $find_ord_id)
                ->where('wfgl_original_number', $find_order_number)
                ->select('wfgl_id', 'wfgl_ware_id', 'wfgl_wago_id', 'wfgl_wafr_id', 'wfgl_wafg_id', 'wfgl_lock_quantity', 'wfgl_lock_type', 'wafr_name', 'wfgl_waon_class')
                ->get()->toArray();
            $find_wfgl_data = json_decode(json_encode($find_wfgl_data, true), true);
            $new_wfgl_sate = false; //是否重新组仓位数据
            if (empty($find_wfgl_data)) {
                // 没有查询到仓位锁定库存，需要重新组数据
                $new_wfgl_sate = true;
            }
            $new_wfgl_data = []; //新的仓位数据
            $surplus_wfgl_data = $find_wfgl_data; //剩余仓位数据
            foreach ($digo_data as $key => $value) {
                // 查询仓库商品表中有可发货商品的数据
                $option_ware[] = DB::table('warehouse_goods as wago')
                    ->leftjoin('warehouse as w', 'wago.wago_ware_id', '=', 'w.ware_id')
                    ->where('wago_ware_id', $dis_data->dego_out_ware_id)
                    ->where('wago_id', $value->digo_wago_id)
                    ->where('wago_class', $value->digo_wago_class)
                    ->where('wago_goo_id', $value->digo_goo_id)
                    ->select('ware_id as wafr_id', 'ware_name as wafr_name', 'wago_stock_amount as wafg_stock_number', 'wago_lock_amount as wafg_lock_quantity', 'wago_priority_lock_amount as wafg_priority_lock_quantity', 'wago_priority_stock_amount as wafg_priority_stock_number')
                    ->first();

                // 查询仓位商品表中有发货商品的数据
                $digo_data[$key]->option_freight = DB::table('warehouse_freight_goods as wafg')
                    ->leftjoin('warehouse_freight as wafr', 'wafg.wafg_wafr_id', '=', 'wafr.wafr_id')
                    ->where('wafg_ware_id', $dis_data->dego_out_ware_id)
                    ->where('wafg_wago_id', $value->digo_wago_id)
                    ->where('wafg_class', $value->digo_wago_class)
                    ->where('wafg_goo_id', $value->digo_goo_id)
                    ->where(function ($query) use ($value) {
                        if ($value->digo_goo_inventory == 1) {
                            $query->where('wafg_stock_number', '>', 0)->orWhere('wafg_lock_quantity', '>', 0);
                        } else {
                            $query->where('wafg_priority_stock_number', '>', 0)->orWhere('wafg_priority_lock_quantity', '>', 0);
                        }
                    })
                    ->select('wafr_id', 'wafr_name', 'wafr_rank', 'wafg_stock_number', 'wafg_priority_stock_number', 'wafg_lock_quantity', 'wafg_priority_lock_quantity')
                    ->get()->toArray();
                if (!empty($option_ware[0])) {
                    if ($value->digo_goo_inventory == 1 && ($option_ware[0]->wafg_stock_number > 0 || $option_ware[0]->wafg_lock_quantity > 0)) {
                        $option_ware[0]->wafr_id = 0;
                        $option_ware[0]->wafr_name = '仓库';
                        $option_ware[0]->wafg_stock_number = $option_ware[0]->wafg_stock_number;
                        $option_ware[0]->wafg_lock_quantity = $option_ware[0]->wafg_lock_quantity;
                        $option_ware[0]->wafg_priority_stock_number = $option_ware[0]->wafg_priority_stock_number;
                        $option_ware[0]->wafg_priority_lock_quantity = $option_ware[0]->wafg_priority_lock_quantity;
                        $digo_data[$key]->option_freight = array_merge($option_ware, $digo_data[$key]->option_freight);
                        $option_ware[0]->wafr_id = 0;
                    }
                    if ($value->digo_goo_inventory == 2 && ($option_ware[0]->wafg_priority_stock_number > 0 || $option_ware[0]->wafg_priority_lock_quantity > 0)) {
                        $option_ware[0]->wafr_id = 0;
                        $option_ware[0]->wafr_name = '仓库';
                        $option_ware[0]->wafg_stock_number = $option_ware[0]->wafg_stock_number;
                        $option_ware[0]->wafg_lock_quantity = $option_ware[0]->wafg_lock_quantity;
                        $option_ware[0]->wafg_priority_stock_number = $option_ware[0]->wafg_priority_stock_number;
                        $option_ware[0]->wafg_priority_lock_quantity = $option_ware[0]->wafg_priority_lock_quantity;
                        $digo_data[$key]->option_freight = array_merge($option_ware, $digo_data[$key]->option_freight);
                        $option_ware[0]->wafr_id = 0;
                    }
                }
                unset($option_ware);
                if ($new_wfgl_sate) {
                    // 重新调整数组
                    $temp_wfgl_data['wfgl_id'] = 0; //仓位商品锁定主键id
                    $temp_wfgl_data['wafr_name'] = '仓库'; //仓位商品锁定主键id
                    $temp_wfgl_data['wfgl_ware_id'] = $dis_data->dego_out_ware_id; //仓库id
                    $temp_wfgl_data['wfgl_wago_id'] = $value->digo_wago_id; //仓库商品主键id
                    $temp_wfgl_data['wfgl_wafr_id'] = 0; //仓位id
                    $temp_wfgl_data['wfgl_wafg_id'] = 0; //仓位商品主键id
                    $temp_wfgl_data['wfgl_lock_quantity'] = $value->digo_goo_quantity; //商品锁定数量
                    $temp_wfgl_data['wfgl_lock_type'] = $value->digo_goo_inventory; //商品锁定类型：1良品2优先
                    $new_wfgl_data[] = $temp_wfgl_data;
                    unset($temp_wfgl_data);
                }
                if ($new_wfgl_sate) { //没有仓位锁定商品
                    $digo_data[$key]->wfgl_data = $new_wfgl_data;
                    unset($new_wfgl_data);
                } else { //有锁定商品的
                    $num = 0;
                    $digo_goo_quantity = $value->digo_goo_quantity; //发货数量
                    foreach ($find_wfgl_data as $wfgl_key => $wfgl_value) { //从仓位商品表中扣除发货数量
                        if ($wfgl_value['wfgl_wago_id'] == $value->digo_wago_id && $value->digo_goo_inventory == $wfgl_value['wfgl_lock_type'] && $value->digo_wago_class == $wfgl_value['wfgl_waon_class']) { //判断仓库类别和发货类型和仓库商品id
                            if ($wfgl_value['wfgl_lock_quantity'] != 0) { //此仓位还有锁定数量，可以从这个仓位出库
                                $digo_goo_quantity = $digo_goo_quantity - $wfgl_value['wfgl_lock_quantity']; //出库商品-仓位中锁定的数量
                                $wafr_data[$num]['wafr_name'] = $wfgl_value['wafr_name'] ? $wfgl_value['wafr_name'] : '仓库'; //仓位锁定表中锁定仓库商品没有仓位名称显示仓库
                                $wafr_data[$num]['wfgl_id'] = $wfgl_value['wfgl_id'];
                                $wafr_data[$num]['wfgl_wago_id'] = $wfgl_value['wfgl_wago_id'];
                                $wafr_data[$num]['wfgl_wafr_id'] = $wfgl_value['wfgl_wafr_id'];
                                $wafr_data[$num]['wfgl_wafg_id'] = $wfgl_value['wfgl_wafg_id'];
                                $wafr_data[$num]['wfgl_lock_type'] = $wfgl_value['wfgl_lock_type'];
                                if ($digo_goo_quantity <= 0) { //出库商品-仓位中锁定的数量小于0，仓位锁定出库后还有剩余，出完了，跳出
                                    $find_wfgl_data[$wfgl_key]['wfgl_lock_quantity'] = abs($digo_goo_quantity);
                                    $wafr_data[$num]['wfgl_lock_quantity'] = $digo_goo_quantity + $wfgl_value['wfgl_lock_quantity'];
                                    break;
                                } else { //出库商品-仓位中锁定的数量大于0，没出完，从下一个仓位扣除
                                    $find_wfgl_data[$wfgl_key]['wfgl_lock_quantity'] = 0;
                                    $wafr_data[$num]['wfgl_lock_quantity'] = $wfgl_value['wfgl_lock_quantity'];
                                }
                                $num++;
                            }
                        }
                    }

                    if ($digo_goo_quantity > 0) { //仓位出库后还有需要出库的库存，从仓库出库
                        $wafr_data[$num]['wafr_name'] = '仓库';
                        $wafr_data[$num]['wfgl_lock_quantity'] = $digo_goo_quantity;
                        $wafr_data[$num]['wfgl_id'] = $digo_goo_quantity;
                        $wafr_data[$num]['wfgl_ware_id'] = $dis_data->dego_out_ware_id; //仓库id
                        $wafr_data[$num]['wfgl_wago_id'] = $value->digo_wago_id; //仓库商品主键id
                        $wafr_data[$num]['wfgl_wafr_id'] = 0;
                        $wafr_data[$num]['wfgl_wafg_id'] = 0; //仓位商品主键id
                        $wafr_data[$num]['wfgl_lock_type'] = $value->digo_goo_inventory; //商品锁定类型：1良品2优先
                    }
                    $digo_data[$key]->wfgl_data = $wafr_data;
                    unset($digo_goo_quantity);
                    unset($wafr_data);
                }
                // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                    if (!empty($value->goo_brse_id)) {
                        if ($value->goo_class == 2) {
                            $digo_data[$key]->digo_goo_name = $brse_data[$value->goo_brse_id] . ' ' . $value->digo_goo_name;
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $digo_data[$key]->digo_goo_name = $brse_data[$value->goo_brse_id] . ' ' . $value->digo_goo_name;
                            }
                        }
                    }
                }
                // 显示品牌名称
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                    if ($value->goo_class == 2) {
                        $digo_data[$key]->digo_goo_name = $value->goo_bra_name . ' ' . $value->digo_goo_name;
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $digo_data[$key]->digo_goo_name = $value->goo_bra_name . ' ' . $value->digo_goo_name;
                        }
                    }
                }
                unset($digo_data[$key]->goo_brse_id);
                unset($digo_data[$key]->goo_class);
            }
            // 查询服务门店名称
            $dis_data->dego_service_shop_name = DB::table('shop')
                ->where('shop_id', $dis_data->dego_service_shop_id)
                ->value('shop_store_name');
            // 查询仓库名称
            $dis_data->ware_name = DB::table('warehouse')
                ->where('ware_id', $dis_data->dego_out_ware_id)
                ->value('ware_name');
            // 查询领货人名称
            $dis_data->adm_name = DB::table('admin')
                ->where('adm_id', $dis_data->dego_create_adm_id)
                ->value('adm_name');
            // 订单发货
            if ($dis_data->dego_order_type == 1) {
                // 查找订单客户信息
                $order_client = DB::table('order as ord')
                    ->leftjoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
                    ->where('orcl_ord_id', $dis_data->dego_wor_id)
                    ->select('orcl_ord_id', 'orcl_channel_unit', 'ord_type', 'orcl_standby_battery_type', 'orcl_client_id')
                    ->first();
                $order_client->orcl_channel_unit = DB::table('channel_unit')
                    ->where('chun_id', $order_client->orcl_client_id)
                    ->value('chun_unit_name');
                unset($order_client->orcl_client_id);
            } else {
                $order_client = [];
            }

            // 工单发货
            if ($dis_data->dego_order_type == 2) {
                // 查找工单客户信息
                $work_client = DB::table('work_order as wor')
                    ->leftjoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wor.wor_id')
                    ->where('wocl_wor_id', $dis_data->dego_wor_id)
                    ->select('wocl_wor_id', 'wocl_channel_unit', 'wocl_name', 'wor_type', 'wocl_standby_battery_type', 'wocl_client_id')
                    ->first();
                $work_client->wocl_channel_unit = DB::table('channel_unit')
                    ->where('chun_id', $work_client->wocl_client_id)
                    ->value('chun_unit_name');
                unset($work_client->wocl_client_id);
            } else {
                $work_client = [];
            }


            $data['dis_data'] = $dis_data;
            $data['order_client'] = $order_client;
            $data['work_client'] = $work_client;
            $data['dispatch_goods'] = $digo_data;
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }

        $request_goods_data = json_decode($request['goodsDataList'], true); //前端提交的出库商品数据
        if (empty($request_goods_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'请选择出库商品']);
        }

        // 判断出库仓库类型，pc端不能发移动仓库的商品，只能发固定仓的，有权限的商品
        // ware_type类型：1固定仓2技师库3移动仓
        $dego_out_ware_type = DB::table('warehouse')
            ->where('ware_id', $dis_data->dego_out_ware_id)
            ->value('ware_type');
        if ($dego_out_ware_type != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前供货仓库不是固定仓库，没有发货权限！']);
        }

        // 查询当前账号所拥有的仓库权限
        $find_admin_set = DB::table('admin_set')
            ->where('adms_adm_id', $user_info->adm_id)
            ->where('adms_shop_id', $user_info->adm_shop_id)
            ->value('adms_ware_id');
        $find_admin_set = explode(',', trim($find_admin_set, ','));
        if (!in_array($dis_data->dego_out_ware_id, $find_admin_set)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'没有当前仓库的发货权限！']);
        }

        DB::beginTransaction();

        // 更改仓库、仓位发货数量
        $shipments_retrun = Dispatch::shipments(
            $user_info, //用户信息
            $request->all(), //用户信息
            $request_goods_data, //提交的商品数据
            $dis_data, //查询的发货单信息
            $dego_out_ware_type, //发货仓库类型
            $find_ord_id, //订单id
            $find_order_number, //订单单号
            $service_ware_id //服务技师库id
        );
        if ($shipments_retrun['code'] == 500) {
            DB::rollBack();
            return response()->json($shipments_retrun);
        }

        // 修改发货单表的状态
        $update_data['dego_type'] = 2; //类型：1未出库2已出库
        $update_data['dego_update_time'] = date('Y-m-d H:i:s'); //更新时间
        $dispatch_res = DB::table('dispatch_bill')
            ->where('dego_id', $request['dego_id'])
            ->update($update_data);

        // 更新订单商品表的商品成本，根据订单id,查询商品
        $find_orgo_data = DB::table('order_goods')
            ->where('orgo_ord_id', $find_ord_id)
            ->where('orgo_state', '!=', 2)
            ->select('orgo_id', 'orgo_state', 'orgo_ord_id', 'orgo_ware_id', 'orgo_waon_class', 'orgo_goo_id', 'orgo_goo_price', 'orgo_goo_quantity')
            ->get()->toArray();
        $cost_price = 0; //总成本金额
        $recycle_amount = 0; //回收商品总成本
        $now_date = date('Y-m-d H:i:s'); //当前时间
        foreach ($find_orgo_data as $kkkk => $vvvv) {
            // 获取当前月份商品成本价
            if (in_array($vvvv->orgo_state, [1, 5, 8])) {
                $find_ense_end_price = DB::table('enters_sells_saves')
                    ->where('ense_goo_id', $vvvv->orgo_goo_id)
                    ->where('ense_goo_warehouse', $vvvv->orgo_ware_id)
                    ->where('ense_goo_waretype', $vvvv->orgo_waon_class)
                    ->where('ense_order_number', $find_order_number)
                    ->orderBy('ense_id', 'desc')
                    ->value('ense_end_price');
                $find_ense_end_price = sprintf('%.2f', $find_ense_end_price);
            } else {
                $find_ense_end_price = 0;
            }
            $cost_price += $find_ense_end_price * $vvvv->orgo_goo_quantity; //总成本金额

            if ($vvvv->orgo_state == 3) {
                $recycle_amount += $vvvv->orgo_goo_price * $vvvv->orgo_goo_quantity; //回收商品成本金额
            }
            // 修改订单商品成本
            $orgo_edit_data['orgo_goo_cost'] = $find_ense_end_price * 100;
            $orgo_edit_data['orgo_update_time'] = $now_date;
            // 修改订单表的更新时间
            $orgo_edit_res = DB::table('order_goods')
                ->where('orgo_id', $vvvv->orgo_id)
                ->where('orgo_ord_id', $find_ord_id)
                ->where('orgo_order_number', $find_order_number)
                ->update($orgo_edit_data);
            unset($orgo_edit_data);
        }
        if ($dis_data->dego_order_type == 1) {
            // 订单发货单 将订单状态改为完成
            $update_date['ord_wor_state'] = 4;
            $update_date['ord_update_time'] = date('Y-m-d H:i:s');
            $update_state = DB::table('order')
                ->where('ord_id', $dis_data->dego_wor_id)
                ->update($update_date);

            $order_client = DB::table('order_client')
                ->where('orcl_ord_id', $dis_data->dego_wor_id)
                ->select('orcl_channel_unit', 'orcl_client_id', 'orcl_acc_subject_id', 'orcl_collect_state', 'orcl_name')
                ->first();
            $ord_data = DB::table('order')
                ->where('ord_id', $dis_data->dego_wor_id)
                ->select('ord_type', 'ord_actual_price', 'ord_remark', 'ord_order_number', 'ord_create_time', 'ord_service_type')
                ->first();
            $ord_plus_minus = 1;
            if ($ord_data->ord_actual_price < 0) {
                $ord_plus_minus = 2;
            }
            // 生成订单应收应付
            $ord_bill = ReceivableBill::create(
                $user_info, //用户信息
                3, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $dis_data->dego_wor_id, //原始id(订单id)
                $dis_data->dego_original_number, //应收账款单号/原始号(订单编号)
                $ord_data->ord_type, //客户类型：1.门店零售 2.来往单位
                $order_client->orcl_client_id, //会员id/来往单位id
                $order_client->orcl_channel_unit, //来往单位名称
                abs($ord_data->ord_actual_price), //结算金额
                date('Y-m-d H:i:s'), //结款时间
                $order_client->orcl_acc_subject_id, //会计科目id
                abs($ord_data->ord_actual_price), //实际金额
                0, //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                $ord_data->ord_remark,  //备注
                0, //已收金额
                '', //截止时间
                $ord_plus_minus, //金额正负1正2负值
                1, //显示类型：1订单收款 10订单退款
                2, //是否合并代收：1是2否
                $ord_data->ord_create_time,
                $order_client->orcl_collect_state //技师是否收钱：0未选择1是2否
            );
            if (!$ord_bill || !$update_state) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'发货失败！03']);
            }

            // 判断门店是否使用用友u8财务系统
            if (config('apiu8cloud.CODE_STARTS') && in_array($user_info->adm_shop_id, config('apiu8cloud.u8cloud_shop'))) {
                // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
                $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
                // 生成凭证单据
                if ($ord_data->ord_type == '1') {
                    $order_client->orcl_channel_unit = $order_client->orcl_name;
                } elseif ($ord_data->ord_type == '2') {
                    $order_client->orcl_channel_unit = $order_client->orcl_channel_unit;
                } elseif ($ord_data->ord_type == '3') {
                    $order_client->orcl_channel_unit = $order_client->orcl_channel_unit;
                }
                $vore_data = WorkOrder::voucherReceipts($user_info, $shop_id, 1, 0, '', $dis_data->dego_wor_id, $ord_data->ord_order_number, $ord_data->ord_actual_price, $recycle_amount, 0, $cost_price, $ord_data->ord_service_type, $ord_data->ord_type, $order_client->orcl_client_id, $order_client->orcl_channel_unit);
                if (!$vore_data) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'凭证单生成失败']);
                }
            }
        }

        // 仓库商品锁定表
        $wagl_id = DB::table('warehouse_goods_lock')
            ->where('wagl_original_correlation_id', $request['dego_id'])
            ->where('wagl_correlation_type', 2)
            ->value('wagl_id');
        if (!empty($wagl_id)) {
            $wagl_res = DB::table('warehouse_goods_lock')
                ->where('wagl_original_correlation_id', $request['dego_id'])
                ->where('wagl_correlation_type', 2)
                ->update(['wagl_update_time' => date('Y-m-d H:i:s'), 'wagl_state' => 2]);
        } else {
            $wagl_res =  true;
        }
        $wfgl_id = DB::table('warehouse_freight_goods_lock')
            ->where('wfgl_shop_id', $user_info->adm_shop_id)
            ->where('wfgl_original_id', $find_ord_id)
            ->where('wfgl_original_number', $find_order_number)
            ->where('wfgl_type', 1)
            ->value('wfgl_id');
        if (!empty($wfgl_id)) {
            $wfgl_res = DB::table('warehouse_freight_goods_lock')
                ->where('wfgl_shop_id', $user_info->adm_shop_id)
                ->where('wfgl_original_id', $find_ord_id)
                ->where('wfgl_original_number', $find_order_number)
                ->where('wfgl_type', 1)
                ->update(['wfgl_update_time' => date('Y-m-d H:i:s'), 'wfgl_state' => 2]);
        } else {
            $wfgl_res = true;
        }

        if ($dispatch_res && $wagl_res && $wfgl_res) {
            Common::addLog($user_info, getRealIp($request), '发货单', '发货', '发货单：' . $dis_data->dego_number . ' 发货成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'发货成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'发货失败']);
        }
    }

    // 发货单详情
    public function info(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyAppletDispatchController;
        $error_message = $verify_data->infoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::wechatGetUserInfo($request['api_token']);

        $select_field = "dego_order_type, dego_wor_id, dego_count, dego_out_ware_id, dego_type";
        $dispatch_info = new Dispatch();
        $return_data = $dispatch_info->info($user_info, $request->all(), $select_field);
        return response()->json($return_data);
    }
}
