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

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\Workbench\VerifyCashierDeskController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\DispatchBill;
use App\Http\Models\Api\OutinRecord;
use App\Http\Models\Api\ReceivableBill;
use App\Http\Models\Api\Warehouse;
use App\Http\Models\Api\CashierDesk;
use App\Http\Models\Services\ImageUpload;
use App\Http\Controllers\Api\WeChatPush;
use App\Http\Models\Services\Order;
use App\Http\Models\Services\OrderCache;
use App\Http\Models\Services\PublicSearch;
use App\Http\Models\Services\WarehouseLock;
use App\Http\Models\Services\Dispatch;
use App\Http\Models\Services\WarehouseManage\OutinStockLock;
use App\Services\Business\WashOrderService;

// 业务系统 -- 工作总台
class CashierDeskController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    public function index(Request $request)
    {
        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], 94);
        return response()->json(['code'=>200, 'msg'=>'success', 'list_button'=>$list_button]);
    }

    // 生成订单
    public function addOrder(Request $request)
    {
        // 判断请求中是否存在值并且不为空
        if (!$request->filled('service_adm_id')) {
            $request->offsetSet('service_adm_id', 0);
        }
        if (!$request->filled('ware_id')) {
            $request->offsetSet('ware_id', 0);
        }

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

        $neaten_goods_data = []; //整理后的仓库商品库存数据
        $goods_data = []; //提交的商品数据
        $goo_all_quantity = 0; //商品总数量
        $goo_all_price = 0; //商品总金额
        $orgo_goo_price_compare = 2; //商品金额比较:1小于成本金额2不小于成本金额
        $goods_data = json_decode($request['goods_data'], true);
        // 判断提交的商品参数
        if (empty($goods_data)) {
            // 救援单的可以不选商品
            if ($request['ord_service_type'] != 7) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'请选择商品']);
            }
        } else {
            foreach ($goods_data as $key => $value) {
                if (!isset($value['wago_id'])) {
                    $value['wago_id'] = 0;
                    $goods_data[$key]['wago_id'] = 0;
                }
                if (!is_numeric($value['wago_id']) || !is_numeric($value['goo_id']) || !in_array($value['goo_state'], [1, 3, 4, 5, 6, 7, 8]) || !is_numeric($value['goo_waon_class']) || !in_array($value['goo_inventory'], [1, 2])  || !is_numeric($value['goo_price']) || !is_numeric($value['goo_collection_price']) || !is_numeric($value['goo_quantity'])) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品参数类型错误']);
                }
                // goo_state 商品状态1正常3回收的商品4换货商品5赠品商品6备用电池7临时商品8旧货商品
                if ($value['goo_state'] != 4) {
                    // [仓库商品id][出库类型：良品/优先]，用于判断仓库是否有库存
                    if (isset($neaten_goods_data[$value['wago_id']][$value['goo_inventory']])) {
                        $neaten_goods_data[$value['wago_id']][$value['goo_inventory']]['goo_quantity'] += $value['goo_quantity'];
                    } else {
                        $neaten_goods_data[$value['wago_id']][$value['goo_inventory']] = $value;
                    }
                    $goo_all_quantity += $value['goo_quantity'];
                    $goo_all_price += $value['goo_quantity'] * $value['goo_price'];
                }
                // 工作总台开单的时候，判断一下商品金额小于当前进销存的成本，生成待审核状态订单，需要审核通过
                if (in_array($request['ord_service_type'], [1, 5, 7]) && !in_array($value['goo_state'], [5, 6, 7])) {
                    // 获取订单商品成本价
                    $orgo_goo_cost = DB::table('enters_sells_saves')
                        ->where('ense_goo_warehouse', $request['ware_id'])
                        ->where('ense_goo_waretype', $value['goo_waon_class'])
                        ->where('ense_goo_id', $value['goo_id'])
                        ->orderBy('ense_id', 'desc')
                        ->value('ense_end_price');
                    $orgo_data[$key]['orgo_goo_cost'] = $orgo_goo_cost * 100; //商品成本
                    if ($value['goo_price'] < $orgo_goo_cost) {
                        $orgo_goo_price_compare = 1;
                    }
                }
                // 仓库类别对应的商品，库存-出入库记录
                if (isset($wago_class_goods[$value['goo_inventory']][$value['goo_waon_class']][$value['goo_id']])) {
                    $wago_class_goods[$value['goo_inventory']][$value['goo_waon_class']][$value['goo_id']]['goo_quantity'] = $wago_class_goods[$value['goo_inventory']][$value['goo_waon_class']][$value['goo_id']]['goo_quantity'] + $value['goo_quantity'];
                } else {
                    $wago_class_goods[$value['goo_inventory']][$value['goo_waon_class']][$value['goo_id']] = $value;
                }
            }
        }

        // 选择虚拟加盟店生成订单
        if ($request['orcl_shipment_party'] == 4) {
            $request->offsetSet('ware_id', 0);
            if ($request['ord_type'] == 2) {
                $vish_chun_id = DB::table('virtual_shop')
                    ->where('vish_id', $request['service_shop_id'])
                    ->value('vish_chun_id');
                if ($request['ord_client_id'] == $vish_chun_id) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'虚拟加盟店与关联客户单位相同，无法派单！']);
                }
            }
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        $shop_versions = $user_info->shop_versions; //系统版本信息

        DB::beginTransaction();

        // 订单缓存表 清除缓存数据
        $order_cache = new OrderCache();
        $clear_return = $order_cache->clearOrderCache($user_info);
        if ($clear_return['code'] == 500) {
            DB::rollBack();
            return response()->json($clear_return);
        }

        // 生成订单数据
        $service_order = new Order();
        $order_data = $service_order->createOrder($user_info, $request->all());
        if ($order_data['code'] == 500) {
            DB::rollBack();
            return response()->json($order_data);
        }
        if (!empty($goods_data)) {
            $goods_data = $order_data['data']['goods_data'];
        }

        // 运营中心版本订单，商品金额有小于商品成本金额的,订单的工单状态改为12，此订单需要在订单列表审核通过
        if ($orgo_goo_price_compare == 1 && $shop_versions != 1) {
            // 订单的工单状态1未派工单2服务中3售后中4已完成5无工单6审核活动7待接单8锁定9速电撤销回收10终止11取消订单12超出可欠天数待审核
            $ord_wor_state_res = DB::table('order')
                ->where('ord_id', $order_data['data']['ord_id'])
                ->update(['ord_wor_state' => 12]);
        }

        // 添加订单备注
        if (!empty($request['ord_remark'])) {
            $wor_remark = orderRemark($user_info, $order_data['data']['ord_id'], 0, $request['ord_remark'], '工作总台');
        } else {
            $wor_remark = true;
        }

        $ord_data = DB::table('order')
            ->leftjoin('order_client as oc', 'oc.orcl_ord_id', '=', 'order.ord_id')
            ->where('ord_id', $order_data['data']['ord_id'])
            ->first(['ord_actual_price', 'orcl_assign_price']);
        $arrearage_state = true; //客户欠款状态
        // 有订单金额，不是退货单，不是铺货类型的情况判断客户单位可欠天数
        if (($ord_data->ord_actual_price > 0) && ($request['ord_service_type'] != 4) && $request['orcl_chin_type'] != 1) {
            // 判断是否通过可欠金额  可欠天数的判断
            $CashierDesk = new CashierDesk;
            $isExceed_res = $CashierDesk->isExceed($request->all(), $user_info, $ord_data->ord_actual_price);
            if (empty($isExceed_res)) {
                $arrearage_state = DB::table('order')
                    ->where('ord_id', $order_data['data']['ord_id'])
                    ->update(['ord_order_state' => 10, 'ord_wor_state' => 12]);
            }
        }

        // 订单类型：7救援单，没有选择商品的情况
        if ($request['ord_service_type'] == 7 && empty($goods_data)) {
            // 7. 生成操作记录
            $orlo_res = orderLog($user_info, $order_data['data']['ord_id'], 0, '生成订单');
            if ($orlo_res && $wor_remark) {
                DB::commit();
                Common::addLog($user_info, getRealIp($request), '工作总台', '生成订单', '生成订单：' . $order_data['data']['ord_order_number'] . '成功');
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'生成订单成功']);
            } else {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'生成订单失败']);
            }
        }

        /*
            锁定仓库商品库存处理
            虚拟加盟店订单商品没有库存，不需要锁定库存；
            退货单商品不需要锁定商品库存；
            运营中心派单商品不需要锁定商品库存；
            其他有商品的情况需要锁定商品库存
        */
        $wagl_data = [];
        if ($request['orcl_shipment_party'] != 4 && $request['orcl_shipment_party'] != 5 && $request['ord_service_type'] != 4) {
            if (!empty($neaten_goods_data)) {
                $ware_lock_return = WarehouseLock::warehouseLockInventory(
                    $user_info,
                    $request->all(),
                    $order_data,
                    $neaten_goods_data
                );
                if ($ware_lock_return['code'] == 500) {
                    DB::rollBack();
                    return response()->json($ware_lock_return);
                }
                // 查询仓位商品锁定表
                $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_ware_id', $request['ware_id'])
                    ->where('wfgl_correlation_type', 1)
                    ->where('wfgl_original_id', $order_data['data']['ord_id'])
                    ->where('wfgl_original_number', $order_data['data']['ord_order_number'])
                    ->where('wfgl_type', 1)
                    ->where('wfgl_state', 1)
                    ->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);
                $orgf_wfgl_key = 0;
                if (!empty($goods_data) && !empty($find_wfgl_data)) {
                    foreach ($goods_data as $key => $value) {
                        $digo_goo_quantity = $value['goo_quantity'];
                        foreach ($find_wfgl_data as $wfgl_key => $wfgl_value) { //从仓位商品表中扣除发货数量
                            if ($wfgl_value['wfgl_wago_id'] == $value['wago_id'] && $value['goo_inventory'] == $wfgl_value['wfgl_lock_type'] && $value['goo_waon_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']; //出库商品-仓位中锁定的数量
                                    // 订单商品仓位表
                                    $orgf_data[$orgf_wfgl_key]['orgf_shop_id'] = $user_info->adm_shop_id; //门店id
                                    $orgf_data[$orgf_wfgl_key]['orgf_ord_id'] = $order_data['data']['ord_id']; //订单id
                                    $orgf_data[$orgf_wfgl_key]['orgf_order_number'] = $order_data['data']['ord_order_number']; //订单单号
                                    $orgf_data[$orgf_wfgl_key]['orgf_orgo_id'] = $value['orgo_id']; //订单商品主键id
                                    $orgf_data[$orgf_wfgl_key]['orgf_wago_id'] = $value['wago_id']; //仓库商品主键id
                                    $orgf_data[$orgf_wfgl_key]['orgf_ware_id'] = $request['ware_id']; //仓库id
                                    $orgf_data[$orgf_wfgl_key]['orgf_wafr_id'] = $wfgl_value['wfgl_wafr_id']; //仓位id
                                    $orgf_data[$orgf_wfgl_key]['orgf_wafg_id'] = 0; //仓位商品主键id
                                    $orgf_data[$orgf_wfgl_key]['orgf_original_id'] = $order_data['data']['ord_id']; //原始单的id
                                    $orgf_data[$orgf_wfgl_key]['orgf_goo_id'] = $value['goo_id']; //商品id
                                    $orgf_data[$orgf_wfgl_key]['orgf_goo_inventory'] = $value['goo_inventory']; //出库类型1良品2优先
                                    $orgf_data[$orgf_wfgl_key]['orgf_outin_type'] = 1; //出入库类型：1出库2入库
                                    if ($digo_goo_quantity <= 0) { //出库商品-仓位中锁定的数量小于0，仓位锁定出库后还有剩余，出完了，跳出
                                        $orgf_data[$orgf_wfgl_key]['orgf_goo_quantity'] = $digo_goo_quantity + $wfgl_value['wfgl_lock_quantity']; //商品数量
                                        $find_wfgl_data[$wfgl_key]['wfgl_lock_quantity'] = abs($digo_goo_quantity);
                                        $orgf_wfgl_key++;
                                        break;
                                    } else {
                                        $orgf_data[$orgf_wfgl_key]['orgf_goo_quantity'] = $wfgl_value['wfgl_lock_quantity']; //商品数量
                                        $find_wfgl_data[$wfgl_key]['wfgl_lock_quantity'] = 0;
                                        $orgf_wfgl_key++;
                                    }
                                }
                            }
                        }
                    }
                    // 添加订单商品仓位记录
                    $orgf_res = DB::table('order_goods_freight')->insert($orgf_data);
                    unset($orgf_data);
                    if (!$orgf_res) {
                        DB::rollBack();
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'生成订单失败']);
                    }
                }
                $neaten_wago_id = []; //良品商品
                $priority_neaten_wago_id = []; //优先商品
                $wagl_key = 0;
                $wagl_lock_quantity = []; //仓库锁定表的商品锁定数量
                foreach ($neaten_goods_data as $wago_id => $wago_id_value) {
                    foreach ($wago_id_value as $goo_inventory => $goo_value) {
                        if ($goo_inventory == 1) {
                            // 良品商品锁定库存
                            $ware_id[$wago_id] = $request['ware_id'];
                            $wago_goo_id[$wago_id] = $goo_value['goo_id'];
                            $wago_goo_quantity[$wago_id] = $goo_value['goo_quantity'];
                            $wago_goo_inventory[$wago_id] = $goo_inventory;
                            $wago_goo_class[$wago_id] = $goo_value['goo_waon_class'];
                            $neaten_wago_id[] = $wago_id;
                        } else {
                            // 优先商品锁定库存
                            $priority_ware_id[$wago_id] = $request['ware_id'];
                            $priority_wago_goo_id[$wago_id] = $goo_value['goo_id'];
                            $priority_wago_goo_quantity[$wago_id] = $goo_value['goo_quantity'];
                            $priority_wago_goo_inventory[$wago_id] = $goo_inventory;
                            $priority_wago_goo_class[$wago_id] = $goo_value['goo_waon_class'];
                            $priority_neaten_wago_id[] = $wago_id;
                        }
                        // 仓库锁定表的商品锁定数量：良品+优先 总的锁定数量
                        if (isset($wagl_lock_quantity[$wago_id])) {
                            $wagl_lock_quantity[$wago_id] += $goo_value['goo_quantity'];
                        } else {
                            $wagl_lock_quantity[$wago_id] = $goo_value['goo_quantity'];
                        }
                    }

                    // 仓库商品锁定表
                    $wagl_data[$wagl_key]['wagl_shop_id'] = $user_info->adm_shop_id;
                    $wagl_data[$wagl_key]['wagl_ware_id'] = $request['ware_id'];
                    $wagl_data[$wagl_key]['wagl_wago_id'] = $wago_id;
                    $wagl_data[$wagl_key]['wagl_original_id'] = $order_data['data']['ord_id'];
                    $wagl_data[$wagl_key]['wagl_original_number'] = $order_data['data']['ord_order_number'];
                    $wagl_data[$wagl_key]['wagl_original_correlation_id'] = $order_data['data']['ord_id']; //关联id：订单id/发货单id/调拨单id
                    $wagl_data[$wagl_key]['wagl_correlation_type'] = 1; //关联类型：1订单2发货单3调拨单
                    $wagl_data[$wagl_key]['wagl_type'] = 1; //原始单类型：1订单2调拨单
                    $wagl_data[$wagl_key]['wagl_state'] = 1; //锁定状态：1下单锁定2出库解锁
                    $wagl_data[$wagl_key]['wagl_lock_quantity'] = $wagl_lock_quantity[$wago_id]; //商品锁定库存数量
                    $wagl_key++;
                }
            }
        }

        // 6. 订单类型为 发货单 生成发货单  虚拟加盟店不生成发货单(需要修改)
        if ($request['ord_service_type'] == 5 && $request['orcl_shipment_party'] != 4 && $request['orcl_shipment_party'] != 5) {
            $dibi_data = DispatchBill::create(
                $user_info,   //用户信息
                $request->all(),  //订单提交数据
                $goods_data,  //提交的商品数据
                1,  //类型：1.订单发货 2.工单发货
                $request['ware_id'],  //出库仓库id
                $order_data['data']['ord_order_number'],  //原始单号，订单号/工单号
                $order_data['data']['ord_id'],  //发货单关联的工单/订单id
                $order_data['data']['shop_id'],  //所属总店id
                $order_data['data']['ord_type'],  //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
                $order_data['data']['ord_client_id'],  //选择的客户id,会员id/单位id
                $goo_all_quantity  //发货总数量
            );
            if ($dibi_data['code'] == 500) {
                DB::rollBack();
                return response()->json($dibi_data);
            }
            foreach ($wagl_data as $key => $value) {
                $wagl_data[$key]['wagl_original_correlation_id'] = $dibi_data['dego_id']; //关联id：订单id/发货单id/调拨单id
                $wagl_data[$key]['wagl_correlation_type'] = 2; //关联类型：1订单2发货单3调拨单
            }
        } else {
            $ship_res = true;
        }
        // 添加仓库商品锁定数据
        if (!empty($wagl_data)) {
            $wagl_res = DB::table('warehouse_goods_lock')->insert($wagl_data);
            if (!$wagl_res) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'生成订单失败']);
            }
        }

        // 10. 订单类型为退货单 生成退换回收单
        if ($request['ord_service_type'] == 4 && $request['orcl_shipment_party'] != 4 && $request['orcl_shipment_party'] != 5) {
            $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
            // 10.1退换回收单表添加数据
            $rec_number = 'TH' . rand(100, 999) . date('mdHis') . rand(100000, 999999); // 回收单号
            $add_recycle['rec_cid'] = $user_info->adm_cid; //公司id
            $add_recycle['rec_shop_id'] = $user_info->adm_shop_id; //门店id
            $add_recycle['rec_superior_shop_id'] = $shop_id; //总店id
            $add_recycle['rec_date'] = date('Y-m-d'); //日期
            $add_recycle['rec_number'] = $rec_number; //回收单号
            $add_recycle['rec_ord_id'] = $order_data['data']['ord_id']; //订单id
            $add_recycle['rec_ord_order_number'] = $order_data['data']['ord_order_number']; //订单号
            $add_recycle['rec_source_type'] = 8; //类型 4 (工单号)退货单 5技师退回 6技师拒单 7技师终止 8(订单号)退货单
            $add_recycle['rec_price'] = $goo_all_price * 100; //退换总金额（单位：分）
            $add_recycle['rec_amount'] = $goo_all_quantity; //退换总数量
            $add_recycle['rec_state'] = 1; //回收状态 1.未回收 2.已回收
            $add_recycle['rec_type'] = $request['ord_type']; //买家类型 1.门店零售 2.来往单位
            $add_recycle['rec_ware_id'] =  $request['ware_id']; //仓库id
            $add_recycle['rec_create_adm_id'] = $user_info->adm_id; //创建人id
            $add_recycle['rec_remark'] = $request['ord_remark'] ? $request['ord_remark'] : ''; //备注
            $recycle_id = DB::table('recede_recycle')->insertGetId($add_recycle);

            // 10.2退换回收商品表添加数据
            foreach ($goods_data as $key => $value) {
                $rego_data[$key]['rego_rec_id'] = $recycle_id; //退换回收单id
                $rego_data[$key]['rego_ware_id'] = $request['ware_id']; //仓库id
                $rego_data[$key]['rego_waon_class'] = $value['goo_waon_class']; //仓库类别
                $rego_data[$key]['rego_wago_id'] = $value['orgo_id']; //仓库商品id
                $rego_data[$key]['rego_orgo_id'] = isset($value['orgo_id']) ? $value['orgo_id'] : 0; //订单商品主键id
                $rego_data[$key]['rego_goo_id'] = $value['goo_id']; //商品id
                $rego_data[$key]['rego_goo_price'] = $value['goo_price'] * 100; //回收价格（单位：分）
                $rego_data[$key]['rego_sell_number'] =  $value['goo_quantity']; //销售数量
                $rego_data[$key]['rego_recycle_number'] =  $value['goo_quantity']; //回收数量
                $rego_data[$key]['rego_goo_inventory'] =  $value['goo_inventory']; //出库类型1.良品 2.优先
                $find_goods_data = DB::table('goods')
                    ->where('goo_id', $value['goo_id'])
                    ->first(['goo_name', 'goo_goods_encode', 'goo_class']);
                if ($find_goods_data->goo_class == 1) { //类型：1自营商品2系统商品
                    // 查询商品附属表
                    $goaf_another_name = DB::table('goods_affiliate')
                        ->where('goaf_goo_id', $value['goo_id'])
                        ->where('goaf_shop_id', $user_info->adm_shop_id)
                        ->value('goaf_another_name');
                    if (!empty($goaf_another_name)) {
                        $find_goods_data->goo_name = $goaf_another_name;
                    }
                } else {
                    // 查询系统商品属性表
                    $gosa_another_name = DB::table('goods_system_affiliate')
                        ->where('gosa_goo_id', $value['goo_id'])
                        ->where('gosa_shop_id', $user_info->adm_shop_id)
                        ->value('gosa_another_name');
                    if (!empty($gosa_another_name)) {
                        $find_goods_data->goo_name = $gosa_another_name;
                    }
                }
                $rego_data[$key]['rego_goo_name'] = $find_goods_data->goo_name;
                $rego_data[$key]['rego_goo_goods_encode'] = $find_goods_data->goo_goods_encode;
            }
            $add_goods =  DB::table('recede_goods')->insert($rego_data);

            // 10.3 退换回收客户表添加数据
            $jucl_data['recl_rec_id'] = $recycle_id; //回收单id
            $jucl_data['recl_client_id'] = $request['ord_client_id']; //来往单位id/客户id
            $jucl_data['recl_name'] = $request['orcl_name']; //客户姓名
            $jucl_data['recl_phone'] = $request['orcl_phone']; //联系电话
            if ($request['ord_type'] == 2) {
                $jucl_data['recl_channel_unit'] = $request['orcl_channel_unit']; //渠道单位
                $mem_res = true;
            } else {
                if (empty($request['ord_client_id'])) {
                    // 零售类型，临时会员，没有会员id
                    $mem_res = true;
                } else {
                    // 零售类型，会员对应的退货数量加1
                    $mem_res =  DB::table('member')
                        ->where('mem_id', $request['ord_client_id'])
                        ->increment('mem_retreat_trade');
                }
            }
            $add_client =  DB::table('recede_client')->insert($jucl_data);
            // 门店版退货单入库
            if ($shop_versions == 1) {
                if ($add_client && $recycle_id && $add_goods && $wor_remark && $ship_res) {
                    $request_recycle['rec_id'] = $recycle_id; //退货回收单id
                    $request_recycle['rec_amount'] = 0;
                    $request_recycle['rec_ware_id'] = $request['ware_id']; //仓库id
                    $request_recycle['rec_remark'] = $request['ord_remark']; //备注
                    $request_recycle['rec_date'] = date('Y-m-d H:i:s'); //日期
                    $goo_data = json_decode($request['goods_data'], true);
                    $recy_res = $this->returnRecycle($user_info, $request_recycle, $goo_data);
                    if ($recy_res['code'] == 200) {
                        $recy_res == true;
                    } else {
                        return response()->json($recy_res);
                    }
                } else {
                    $recy_res = true;
                }
            } else {
                $recy_res = true;
            }

            if (!$add_client || !$mem_res || !$add_goods || !$recycle_id || !$recy_res) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'生成订单失败']);
            }
        } else {
            $recy_res = true;
        }

        // 遍历仓库类型数据，处理固定仓库对应仓库类型的库存-出入库记录
        if (!empty($wago_class_goods) && $request['ord_service_type'] != 4 && $request['orcl_shipment_party'] != 4 && $request['orcl_shipment_party'] != 5) {
            $ware_return_data = WarehouseLock::warehouseLockRecord(
                $user_info,
                $request->all(),
                $order_data,
                $wago_class_goods
            );
            if ($ware_return_data['code'] == 500) {
                DB::rollBack();
                return response()->json($ware_return_data);
            }
        }

        // 7. 生成操作记录
        $orlo_res = orderLog($user_info, $order_data['data']['ord_id'], 0, '生成订单');
        if ($orlo_res && $wor_remark && $arrearage_state && $recy_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '工作总台', '生成订单', '生成订单：' . $order_data['data']['ord_order_number'] . '成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'生成订单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'生成订单失败']);
        }
    }

    /**
     * [returnRecycle 生成退货单调用退换入库的代码]
     * @param  [array] $user_info [用户信息]
     * @param  [array] $request   [前端提交的数据]
     * @param  [array] $goo_data  [前端提交的商品数据]
     * @return [type]             [description]
     */
    private function returnRecycle(
        $user_info,
        $request,
        $goo_data
    ) {
        // 获取退货回收单数据
        $find_recede = DB::table('recede_recycle as re')
            ->leftjoin('admin as a', 'a.adm_id', '=', 're.rec_create_adm_id')
            ->leftjoin('recede_client as recl', 'recl.recl_rec_id', '=', 're.rec_id')
            ->where('rec_id', $request['rec_id'])
            ->select('rec_number', 'rec_ord_id', 'rec_ord_order_number', 'rec_create_time', 'rec_state', 'rec_amount', 'rec_remark', 'rec_date', 'rec_price', 'rec_mobile_ware_id', 'rec_source_type', 'rec_ware_id', 'adm_name as rec_create_adm_name', 'rec_waon_class', 'rec_id', 'rec_type', 'recl_client_id', 'recl_channel_unit', 'recl_name')
            ->first();
        if (empty($find_recede)) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'当前退换入库单不存在'];
        }

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

        // 来源类型1. 售后退货 2. 工单退货(换货单) 3 页面新增 4 (工单号)退货单 5技师退回 6技师拒单 7技师终止 8(订单号)退货单
        if ($find_recede->rec_source_type == 8) {
            // 根据原始单id,查询到订单id
            $find_order = DB::table('order')
                ->where('ord_id', $find_recede->rec_ord_id)
                ->select('ord_id as wor_order_id', 'ord_order_number as wor_order_number', 'ord_type', 'ord_client_id', 'ord_collection_price', 'ord_service_type as wor_service_type')
                ->first();
        }

        $voucher_cost = 0;
        $goo_rec_amount = 0; //回收商品总数量
        $goo_all_price = 0; //回收商品总金额

        $shop_state = true;
        if (in_array($shop_id, config('apisystem.NO_SHOPID'))) {
            $shop_state = false;
        }
        $goo_ids = array_column($goo_data, 'goo_id');
        // 查询商品名称
        $find_goods = DB::table('goods')
            ->where(function ($query) use ($user_info, $shop_state) {
                if ($shop_state) {
                    $query->where('goo_cid', 0)
                        ->orwhere('goo_cid', $user_info->adm_cid);
                } else {
                    $query->where('goo_cid', $user_info->adm_cid);
                }
            })
            ->where(function ($query) use ($user_info, $shop_state) {
                if ($shop_state) {
                    $query->where('goo_shop_id', 0)
                        ->orwhere('goo_shop_id', $user_info->adm_shop_id);
                } else {
                    $query->where('goo_shop_id', $user_info->adm_shop_id);
                }
            })
            ->whereIn('goo_id', $goo_ids)
            ->select('goo_id', 'goo_name', 'goo_goods_encode', 'goo_class')
            ->get()->toArray();
        $find_goods = array_column($find_goods, null, 'goo_id');
        $goo_id = array_column($find_goods, 'goo_id');
        // 查询商品附属表信息
        $goaf_data = DB::table('goods_affiliate')
            ->where('goaf_shop_id', $user_info->adm_shop_id)
            ->whereIn('goaf_goo_id', $goo_id)
            ->pluck('goaf_another_name', 'goaf_goo_id')
            ->toArray();
        // 查询系统商品属性表信息
        $gosa_data = DB::table('goods_system_affiliate')
            ->where('gosa_shop_id', $user_info->adm_shop_id)
            ->whereIn('gosa_goo_id', $goo_id)
            ->pluck('gosa_another_name', 'gosa_goo_id')
            ->toArray();
        foreach ($find_goods as $key => $value) {
            if ($value->goo_class == 2 && isset($gosa_data[$value->goo_id]) && !empty($gosa_data[$value->goo_id])) {
                $find_goods[$key]->goo_name = $gosa_data[$value->goo_id];
            }
            if (isset($goaf_data[$value->goo_id]) && !empty($goaf_data[$value->goo_id])) { //商品别名
                $find_goods[$key]->goo_name = $goaf_data[$value->goo_id];
            }
        }

        $request_goo_waon_class = []; //仓库类别
        $request_goo_amount = [];

        // 退货单入库
        foreach ($goo_data as $key => $value) {
            if (!is_numeric($value['goo_id']) || $value['goo_id'] < 0  || !is_numeric($value['goo_price']) || $value['goo_price'] < 0 || !is_numeric($value['goo_quantity']) || $value['goo_quantity'] < 0) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'参数类型错误'];
            }

            // 回收单商品表重新添加的商品数据
            $rego_data[$key]['rego_rec_id'] = $request['rec_id']; //回收id
            $rego_data[$key]['rego_ware_id'] = $request['rec_ware_id']; //仓库id
            $rego_data[$key]['rego_waon_class'] = $value['goo_waon_class']; //仓库类别
            // $rego_data[$key]['rego_wago_id'] = $request['rec_goo_wago_id'][$key]; //仓库商品id
            $rego_data[$key]['rego_goo_id'] = $value['goo_id']; //商品id
            $rego_data[$key]['rego_goo_name'] = $find_goods[$value['goo_id']]->goo_name; //商品名称
            $rego_data[$key]['rego_goo_goods_encode'] = $find_goods[$value['goo_id']]->goo_goods_encode; //检索编码
            $rego_data[$key]['rego_goo_price'] = $value['goo_price'] * 100; //回收单价
            $rego_data[$key]['rego_sell_number'] = $value['goo_quantity']; //销售数量
            $rego_data[$key]['rego_recycle_number'] = $value['goo_quantity']; //单个商品回收总数量
            $rego_data[$key]['rego_fine_quantity'] = 0; //良品回收数量
            $rego_data[$key]['rego_priority_quantity'] = $value['goo_quantity']; //优先回收数量
            $rego_data[$key]['rego_unchecked_quantity'] = 0; //残损回收数量
            if ($rego_data[$key]['rego_fine_quantity'] > '0') {
                $rego_data[$key]['rego_goo_inventory'] = 1; //1良品
            } elseif ($rego_data[$key]['rego_priority_quantity'] > '0') {
                $rego_data[$key]['rego_goo_inventory'] = 2; //2优先
            } elseif ($rego_data[$key]['rego_unchecked_quantity'] > '0') {
                $rego_data[$key]['rego_goo_inventory'] = 3; //3待检测
            }
            $goo_all_price += $value['goo_price'] * $value['goo_quantity']; //回收总金额

            $goo_recycle_amount[$key] = $value['goo_quantity'];
            $goo_inventory[$key] = 2;

            // 出入库记录需要的的商品数租
            $oure_goods_data[$value['goo_id']]['goo_quantity'] = $value['goo_quantity']; //出入库商品数量
            $oure_goods_data[$value['goo_id']]['goo_inventory'] = $goo_inventory[$key]; //出入库商品类型，类型1良品2优先

            // 出入库记录需要
            $oure_goods_id[$value['goo_id']] = $value; //出入库商品id
            $oure_goods_quantity[$value['goo_id']] = $value['goo_quantity']; //出入库商品数量
            $oure_goods_inventory[$value['goo_id']] = $goo_inventory[$key]; //出入库商品类型，类型1良品2优先

            $request_goo_waon_class[$value['goo_id']] = $value['goo_waon_class'];
            if (isset($request_goo_amount[$value['goo_id']])) {
                $request_goo_amount[$value['goo_id']] += $value['goo_quantity'];
            } else {
                $request_goo_amount[$value['goo_id']] = $value['goo_quantity'];
            }

            $wago_class[] = $value['goo_waon_class']; //仓库类别
            if (isset($wogo_class_goods[$value['goo_waon_class']][$value['goo_id']])) {
                $wogo_class_goods[$value['goo_waon_class']][$value['goo_id']] += $value['goo_quantity']; //仓库类型对应的商品，出入库记录
            } else {
                $wogo_class_goods[$value['goo_waon_class']][$value['goo_id']] = $value; //仓库类型对应的商品，出入库记录
            }

            $goo_stock_number[$value['goo_id']] = $value['goo_quantity']; //数量
            $goo_wago_class[$value['goo_id']] = $value['goo_waon_class']; //仓库类别
            $goo_rec_amount += $value['goo_quantity']; //回收总数量
        }
        // 2.1 删除原来收回单id对应的商品数据
        $del_rego = DB::table('recede_goods')
            ->where('rego_rec_id', $request['rec_id'])
            ->delete();
        // 2.2 重新添加提交的商品数据
        $add_rego =  DB::table('recede_goods')->insert($rego_data);

        // 3 更改退换回收单表数据
        $update_recycle['rec_price'] = $goo_all_price * 100; //回收总金额（单位：分）
        $update_recycle['rec_amount'] = $goo_rec_amount; //回收总数量
        $update_recycle['rec_remark'] = $request['rec_remark'] ? $request['rec_remark'] : ''; //备注
        $update_recycle['rec_state'] = 2; //回收状态 1.未回收 2.已回收
        $update_recycle['rec_date'] = $request['rec_date']; //日期
        $update_recycle['rec_ware_id'] = $request['rec_ware_id']; //回收仓库
        $update_recycle['rec_record_adm_id'] = $user_info->adm_id; //记录人
        $update_recycle['rec_update_time'] = date("Y-m-d H:i:s"); //更新时间
        $rec_res = DB::table('recede_recycle')
            ->where('rec_id', $request['rec_id'])
            ->update($update_recycle);
        // 仓库类别
        $wago_class = array_unique($wago_class);

        // 4. 仓库商品表
        // 4.1 查询商品库存数量
        $warehouse_goods = DB::table('warehouse_goods')
            ->where('wago_ware_id', $request['rec_ware_id'])
            ->whereIn('wago_class', $wago_class)
            ->whereIn('wago_goo_id', $goo_ids)
            ->select('wago_id', 'wago_class', 'wago_stock_number', 'wago_priority_stock_number', 'wago_unchecked_stock_number', 'wago_goo_id', 'wago_stock_amount', 'wago_priority_stock_amount', 'wago_unchecked_stock_amount')
            ->get()->toArray();

        if (empty($warehouse_goods)) {
            $ware_edit_res = true;
        } else {
            // 4.2 仓库商品表中已存在的商品，更改库存数量，整理更改SQL语句
            $sql = 'UPDATE `faster_warehouse_goods` SET ';
            $stock_number_sql = ''; //良品库存数量(仓库+仓位)
            $priority_stock_number_sql = ''; //优先库存数量(仓库+仓位)
            $unchecked_stock_number_sql = ''; //待检测数量(仓库+仓位)
            $stock_amount_sql = ''; //仓库良品库存数量
            $priority_stock_amount_sql = ''; //仓库优先库存数量
            $unchecked_stock_amount_sql = ''; //仓库待检测库存数量
            $update_time_sql = '';
            $ids = '';
            foreach ($warehouse_goods as $key => $value) {
                // 更改良品库存数量(仓库+仓位)
                $stock_number_sql = $stock_number_sql . ' WHEN ' . $value->wago_id . ' THEN wago_stock_number + 0';
                // 更改优先库存数量(仓库+仓位)
                $priority_stock_number_sql = $priority_stock_number_sql . ' WHEN ' . $value->wago_id . ' THEN wago_priority_stock_number + ' . $goo_stock_number[$value->wago_goo_id];
                // 更改待检测数量(仓库+仓位)
                $unchecked_stock_number_sql = $unchecked_stock_number_sql . ' WHEN ' . $value->wago_id . ' THEN wago_unchecked_stock_number + 0';

                // 更改仓库良品库存数量
                $stock_amount_sql = $stock_amount_sql . ' WHEN ' . $value->wago_id . ' THEN wago_stock_amount + 0';
                // 更改仓库优先库存数量
                $priority_stock_amount_sql = $priority_stock_amount_sql . ' WHEN ' . $value->wago_id . ' THEN wago_priority_stock_amount + ' . $goo_stock_number[$value->wago_goo_id];
                // 更改仓库待检测库存数量
                $unchecked_stock_amount_sql = $unchecked_stock_amount_sql . ' WHEN ' . $value->wago_id . ' THEN wago_unchecked_stock_amount + 0';

                // 更改时间
                $update_time_sql = $update_time_sql . ' WHEN ' . $value->wago_id;
                $update_time_sql = $update_time_sql . ' THEN "' . date('Y-m-d H:i:s') . '"';

                $ids = $ids . $value->wago_id . ',';
                // 删除已更改的商品数据
                unset($goo_stock_number[$value->wago_goo_id]);
            }
            $sql = $sql . ' `wago_stock_number`=  CASE `wago_id` ' . $stock_number_sql . ' END,';
            $sql = $sql . ' `wago_priority_stock_number`=  CASE `wago_id` ' . $priority_stock_number_sql . ' END,';
            $sql = $sql . ' `wago_unchecked_stock_number`=  CASE `wago_id` ' . $unchecked_stock_number_sql . ' END,';
            $sql = $sql . ' `wago_stock_amount`=  CASE `wago_id` ' . $stock_amount_sql . ' END,';
            $sql = $sql . ' `wago_priority_stock_amount`=  CASE `wago_id` ' . $priority_stock_amount_sql . ' END,';
            $sql = $sql . ' `wago_unchecked_stock_amount`=  CASE `wago_id` ' . $unchecked_stock_amount_sql . ' END,';
            $sql = $sql . ' `wago_update_time`=  CASE `wago_id` ' . $update_time_sql . ' END';
            $sql = $sql . ' WHERE `wago_id` IN (' . trim($ids, ',') . ')';
            $ware_edit_res = DB::update($sql);
        }

        // 4.3 仓库商品表中没有的商品，新增仓库商品
        if (!empty($warehouse_goods) && empty($goo_stock_number)) {
            $ware_add_res = true;
        } else {
            $num = 0;
            foreach ($goo_stock_number as $key => $value) {
                $ware_add_data[$num]['wago_ware_id'] = $request['rec_ware_id'];
                $ware_add_data[$num]['wago_class'] = $goo_wago_class[$key];
                $ware_add_data[$num]['wago_goo_id'] = $key;
                $ware_add_data[$num]['wago_stock_number'] = 0;
                $ware_add_data[$num]['wago_priority_stock_number'] = $value;
                $ware_add_data[$num]['wago_unchecked_stock_number'] = 0;
                $ware_add_data[$num]['wago_stock_amount'] = 0; //仓库良品库存数量
                $ware_add_data[$num]['wago_priority_stock_amount'] = $value; //仓库优先库存数量
                $ware_add_data[$num]['wago_unchecked_stock_amount'] = 0; //仓库待检测库存数量
                $num++;
            }
            $ware_add_res = DB::table('warehouse_goods')->insert($ware_add_data);
        }

        $find_ware = DB::table('warehouse_onhand')
            ->where('waon_ware_id', '=', $request['rec_ware_id'])
            ->whereIn('waon_class', $wago_class)
            ->select('waon_all_amount', 'waon_stock_fine_amount', 'waon_lock_fine_amount', 'waon_stock_unchecked_amount', 'waon_stock_priority_amount', 'waon_lock_priority_amount')
            ->first();
        // 5.修改仓库表 总库存量
        $waon_update_data['waon_all_amount'] = $find_ware->waon_all_amount + $goo_rec_amount;
        $waon_update_data['waon_stock_fine_amount'] = $find_ware->waon_stock_fine_amount;
        $waon_update_data['waon_stock_priority_amount'] = $find_ware->waon_stock_priority_amount + $goo_rec_amount;
        $waon_update_data['waon_stock_unchecked_amount'] = $find_ware->waon_stock_unchecked_amount;
        $waon_update_data['waon_update_time'] = date('Y-m-d H:i:s');

        $update_ware = DB::table('warehouse_onhand')
            ->where('waon_ware_id', $request['rec_ware_id'])
            ->whereIn('waon_class', $wago_class)
            ->update($waon_update_data);
        // 来源类型1. 售后退货 2. 工单退货(换货单) 3 页面新增 4 (工单号)退货单 5技师退回 6技师拒单 7技师终止 8(订单号)退货单
        if ($find_recede->rec_source_type == 8) {
            $oure_type = 13;
        }

        $osld_out_key = 0;
        foreach ($wogo_class_goods as $waon_class_key => $class_goods_data) {
            // 查询仓库类别的进销存计算方式
            $goo_all_amount = 0;
            foreach ($class_goods_data as $goo_id_key => $value) {
                // 查询出库类型1良品2优先
                $goo_inventory = DB::table('recede_goods')
                    ->where('rego_rec_id', $request['rec_id'])
                    ->where('rego_goo_id', $goo_id_key)
                    ->value('rego_goo_inventory');
                // 出入库记录需要的的商品数组
                $oure_goods_data[$waon_class_key][$goo_id_key]['goo_quantity'] = $request_goo_amount[$goo_id_key]; //出入库商品数量
                $oure_goods_data[$waon_class_key][$goo_id_key]['goo_inventory'] = $goo_inventory; //出入库商品类型，类型1良品2优先
                $goo_all_amount += $request_goo_amount[$goo_id_key];

                // 出入库记录需要
                $oure_goods_id[$goo_id_key] = $goo_id_key; //出入库商品id
                $oure_goods_quantity[$goo_id_key] = $request_goo_amount[$goo_id_key]; //出入库商品数量
                $oure_goods_inventory[$goo_id_key] = $goo_inventory; //出入库商品类型，类型1良品2优先
                $oure_goods_price[$goo_id_key] = $value['goo_price']; //退货入库的商品金额

                // 库存锁定-出入库记录表
                $osld_goo_data[$osld_out_key]['goo_waon_class'] = $value['goo_waon_class']; //仓库类别：1货物仓2非货物仓3旧货仓4临时仓
                $osld_goo_data[$osld_out_key]['goo_id'] = $value['goo_id']; //商品id
                $osld_goo_data[$osld_out_key]['goo_number'] = $value['goo_quantity']; //商品数量
                $osld_goo_data[$osld_out_key]['goo_out_in_type'] = 2; //出入库类型：1出库2入库3锁定4取消锁定
                $osld_goo_data[$osld_out_key]['goo_inventory'] = $goo_inventory; //类型1良品2优先3待检测
                // 查询仓库商品库存数量
                $find_wago_data = DB::table('warehouse_goods')
                    ->where('wago_ware_id', $request['rec_ware_id'])
                    ->where('wago_class', $value['goo_waon_class'])
                    ->where('wago_goo_id', $goo_id_key)
                    ->select('wago_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity', 'wago_unchecked_stock_number')
                    ->first();
                if ($goo_inventory == 1) { //良品
                    $osld_goo_data[$osld_out_key]['old_stock_number'] = $find_wago_data->wago_stock_number - $value['goo_quantity']; //旧的商品良品库存数量
                    $osld_goo_data[$osld_out_key]['old_stock_lock_number'] = $find_wago_data->wago_lock_quantity; //旧的商品良品库存锁定数量
                    $osld_goo_data[$osld_out_key]['old_priority_number'] = $find_wago_data->wago_priority_stock_number; //旧的商品优先库存数量
                    $osld_goo_data[$osld_out_key]['old_priority_lock_number'] = $find_wago_data->wago_priority_lock_quantity; //旧的商品优先库存锁定数量
                    $osld_goo_data[$osld_out_key]['old_unchecked_number'] = $find_wago_data->wago_unchecked_stock_number; //旧的商品待检测库存数量
                    $osld_goo_data[$osld_out_key]['new_stock_number'] = $find_wago_data->wago_stock_number; //新的商品良品库存数量
                    $osld_goo_data[$osld_out_key]['new_stock_lock_number'] = $find_wago_data->wago_lock_quantity; //新的商品良品库存锁定数量
                    $osld_goo_data[$osld_out_key]['new_priority_number'] = $find_wago_data->wago_priority_stock_number; //新的商品优先库存数量
                    $osld_goo_data[$osld_out_key]['new_priority_lock_number'] = $find_wago_data->wago_priority_lock_quantity; //新的商品优先库存锁定数量
                    $osld_goo_data[$osld_out_key]['new_unchecked_number'] = $find_wago_data->wago_unchecked_stock_number; //新的商品待检测库存数量
                } elseif ($goo_inventory == 2) { //优先
                    $osld_goo_data[$osld_out_key]['old_stock_number'] = $find_wago_data->wago_stock_number; //旧的商品良品库存数量
                    $osld_goo_data[$osld_out_key]['old_stock_lock_number'] = $find_wago_data->wago_lock_quantity; //旧的商品良品库存锁定数量
                    $osld_goo_data[$osld_out_key]['old_priority_number'] = $find_wago_data->wago_priority_stock_number - $value['goo_quantity']; //旧的商品优先库存数量
                    $osld_goo_data[$osld_out_key]['old_priority_lock_number'] = $find_wago_data->wago_priority_lock_quantity; //旧的商品优先库存锁定数量
                    $osld_goo_data[$osld_out_key]['old_unchecked_number'] = $find_wago_data->wago_unchecked_stock_number; //旧的商品待检测库存数量
                    $osld_goo_data[$osld_out_key]['new_stock_number'] = $find_wago_data->wago_stock_number; //新的商品良品库存数量
                    $osld_goo_data[$osld_out_key]['new_stock_lock_number'] = $find_wago_data->wago_lock_quantity; //新的商品良品库存锁定数量
                    $osld_goo_data[$osld_out_key]['new_priority_number'] = $find_wago_data->wago_priority_stock_number; //新的商品优先库存数量
                    $osld_goo_data[$osld_out_key]['new_priority_lock_number'] = $find_wago_data->wago_priority_lock_quantity; //新的商品优先库存锁定数量
                    $osld_goo_data[$osld_out_key]['new_unchecked_number'] = $find_wago_data->wago_unchecked_stock_number; //新的商品待检测库存数量
                }
                $osld_goo_data[$osld_out_key]['osld_update_time'] = date('Y-m-d H:i:s'); //更新时间
                $osld_goo_data[$osld_out_key] = (Object)$osld_goo_data[$osld_out_key];
                $osld_out_key++;
            }
            $find_ware = DB::table('warehouse_onhand')
                ->where('waon_ware_id', $request['rec_ware_id'])
                ->where('waon_class', $waon_class_key)
                ->select('waon_stock_fine_amount', 'waon_lock_fine_amount', 'waon_stock_unchecked_amount', 'waon_stock_priority_amount', 'waon_lock_priority_amount')
                ->first();
            // 1. 新增一条入库记录
            $oure_goods_data = $oure_goods_data[$waon_class_key];
            $oure_class_goo_id = array_keys($oure_goods_data);
            $oure_res = OutinRecord::addition(
                $user_info, //用户信息
                $find_order->wor_order_id, //原始单的关联id
                $find_order->wor_order_number, //原始单的关联单号
                1, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后
                $find_recede->rec_type, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
                $find_recede->recl_client_id, //选择的客户id,会员id/单位id
                $find_recede->rec_number, //原始单号
                $request['rec_ware_id'], //入库仓库id
                0, //出库仓库id
                $goo_all_amount, //出库的商品总量
                $oure_type, //类型 5.退换回收单 9.发货单 10移动仓出库 11换货出库12换货入库13退货入库14退货出库
                3, //操作类型：1锁定库存2出库3入库4调货5发货
                $find_ware->waon_stock_fine_amount, //良品总库存
                $find_ware->waon_lock_fine_amount, //良品锁定数量
                $find_ware->waon_stock_priority_amount, //优先总库存
                $find_ware->waon_lock_priority_amount, //优先锁定数量
                $find_ware->waon_stock_unchecked_amount, //待检测总库存
                2, //出入库类型：1出库，2入库
                $waon_class_key, //仓库类别
                $oure_goods_id, //数组，商品id
                $oure_goods_quantity, //数组，商品数量
                $oure_goods_inventory, //数组，出库类型1良品2优先
                [], //仓位id
                $oure_class_goo_id, //仓库类别下的商品id
                $oure_goods_price //退货入库的商品金额
            );
            // 库存锁定-出入库记录
            $oslr_res = OutinStockLock::addition(
                $user_info, //用户信息
                $find_order->wor_order_id, //原始单的关联id
                $find_order->wor_order_number, //原始单的关联单号
                6, //原始单的关联类型1.订单2.调拨单3.采购单4.销售单5.旧货回收6.退货入库7.售后
                $find_recede->rec_type, //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
                $find_recede->recl_client_id, //选择的客户id,会员id/单位id
                $find_recede->rec_number, //原始单号
                $request['rec_ware_id'], //出库/入库的仓库id
                $goo_all_amount, //出库/入库总数量
                13, //类型：1锁定库存2取消锁定3调拨单4旧货回收单5退换回收单6订单出库7部分入库8部分出库9发货单10移动仓出库11换货出库12换货入库13退货入库14退货出库15盘库单
                $find_ware->waon_stock_fine_amount, //良品总库存
                $find_ware->waon_lock_fine_amount, //良品锁定数量
                $find_ware->waon_stock_priority_amount, //优先总库存
                $find_ware->waon_lock_priority_amount, //优先锁定数量
                $find_ware->waon_stock_unchecked_amount, //待检测总库存
                2, //出入库类型：1出库，2入库
                $osld_goo_data
            );
            unset($osld_goo_data);
            if ($find_recede->rec_source_type == 8) {
                // 查询
                $find_goods = DB::table('recede_goods')
                    ->where('rego_rec_id', $request['rec_id'])
                    ->select('rego_goo_id as goo_id', 'rego_ware_id', 'rego_waon_class', 'rego_wago_id', 'rego_recycle_number')
                    ->get()->toArray();
                foreach ($find_goods as $keys => $values) {
                    $newprice = DB::table('enters_sells_saves')
                        ->where('ense_goo_id', $values->goo_id)
                        ->where('ense_goo_warehouse', $request['rec_ware_id'])
                        ->where('ense_goo_waretype', $values->rego_waon_class)
                        ->where('ense_order_number', $find_recede->rec_ord_order_number)
                        ->orderBy('ense_id', 'desc')
                        ->value('ense_end_price');
                    $newprice = sprintf('%.2f', $newprice);
                    if ($newprice) {
                        $voucher_cost += $newprice * $values->rego_recycle_number;
                    } else {
                        $voucher_cost = 0;
                    }
                    // 修改订单商品成本
                    $date = date('Y-m-d H:i:s');
                    $orgo_edit_data['orgo_goo_cost'] = $newprice * 100;
                    $orgo_edit_data['orgo_update_time'] = $date;
                    // 修改订单表的更新时间
                    $orgo_edit_data['ord_update_time'] = $date;
                    $orgo_edit_res = DB::table('order_goods as orgo')
                        ->leftjoin('order as ord', 'ord.ord_id', '=', 'orgo.orgo_ord_id')
                        ->where('orgo_ord_id', $find_recede->rec_ord_id)
                        ->where('orgo_order_number', $find_recede->rec_ord_order_number)
                        ->where('orgo_ware_id', $request['rec_ware_id'])
                        ->where('orgo_waon_class', $values->rego_waon_class)
                        ->where('orgo_goo_id', $values->goo_id)
                        ->update($orgo_edit_data);
                }
                if ($find_recede->rec_type == '1') {
                    $find_recede->recl_channel_unit = $find_recede->recl_name;
                } elseif ($find_recede->rec_type == '2') {
                    $find_recede->recl_channel_unit = $find_recede->recl_channel_unit;
                }
            }
        }

        // 来源类型：8(订单号)退货单,无技师流程的退货单
        if ($find_recede->rec_source_type == 8) {
            // 更改订单表数据
            $edit_order['ord_wor_state'] = 4;
            $edit_order['ord_order_price'] = '-' . $goo_all_price * 100;
            $edit_order['ord_actual_price'] = '-' . $goo_all_price * 100;
            $edit_order['ord_goods_quantity'] = $goo_all_amount;
            $edit_order['ord_remark'] = $request['rec_remark'] ? $request['rec_remark'] : ''; //备注
            $edit_order['ord_update_time'] = date("Y-m-d H:i:s"); //更新时间
            $edit_ord_res = DB::table('order')
                ->where('ord_id', $find_order->wor_order_id)
                ->update($edit_order);

            $client_name = DB::table('order_client')
                ->where('orcl_ord_id', $find_order->wor_order_id)
                ->value('orcl_channel_unit');
            // 查询订单创建时间
            $ord_create_time = DB::table('order')
                ->where('ord_id', $find_order->wor_order_id)
                ->value('ord_create_time');
            // 生成应收应付
            $ord_bill = ReceivableBill::create(
                $user_info, //用户信息
                3, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $find_order->wor_order_id, //原始id(订单id)
                $find_order->wor_order_number, //应收账款单号/原始号(订单编号)
                $find_order->ord_type, //客户类型：1.门店零售 2.来往单位
                $find_order->ord_client_id, //会员id/来往单位id
                $client_name, //来往单位名称
                abs($edit_order['ord_actual_price']), //结算金额(应收金额)
                '', //结款时间
                0, //会计科目id
                0, //实际金额(应收金额)
                0, //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                $edit_order['ord_remark'],  //备注
                0,  //已收金额
                '', //截止时间
                2, //金额正负1正   2负值
                10, //显示类型：10订单退款(退货单)
                2, //是否合并代收：1是2否
                $ord_create_time
            );
            // 如果订单有代收金额，生成代收应收应付
            if ($find_order->ord_collection_price) {
                $collection_ord_bill = ReceivableBill::create(
                    $user_info, //用户信息
                    3, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                    0, //应收账款id
                    $find_order->wor_order_id, //原始id(订单id)
                    $find_order->wor_order_number, //应收账款单号/原始号(订单编号)
                    $find_order->ord_type, //客户类型：1.门店零售 2.来往单位
                    $find_order->ord_client_id, //会员id/来往单位id
                    $client_name, //来往单位名称
                    $find_order->ord_collection_price, //结算金额(应收金额)
                    '', //结款时间
                    0, //会计科目id
                    0, //实际金额(应收金额)
                    0, //抹零金额
                    1,  //状态：1.未核销 2.已核销
                    1,  //应收账单id是否是自己 1.不是 2.是
                    $edit_order['ord_remark'],  //备注
                    0,  //已收金额
                    '', //截止时间
                    1, //金额正负1正   2负值
                    2, //显示类型： 2受托代收（订单代收）10订单退款(退货单)
                    2, //是否合并代收：1是2否
                    $ord_create_time
                );
            } else {
                $collection_ord_bill = true;
            }
            if (!$edit_ord_res || !$ord_bill || !$collection_ord_bill) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'退换入库失败'];
            }
        }

        if ($oure_res && $del_rego && $add_rego && $rec_res && $ware_edit_res && $ware_add_res && $update_ware) {
            return ['code'=>200, 'msg'=>'success', 'data'=>'退换入库成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'退换入库失败'];
        }
    }

    /**
     * [shopCreateOrder 加盟店生成订单]
     * @param  [type] $user_info [用户信息]
     * @param  [type] $request   [页面提交的数据]
     * @return [type]            [description]
     */
    public function shopCreateOrder($user_info, $request)
    {
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 添加订单数据
        // 1. 添加订单表数据
        $ord_order_number = Common::orderRule($user_info);
        $ord_data['ord_cid'] = $user_info->adm_cid;
        $ord_data['ord_shop_id'] = $user_info->adm_shop_id;
        $ord_data['ord_superior_shop_id'] = $shop_id;
        $ord_data['ord_create_id'] = $user_info->adm_id;
        // 加盟店生成订单，没有工单
        // ord_wor_state 订单的工单状态1未派工单2服务中3售后中4已完成5无工单
        $ord_wor_state = isset($request['assignment']) ? 2 : 5;
        $ord_data['ord_wor_state'] = $ord_wor_state;
        $ord_data['ord_client_id'] = $request['ord_client_id']; //选择客户id
        $ord_data['ord_order_number'] = $ord_order_number; //订单号
        //订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单 7救援单
        $ord_data['ord_service_type'] = $request['ord_service_type'];
        $ord_data['ord_payment_way'] = $request['ord_payment_way']; // 结算方式1.账期 2.现结 3微信 4支付宝
        $ord_data['ord_type'] = $request['ord_type']; // 买家类型：1门店零售2渠道单位
        $ord_data['ord_remark'] = isset($request['ord_remark']) ? $request['ord_remark'] : ''; //订单备注
        $ord_data['ord_service_sepr_id'] = $request['service_sepr_id'] ? $request['service_sepr_id'] : 0; //服务项目id
        $ord_data['ord_service_shop_id'] = $request['service_shop_id']; //服务门店id
        $ord_unique_string = md5(md5($user_info->adm_id . $user_info->adm_shop_id . date('Y-m-d H:i:s') . rand(10000, 99999)) . rand(10000, 99999));
        $ord_data['ord_unique_string'] = $ord_unique_string; //门店订单唯一标识
        $ord_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_id = DB::table('order')->insertGetId($ord_data);

        // 救援单的服务项目金额
        $orcl_rescue_service_price = isset($request['orcl_rescue_service_price']) ? $request['orcl_rescue_service_price'] : 0;
        // 救援单的代收金额
        $orcl_rescue_collection_price = isset($request['orcl_rescue_collection_price']) ? $request['orcl_rescue_collection_price'] : 0;
        if ($request['ord_type'] == '2') {
            $chun_adm_id = DB::table('channel_unit')
                ->where('chun_id', $request['ord_client_id'])
                ->value('chun_adm_id');
            if (empty($chun_adm_id)) {
                $chun_adm_id = 0;
            }
        } else {
            $chun_adm_id = 0;
        }
        // 添加订单客户表数据
        $orcl_data = [
            'orcl_ord_id' => $ord_id,
            'orcl_channel_unit' => isset($request['orcl_channel_unit']) ? $request['orcl_channel_unit'] : '',
            'orcl_adm_id' => $chun_adm_id, //业务员id
            'orcl_name' => $request['orcl_name'],
            'orcl_phone' => $request['orcl_phone'],
            'orcl_car_num' => isset($request['orcl_car_num']) ? $request['orcl_car_num'] : '',
            'orcl_province' => $request['orcl_province'],
            'orcl_city' => $request['orcl_city'],
            'orcl_county' => $request['orcl_county'],
            'orcl_address' => $request['orcl_address'],
            'orcl_chin_type' => isset($request['chin_type']) ? $request['chin_type'] : 2, //铺货类型：1是铺货 2不是铺货
            'orcl_collect_state' => isset($request['orcl_collect_state']) ? $request['orcl_collect_state'] : 0,
            //救援单的服务项目金额
            'orcl_rescue_service_price' => $orcl_rescue_service_price * 100,
            //救援单的代收金额
            'orcl_rescue_collection_price' => $orcl_rescue_collection_price * 100,
            'orcl_update_time' => date('Y-m-d H:i:s'),
            'orcl_order_type' => 2,
            'orcl_shipment_party' => $request['orcl_shipment_party'],
            'orcl_junk_type' => isset($request['orcl_junk_type']) ? $request['orcl_junk_type'] : 2, //是否为旧货1是2否
        ];
        $orcl_id = DB::table('order_client')->insertGetId($orcl_data);

        // 添加订单商品表数据
        $goo_all_quantity = 0; //商品总数量
        $goo_all_price = 0; //商品总金额
        $goo_collection_price = 0; //商品代收总金额
        $n = 0;
        $goo_state = 1; //商品状态
        // $sepr_order_money = 0;//服务项目的订单金额
        $recycle_all_price = 0; //订单回收金额
        $recycle_number = 0;
        $wor_recycle_price = 0;
        $wor_is_recycle = 2;
        $goo_all_assign_price = 0; //接单金额
        // 订单类型：7救援单，查询服务项目的订单金额
        if ($request['ord_service_type'] == 7) {
            // 没有添加商品数据
            if (empty($request['goo_id'])) {
                // 4. 更改订单表客户id、订单金额
                $ord_edit_data['ord_orcl_id'] = $orcl_id;
                $ord_edit_data['ord_plus_minus'] = 1; //金额正负：1正值2负值
                $ord_edit_data['ord_order_price'] = $orcl_rescue_service_price * 100; //订单金额（单位：分）
                $ord_edit_data['ord_actual_price'] = $orcl_rescue_service_price * 100; //结算金额（单位：分）
                $ord_edit_data['ord_goods_quantity'] = 0; //商品总数量
                $ord_edit_data['ord_collection_price'] = $orcl_rescue_collection_price * 100; //商品代收金额（单位：分）
                $ord_eidt_res = DB::table('order')
                    ->where('ord_id', $ord_id)
                    ->update($ord_edit_data);

                // 生成加盟店外派工单
                if (isset($request['assignment']) && $request['assignment'] == 1) {
                    $wor_number = Common::workRule($user_info);
                    $wor_data['wor_cid'] = $user_info->adm_cid;
                    $wor_data['wor_shop_id'] = $user_info->adm_shop_id;
                    $wor_data['wor_superior_shop_id'] = $shop_id;
                    $wor_data['wor_create_id'] = $user_info->adm_id;
                    $wor_data['wor_number'] = $wor_number; //工单
                    $wor_data['wor_order_id'] = $ord_id; //订单id
                    $wor_data['wor_order_number'] = $ord_order_number; //订单号
                    if ($request['service_shop_id']) {
                        // 选择服务门店
                        $wor_data['wor_service_shop_id'] = $request['service_shop_id']; //服务门店id
                    } else {
                        // 没有选择门店，就是当前门店
                        $wor_data['wor_service_shop_id'] = $user_info->adm_shop_id; //服务门店id
                    }
                    $wor_data['wor_service_sepr_id'] = $request['service_sepr_id']; //服务项目id
                    // 订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单
                    $wor_data['wor_service_type'] = $request['ord_service_type'];
                    $wor_data['wor_service_state'] = 1;
                    $wor_data['wor_state'] = 1;
                    $wor_data['wor_pass'] = 1;
                    $wor_data['wor_recycle_number'] = $recycle_number;
                    $wor_data['wor_is_recycle'] = $wor_is_recycle;
                    $wor_data['wor_type'] = $request['ord_type'];
                    $wor_data['wor_remark'] = isset($request['ord_remark']) ? $request['ord_remark'] : ''; //订单备注
                    $wor_data['wor_actual_price'] = abs($orcl_rescue_service_price) * 100; //工单结算金额（单位：分）
                    $wor_data['wor_goo_amount'] = $goo_all_quantity; //总的商品数量
                    $wor_data['wor_collection_price'] = $orcl_rescue_collection_price * 100; //商品代收金额（单位：分）
                    $wor_data['wor_recycle_price'] = $wor_recycle_price * 100; //工单总的回收金额
                    $wor_data['wor_update_time'] = date('Y-m-d H:i:s');
                    $wor_id = DB::table('work_order')->insertGetId($wor_data);

                    // 3. 添加工单客户表数据
                    $wocl_data = [
                        'wocl_wor_id' => $wor_id,
                        'wocl_client_id' => isset($request['wocl_client_id']) ? $request['wocl_client_id'] : 0,
                        'wocl_adm_id' => $chun_adm_id, //业务员id
                        'wocl_channel_unit' => isset($request['orcl_channel_unit']) ? $request['orcl_channel_unit'] : '',
                        'wocl_name' => $request['orcl_name'],
                        'wocl_phone' => $request['orcl_phone'],
                        'wocl_car_num' => isset($request['orcl_car_num']) ? $request['orcl_car_num'] : '',
                        'wocl_province' => $request['orcl_province'],
                        'wocl_city' => $request['orcl_city'],
                        'wocl_county' => $request['orcl_county'],
                        'wocl_address' => $request['orcl_address'],
                        'wocl_chin_type' => isset($request['chin_type']) ? $request['chin_type'] : 2, //铺货类型：1是铺货 2不是铺货,
                        'wocl_collect_state' => isset($request['orcl_collect_state']) ? $request['orcl_collect_state'] : 0,
                        'wocl_update_time' => date('Y-m-d H:i:s'),
                        'wocl_wor_type' => 2,
                        'wocl_junk_type' => isset($request['orcl_junk_type']) ? $request['orcl_junk_type'] : 2, //是否为旧货1是2否
                    ];

                    // 1. 添加订单表数据
                    $join_order_number = Common::orderRule($user_info);
                    $ord_data['ord_order_number'] = $join_order_number; //订单号
                    $ord_data['ord_superior_shop_id'] = $ord_data['ord_service_shop_id']; //总店id
                    $ord_data['ord_service_shop_id'] = $ord_data['ord_superior_shop_id']; //服务门店id
                    $ord_data['ord_order_price'] = abs($orcl_rescue_service_price) * 100; // 订单金额（单位：分）
                    $ord_data['ord_actual_price'] = abs($orcl_rescue_service_price) * 100; // 结算金额（单位：分）
                    $ord_data['ord_goods_quantity'] = $goo_all_quantity; // 商品总数量
                    $ord_data['ord_collection_price'] = $orcl_rescue_collection_price * 100; //商品代收金额（单位：分）
                    $ord_data['ord_wor_state'] = 7; //待接单状态
                    $join_order_id = DB::table('order')->insertGetId($ord_data);
                    //加盟店订单id
                    $wocl_data['wocl_join_ord_id'] = $join_order_id;
                    $wocl_id = DB::table('work_client')->insertGetId($wocl_data);
                    //订单客户表
                    $orcl_data['orcl_ord_id'] = $join_order_id;
                    $orcl_data['orcl_join_wor_id'] = $wor_id;

                    $join_orcl_id = DB::table('order_client')->insertGetId($orcl_data);
                    $join_orcl_res = DB::table('order')
                        ->where('ord_id', $join_order_id)
                        ->update(['ord_orcl_id' => $join_orcl_id]);
                } else {
                    $join_orcl_res = true;
                    $join_orcl_id = true;
                    $join_order_id = true;
                    $wocl_id = true;
                    $wor_id = true;
                }

                if ($ord_id && $orcl_id && $ord_eidt_res && $join_orcl_res && $join_orcl_id && $join_order_id && $wocl_id && $wor_id) {
                    $return_data['ord_id'] = $ord_id;
                    $return_data['ord_order_number'] = $ord_order_number;
                    $return_data['shop_id'] = $shop_id; //总店id
                    return ['code'=>200, 'msg'=>'success', 'data'=>$return_data];
                } else {
                    return ['code'=>500, 'msg'=>'success', 'data'=>'生成订单失败'];
                }
            }
        }

        // 有商品数据
        foreach ($request['goo_id'] as $key => $value) {
            if (!is_numeric($value) || !is_numeric($request['goo_price'][$key]) || !is_numeric($request['goo_quantity'][$key]) || !in_array($request['goo_recycle'][$key], [1, 2]) || !is_numeric($request['goo_recycle_quantity'][$key]) || !is_numeric($request['goo_recycle_price'][$key]) || !in_array($request['goo_state'][$key], [1, 3, 4, 5, 6, 7, 8]) || !is_numeric($request['goo_collection_price'][$key])) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'商品参数类型错误'];
            }

            if ($request['goo_recycle'][$key] == 1) {
                $recycle_all_price += $request['goo_recycle_quantity'][$key] * $request['goo_recycle_price'][$key]; //回收总金额
            }

            $orgo_data[$key]['orgo_ord_id'] = $ord_id;
            $orgo_data[$key]['orgo_order_number'] = $ord_order_number;
            $orgo_data[$key]['orgo_ware_id'] = 0;
            $orgo_data[$key]['orgo_waon_class'] = 0;
            $orgo_data[$key]['orgo_goo_id'] = $value;
            $orgo_data[$key]['orgo_goo_price'] = $request['goo_price'][$key] * 100;
            $orgo_data[$key]['orgo_goo_quantity'] = $request['goo_quantity'][$key];
            $orgo_data[$key]['orgo_recycle_quantity'] = $request['goo_recycle_quantity'][$key];
            $orgo_data[$key]['orgo_recycle_price'] = $request['goo_recycle_price'][$key] * 100;
            $orgo_data[$key]['orgo_can_assign_quantity'] = $request['goo_quantity'][$key];
            $orgo_data[$key]['orgo_collection_price'] = $request['goo_collection_price'][$key] * 100;
            $orgo_data[$key]['orgo_goo_inventory'] = 0; //库存扣除方式1.良品 2.优先，加盟店不选仓库默认一个值
            $orgo_data[$key]['orgo_update_time'] = date('Y-m-d H:i:s');
            $orgo_data[$key]['orgo_assign_price'] = $request['goo_assign_price'][$key] * 100; //派单金额(单位:分)

            // 搜索商品id对应的商品名称、商品编号
            $find_goods_data = DB::table('goods')
                ->where('goo_id', $value)
                ->first(['goo_name', 'goo_goods_encode', 'goo_type', 'goo_ampere_hour', 'goo_type', 'goo_assign_price', 'goo_class']);
            if ($find_goods_data->goo_class == 1) { //类型：1自营商品2系统商品
                // 查询商品附属表
                $goaf_another_name = DB::table('goods_affiliate')
                    ->where('goaf_goo_id', $value['goo_id'])
                    ->where('goaf_shop_id', $user_info->adm_shop_id)
                    ->value('goaf_another_name');
                if (!empty($goaf_another_name)) {
                    $find_goods_data->goo_name = $goaf_another_name;
                }
            } else {
                // 查询系统商品属性表
                $gosa_another_name = DB::table('goods_system_affiliate')
                    ->where('gosa_goo_id', $value['goo_id'])
                    ->where('gosa_shop_id', $user_info->adm_shop_id)
                    ->value('gosa_another_name');
                if (!empty($gosa_another_name)) {
                    $find_goods_data->goo_name = $gosa_another_name;
                }
            }
            if ($find_goods_data->goo_type == 1) {
                $waon_class = 1;
            } elseif ($find_goods_data->goo_type == 2) {
                $waon_class = 2;
            } elseif ($find_goods_data->goo_type == 4) {
                $waon_class = 4;
            } else {
                $waon_class = 0;
            }
            $orgo_data[$key]['orgo_waon_class'] = $waon_class;
            $orgo_data[$key]['orgo_goo_name'] = $find_goods_data->goo_name;
            $orgo_data[$key]['orgo_goo_goods_encode'] = $find_goods_data->goo_goods_encode;
            $orgo_data[$key]['orgo_goo_type'] = $find_goods_data->goo_type;
            $orgo_data[$key]['orgo_goo_ampere_hour'] = $find_goods_data->goo_ampere_hour;
            $orgo_data[$key]['orgo_state'] = $request['goo_state'][$key];

            //工单商品数据
            $wogo_data[$key]['wogo_goo_id'] = $value; //商品id
            $wogo_data[$key]['wogo_waon_class'] = $waon_class; //商品id
            $wogo_data[$key]['wogo_is_recycle'] = $request['goo_recycle'][$key]; //是否回收：1回收2不回收
            $wogo_data[$key]['wogo_goo_price'] = $request['goo_price'][$key] * 100; //工单商品销售金额
            $wogo_data[$key]['wogo_recycle_price'] = $request['goo_recycle_price'][$key] * 100; //回收金额
            $wogo_data[$key]['wogo_recycle_quantity'] = $request['goo_recycle_quantity'][$key]; //回收数量
            $wogo_data[$key]['wogo_goo_amount'] = $request['goo_quantity'][$key]; //工单商品数量
            $wogo_data[$key]['wogo_collection_price'] = $request['goo_collection_price'][$key] * 100; //代收金额
            $wogo_data[$key]['wogo_state'] = $request['goo_state'][$key]; //商品状态1.正常 2.删除3回收的商品4换货商品
            $wogo_data[$key]['wogo_update_time'] = date('Y-m-d H:i:s');
            $wogo_data[$key]['wogo_goo_name'] = $find_goods_data->goo_name;
            $wogo_data[$key]['wogo_goo_goods_encode'] = $find_goods_data->goo_goods_encode;
            $wogo_data[$key]['wogo_goo_type'] = $find_goods_data->goo_type;
            $wogo_data[$key]['wogo_state'] = $request['goo_state'][$key];
            $wogo_data[$key]['wogo_goo_inventory'] = 0;
            $wogo_data[$key]['wogo_assign_price'] = $request['goo_assign_price'][$key] * 100; //派单金额(单位:分)

            // 销售商品金额处理
            // orgo_state 商品状态1.正常 2.删除3回收的商品4换货商品5赠品商品
            if ($request['goo_state'][$key] == 1 || $request['goo_state'][$key] == 5) {
                $orgo_data[$key]['orgo_is_recycle'] = $request['goo_recycle'][$key];
                $wogo_data[$key]['wogo_is_recycle'] = $request['goo_recycle'][$key];
                // 订单商品金额
                $goo_all_price += $request['goo_price'][$key] * $request['goo_quantity'][$key];
                //接单金额
                // $goo_all_assign_price += $find_goods_data->goo_assign_price / 100 * $request['goo_quantity'][$key];
                $goo_all_assign_price += $request['goo_assign_price'][$key] * $request['goo_quantity'][$key]; //派单金额(单位:分)

                // goo_recycle 是否回收：1回收2不回收
                if ($request['goo_recycle'][$key] == 1) {
                    $wor_is_recycle = 1;
                    $recycle_number += $request['goo_recycle_quantity'][$key];
                    $wor_recycle_price += $request['goo_recycle_quantity'][$key] * $request['goo_recycle_price'][$key];
                }
                // 判断换货单的换货商品
                $goo_id[$n] = $value;
                $goo_quantity[$n] = $request['goo_quantity'][$key];
                $goo_price[$n] = $request['goo_price'][$key];
                $n++;

                $goo_all_quantity += $request['goo_quantity'][$key]; //商品总数量
                $goo_collection_price += $request['goo_collection_price'][$key]; //商品代收不乘以商品数量
            } elseif ($request['goo_state'][$key] == 4) {
                $orgo_data[$key]['orgo_is_recycle'] = 2;
                // 换货商品金额
                $goo_all_price -= $request['goo_price'][$key] * $request['goo_quantity'][$key];
                $goo_all_assign_price -= $request['goo_assign_price'][$key] * $request['goo_quantity'][$key]; //派单金额(单位:分)

                $goo_exchange[] = $value;
            }
        }

        // 判断换货单是否选择换货商品
        if ($request['ord_service_type'] == 3 && empty($goo_exchange)) {
            return ['code'=>500, 'msg'=>'success', 'data'=>'请点击“换货”添加退回的商品'];
        }
        if ($request['ord_service_type'] == 3 && empty($goo_id)) {
            return ['code'=>500, 'msg'=>'success', 'data'=>'请添加换新的商品'];
        }

        $goo_all_price = $goo_all_price + $orcl_rescue_service_price; //合计金额=商品总金额+服务项目的订单金额
        $goo_all_price = $goo_all_price - $recycle_all_price;
        if ($goo_all_price < 0 || $request['ord_service_type'] == 4) {
            // 金额小于0，或者退货单类型，金额为负
            $ord_edit_data['ord_plus_minus'] = 2; //金额正负：1正值2负值
        } else {
            $ord_edit_data['ord_plus_minus'] = 1; //金额正负：1正值2负值
        }
        //外派工单
        $goo_all_assign_price = $goo_all_assign_price + $orcl_rescue_service_price; //合计金额=商品总金额+服务项目的订单金额
        $goo_all_assign_price = $goo_all_assign_price - $recycle_all_price;
        if ($goo_all_assign_price < 0 || $request['ord_service_type'] == 4) {
            // 金额小于0，或者退货单类型，金额为负
            $wocl_data['wocl_plus_minus'] = 2; //金额正负：1正值2负值
            $ord_edit_data['orcl_plus_minus'] = 2; //金额正负：1正值2负值
        } else {
            $wocl_data['wocl_plus_minus'] = 1; //金额正负：1正值2负值
            $ord_edit_data['orcl_plus_minus'] = 1; //金额正负：1正值2负值
        }
        $orgo_res = DB::table('order_goods')->insert($orgo_data);

        // 4. 更改订单表客户id、订单金额
        $ord_edit_data['ord_orcl_id'] = $orcl_id;
        $ord_edit_data['ord_order_price'] = abs($goo_all_price) * 100; // 订单金额（单位：分）
        $ord_edit_data['ord_actual_price'] = abs($goo_all_price) * 100; // 结算金额（单位：分）
        $ord_edit_data['ord_goods_quantity'] = $goo_all_quantity; // 商品总数量
        $ord_edit_data['ord_collection_price'] = ($goo_collection_price + $orcl_rescue_collection_price) * 100; //商品代收金额（单位：分）
        $ord_edit_data['orcl_assign_price'] = abs($goo_all_assign_price) * 100; //派单金额（单位：分）

        if (isset($request['assignment']) && $request['assignment'] == 1) {
            $ord_edit_data['ord_wor_quantity'] = 1;
        }
        $ord_eidt_res = DB::table('order as ord')
            ->leftjoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
            ->where('ord_id', $ord_id)
            ->update($ord_edit_data);
        //生成加盟店外派工单
        if (isset($request['assignment']) && $request['assignment'] == 1) {
            orderLog($user_info, $ord_id, 0, '生成外派工单');
            //加盟店订单数据
            $wor_number = Common::workRule($user_info);
            $wor_data['wor_cid'] = $user_info->adm_cid;
            $wor_data['wor_shop_id'] = $user_info->adm_shop_id;
            $wor_data['wor_superior_shop_id'] = $shop_id;
            $wor_data['wor_create_id'] = $user_info->adm_id;
            $wor_data['wor_number'] = $wor_number; //工单
            $wor_data['wor_order_id'] = $ord_id; //订单id
            $wor_data['wor_order_number'] = $ord_order_number; //订单号
            if ($request['service_shop_id']) {
                // 选择服务门店
                $wor_data['wor_service_shop_id'] = $request['service_shop_id']; //服务门店id
            } else {
                // 没有选择门店，就是当前门店
                $wor_data['wor_service_shop_id'] = $user_info->adm_shop_id; //服务门店id
            }
            $wor_data['wor_service_sepr_id'] = $request['service_sepr_id']; //服务项目id
            // 订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单
            $wor_data['wor_service_type'] = $request['ord_service_type'];
            $wor_data['wor_service_state'] = 1;
            $wor_data['wor_state'] = 1;
            $wor_data['wor_pass'] = 1;
            $wor_data['wor_recycle_number'] = $recycle_number;
            $wor_data['wor_is_recycle'] = $wor_is_recycle;
            $wor_data['wor_type'] = $request['ord_type'];
            $wor_data['wor_remark'] = isset($request['ord_remark']) ? $request['ord_remark'] : ''; //订单备注
            $wor_data['wor_actual_price'] = abs($goo_all_price) * 100; //工单结算金额（单位：分）
            $wor_data['wor_goo_amount'] = $goo_all_quantity; //总的商品数量
            $wor_data['wor_collection_price'] = $goo_collection_price * 100; //商品代收金额（单位：分）
            $wor_data['wor_recycle_price'] = $wor_recycle_price * 100; //工单总的回收金额
            $wor_data['wor_update_time'] = date('Y-m-d H:i:s');
            $wor_id = DB::table('work_order')->insertGetId($wor_data);
            // 2. 添加工单商品表数据
            foreach ($wogo_data as $key => $value) {
                $wogo_data[$key]['wogo_wor_id'] = $wor_id;
            }
            $wogo_res = DB::table('work_good')->insert($wogo_data);

            // 3. 添加工单客户表数据
            $wocl_data = [
                'wocl_wor_id' => $wor_id,
                'wocl_client_id' => isset($request['wocl_client_id']) ? $request['wocl_client_id'] : 0,
                'wocl_adm_id' => $chun_adm_id,
                'wocl_channel_unit' => isset($request['orcl_channel_unit']) ? $request['orcl_channel_unit'] : '',
                'wocl_name' => $request['orcl_name'],
                'wocl_phone' => $request['orcl_phone'],
                'wocl_car_num' => isset($request['orcl_car_num']) ? $request['orcl_car_num'] : '',
                'wocl_province' => $request['orcl_province'],
                'wocl_city' => $request['orcl_city'],
                'wocl_county' => $request['orcl_county'],
                'wocl_address' => $request['orcl_address'],
                'wocl_chin_type' => isset($request['chin_type']) ? $request['chin_type'] : 2, //铺货类型：1是铺货 2不是铺货,
                'wocl_collect_state' => isset($request['orcl_collect_state']) ? $request['orcl_collect_state'] : 0,
                'wocl_update_time' => date('Y-m-d H:i:s'),
                'wocl_wor_type' => 2,
                'wocl_assign_price' => abs($goo_all_assign_price) * 100, //派单金额（单位：分）
                'wocl_junk_type' => isset($request['orcl_junk_type']) ? $request['orcl_junk_type'] : 2, //是否为旧货1是2否
            ];

            // 1. 添加订单表数据
            $join_order_number = Common::orderRule($user_info);
            $ord_data['ord_order_number'] = $join_order_number; //订单号
            $ord_data['ord_superior_shop_id'] = $ord_data['ord_service_shop_id']; //总店id
            $ord_data['ord_service_shop_id'] = $ord_data['ord_superior_shop_id']; //服务门店id
            $ord_data['ord_order_price'] = abs($goo_all_assign_price) * 100; // 订单金额（单位：分）
            $ord_data['ord_actual_price'] = abs($goo_all_assign_price) * 100; // 结算金额（单位：分）
            $ord_data['ord_goods_quantity'] = $goo_all_quantity; // 商品总数量
            $ord_data['ord_collection_price'] = ($goo_collection_price + $orcl_rescue_collection_price) * 100; //商品代收金额（单位：分）
            $ord_data['ord_wor_state'] = 7; //待接单状态
            $join_order_id = DB::table('order')->insertGetId($ord_data);
            //加盟店订单id
            $wocl_data['wocl_join_ord_id'] = $join_order_id;
            $wocl_id = DB::table('work_client')->insertGetId($wocl_data);
            //订单客户表
            $orcl_data['orcl_ord_id'] = $join_order_id;
            $orcl_data['orcl_join_wor_id'] = $wor_id;

            $join_orcl_id = DB::table('order_client')->insertGetId($orcl_data);
            foreach ($wogo_data as $key => $value) {
                $orgo_data[$key]['orgo_ord_id'] = $join_order_id;
                $orgo_data[$key]['orgo_goo_price'] = $value['wogo_assign_price'];
            }
            $join_orgo_res = DB::table('order_goods')->insert($orgo_data);

            $join_orcl_res = DB::table('order')
                ->where('ord_id', $join_order_id)
                ->update(['ord_orcl_id' => $join_orcl_id]);
        } else {
            $join_orcl_res = true;
            $join_orgo_res = true;
            $join_orcl_id = true;
            $join_order_id = true;
            $wocl_id = true;
            $wogo_res = true;
            $wor_id = true;
        }
        //计算会员消费总金额
        if( $ord_data['ord_type'] == 1 && $ord_data['ord_client_id'] > 0){
            WashOrderService::consume_money($ord_data['ord_client_id']);
        }
        if ($ord_id && $orgo_res  && $orcl_id && $ord_eidt_res && $join_orcl_res && $join_orgo_res && $join_orcl_id && $join_order_id && $wocl_id && $wogo_res && $wor_id) {
            $return_data['ord_id'] = $ord_id;
            $return_data['ord_order_number'] = $ord_order_number;
            $return_data['shop_id'] = $shop_id; //总店id
            return ['code'=>200, 'msg'=>'success', 'data'=>$return_data];
        } else {
            return ['code'=>500, 'msg'=>'success', 'data'=>'生成订单失败'];
        }
    }

    // 派单
    public function assign(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyCashierDeskController;
        $error_message = $verify_data->assignShowValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

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

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

        if ($request['type'] == 1) { //获取页面数据
            // 查询派单信息
            $find_order = DB::table('order as o')
                ->leftJoin('service_project as sp', 'sp.sepr_id', '=', 'o.ord_service_sepr_id')
                ->where('ord_id', $request['ord_id'])
                ->select('ord_order_number', 'ord_state', 'ord_type', 'ord_create_id', 'ord_order_price', 'ord_actual_price', 'ord_payment_way', 'ord_remark', 'ord_service_shop_id', 'ord_client_id', 'ord_service_sepr_id', 'ord_service_adm_id', 'ord_ware_id', 'sepr_name', 'ord_service_type', 'ord_collection_price', 'ord_client_id', 'ord_wor_state')
                ->first();
            if ($find_order->ord_wor_state == 2) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'已派工单，无法派单']);
            }
            // 获取账号id对应的姓名
            $adm_id[] = $find_order->ord_create_id;
            $adm_id[] = $find_order->ord_service_adm_id;
            $adm_id = array_filter($adm_id); //如果没有回调函数，默认就是删除数组中值为false的元素
            $find_admin = DB::table('admin')
                ->whereIn('adm_id', $adm_id)
                ->pluck('adm_name', 'adm_id')->toArray();
            $find_order->ord_create_name = isset($find_admin[$find_order->ord_create_id]) ? $find_admin[$find_order->ord_create_id] : '';
            $find_order->ord_service_adm_name = isset($find_admin[$find_order->ord_service_adm_id]) ? $find_admin[$find_order->ord_service_adm_id] : '';

            $order_client = DB::table('order_client')
                ->where('orcl_ord_id', $request['ord_id'])
                ->select('orcl_channel_unit', 'orcl_name', 'orcl_phone', 'orcl_car_num', 'orcl_province', 'orcl_city', 'orcl_county', 'orcl_address', 'orcl_collect_state', 'orcl_standby_battery_type', 'orcl_order_type', 'orcl_car_vehicle_type', 'orcl_shipment_party', 'orcl_rescue_assign_price', 'orcl_assign_price', 'orcl_rescue_service_price', 'orcl_rescue_collection_price', 'orcl_client_id', 'orcl_whether_app', 'orcl_precise_lock', 'orcl_appoint_time')
                ->first();
            // 客户单位名称
            $order_client->orcl_channel_unit = DB::table('channel_unit')
                ->where('chun_id', $find_order->ord_client_id)
                ->value('chun_unit_name');

            $warehouse = DB::table('warehouse')
                ->where('ware_id', $find_order->ord_ware_id)
                ->select('ware_id', 'ware_name', 'ware_type')
                ->first();

            $order_goods = DB::table('order_goods as orgo')
                ->leftjoin('goods as goo', 'goo.goo_id', '=', 'orgo.orgo_goo_id')
                ->where('orgo_ord_id', $request['ord_id'])
                ->whereIn('orgo_state', [1, 4, 5, 6, 7, 8]) //商品状态1.正常 2.删除3回收的商品4换货商品5赠品
                ->select('orgo_id', 'orgo_goo_id', 'orgo_actual_goo_id', 'orgo_wago_id', 'orgo_goo_name', 'orgo_goo_goods_encode', 'orgo_goo_price', 'orgo_goo_quantity', 'orgo_is_recycle', 'orgo_can_assign_quantity', 'orgo_collection_price', 'orgo_goo_inventory', 'orgo_state', 'orgo_recycle_price', 'orgo_recycle_quantity', 'orgo_waon_class', 'orgo_goo_type', 'orgo_goo_ampere_hour', 'orgo_tem_goo_name', 'orgo_assign_price as goo_assign_price', 'goo_brse_id', 'goo_bra_name', 'goo_class')
                ->get()->toArray();
            // 查询系列数据
            $goo_brse_id = array_column($order_goods, 'goo_brse_id');
            $brse_data = DB::table('brand_serie')
                ->whereIn('brse_id', $goo_brse_id)
                ->pluck('brse_name', 'brse_id')
                ->toArray();
            foreach ($order_goods as $key => $value) {
                // 判断系列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) {
                            $order_goods[$key]->orgo_goo_name = $brse_data[$value->goo_brse_id] . ' ' . $value->orgo_goo_name;
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $order_goods[$key]->orgo_goo_name = $brse_data[$value->goo_brse_id] . ' ' . $value->orgo_goo_name;
                            }
                        }
                    }
                }
                // 显示品牌名称
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                    if ($value->goo_class == 2) {
                        $order_goods[$key]->orgo_goo_name = $value->goo_bra_name . ' ' . $value->orgo_goo_name;
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $order_goods[$key]->orgo_goo_name = $value->goo_bra_name . ' ' . $value->orgo_goo_name;
                        }
                    }
                }
                unset($order_goods[$key]->goo_class);
                unset($order_goods[$key]->goo_brse_id);
            }
            // 查询服务门店名称
            if ($order_client->orcl_shipment_party == 4) {
                $find_order->ord_service_shop_name = DB::table('virtual_shop')
                    ->where('vish_id', $find_order->ord_service_shop_id)
                    ->value('vish_store_name as shop_store_name');

                $price = $order_client->orcl_rescue_assign_price + $order_client->orcl_assign_price;
                $find_order->ord_actual_price = $price;
                $find_order->ord_order_price = $price;

                $find_order->ord_service_adm_name = DB::table('admin')->where('adm_id', $find_order->ord_service_adm_id)->value('adm_name');

                if (!empty($order_goods)) {
                    foreach ($order_goods as $key => $value) {
                        $order_goods[$key]->orgo_goo_price = $value->goo_assign_price;
                    }
                }
            } else {
                $find_order->ord_service_shop_name = DB::table('shop')
                    ->where('shop_id', $find_order->ord_service_shop_id)
                    ->value('shop_store_name');
            }

            // 查询仓库锁定表是否有该数据
            $find_wagl_data = DB::table('warehouse_goods_lock')
                ->where('wagl_shop_id', $user_info->adm_shop_id)
                ->where('wagl_original_id', $request['ord_id'])
                ->where('wagl_original_number', $find_order->ord_order_number)
                ->select('wagl_id')
                ->get()->toArray();
            $find_order->wagl_states = 1;
            if (empty($find_wagl_data)) {
                $find_order->wagl_states = 2;
            }

            $data['find_order'] = $find_order;
            $data['order_client'] = $order_client;
            $data['order_goods'] = $order_goods;
            $data['warehouse'] = $warehouse;
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }

        // 查询订单数据
        $find_order = DB::table('order')
            ->leftjoin('order_client as oc', 'oc.orcl_ord_id', '=', 'order.ord_id')
            ->where('ord_id', $request['ord_id'])
            ->select('ord_order_number', 'ord_service_type', 'ord_payment_way', 'ord_wor_state', 'ord_wor_quantity', 'ord_type', 'ord_other_system_number', 'ord_actual_price', 'ord_ware_id', 'ord_collection_price', 'ord_remark', 'orcl_shipment_party', 'orcl_assign_price', 'orcl_rescue_assign_price', 'orcl_rescue_service_price', 'orcl_rescue_collection_price', 'orcl_adm_id', 'orcl_whether_app', 'orcl_order_type', 'orcl_shit_id')
            ->first();
        if (!empty($request['goo_id']) && $find_order->ord_service_type != 7) {
            // 验证数据，提交数据
            $error_message = $verify_data->goodsAssignValidator($request->all());
            if ($error_message) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
            }
        } else {
            // 验证数据，提交数据
            $error_message = $verify_data->assignValidator($request->all());
            if ($error_message) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
            }
        }
        if ($find_order->ord_wor_state == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'已派工单，无法派单']);
        }
        if ($find_order->ord_wor_state == 3) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单存在售后单，无法派单']);
        }
        if ($find_order->ord_wor_state == 4) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已完成，无法派单']);
        }
        if ($find_order->ord_wor_state == 5) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单是无工单状态，无法派单']);
        }
        if ($find_order->ord_wor_state == 6) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单是活动审核状态，无法派单']);
        }
        if ($find_order->ord_wor_state == 12) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单是待审核状态，无法派单']);
        }
        if ($find_order->ord_wor_state == 11) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已取消，无法派单']);
        }
        // 是否为速电派到加盟店的工单1是 2否
        if (empty($request['sd_virtual_type'])) {
            $request->offsetSet('sd_virtual_type', 2);
        }

        // 救援单的服务项目金额
        $orcl_rescue_service_price = $request->filled('orcl_rescue_service_price') ? $request['orcl_rescue_service_price'] : 0;
        // 救援单的代收金额
        $orcl_rescue_collection_price = $request->filled('orcl_rescue_collection_price') ? $request['orcl_rescue_collection_price'] : 0;
        // 救援单派单金额
        $orcl_rescue_assign_price = $request->filled('orcl_rescue_assign_price') ? $request['orcl_rescue_assign_price'] : 0;

        // 出库方1仓库2直营店3加盟店4虚拟加盟店5门店，如果不是虚拟加盟店
        if (($find_order->orcl_shipment_party != 4 && $find_order->orcl_shipment_party != 5) && $request['sd_virtual_type'] != 1) {
            if (empty($request['wor_ware_id'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
            }
            $ware_return = Warehouse::existMoveWarehouse($request['wor_service_adm_id']);
            if (empty($ware_return)) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前技师暂未绑定技师库，无法派单']);
            }
        } else {
            $request->offsetSet('wor_ware_id', 0);
            $orcl_rescue_assign_price = $find_order->orcl_rescue_assign_price / 100;
        }

        $neaten_goods_data = []; //整理后的仓库商品库存数据
        $goods_data = []; //提交的商品数据
        $goo_all_quantity = 0; //商品总数量
        $goo_all_price = 0; //商品总金额
        $goods_data = json_decode($request['goods_data'], true);

        // 判断提交的商品参数
        if (empty($goods_data)) {
            // 救援单的可以不选商品
            if ($find_order->ord_service_type != 7) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'请选择商品']);
            }
        } else {
            foreach ($goods_data as $key => $value) {
                if ($find_order->ord_type == 3) {
                    $wago_id = DB::table('warehouse_goods')
                        ->where('wago_class', $value['goo_waon_class'])
                        ->where('wago_goo_id', $value['goo_id'])
                        ->where('wago_ware_id', $request['wor_ware_id'])
                        ->value('wago_id');
                    $goods_data[$key]['wago_id'] = $wago_id;
                    $value['wago_id'] = $wago_id;
                } elseif ($find_order->ord_type == 4) {
                    $wago_id = DB::table('warehouse_goods')
                        ->where('wago_class', $value['goo_waon_class'])
                        ->where('wago_goo_id', $value['goo_id'])
                        ->where('wago_ware_id', $request['wor_ware_id'])
                        ->value('wago_id');
                    $goods_data[$key]['wago_id'] = $wago_id;
                    $value['wago_id'] = $wago_id;
                } elseif ($find_order->ord_type == 5) {
                    $wago_id = DB::table('warehouse_goods')
                        ->where('wago_class', $value['goo_waon_class'])
                        ->where('wago_goo_id', $value['goo_id'])
                        ->where('wago_ware_id', $request['wor_ware_id'])
                        ->value('wago_id');
                    $goods_data[$key]['wago_id'] = $wago_id;
                    $value['wago_id'] = $wago_id;
                }
                if (!$value['wago_id']) {
                    $value['wago_id'] = 0;
                }
                if (!is_numeric($value['wago_id']) || !is_numeric($value['goo_id']) || !in_array($value['goo_state'], [1, 3, 4, 5, 6, 7, 8]) || !is_numeric($value['goo_waon_class']) || !in_array($value['goo_inventory'], [1, 2])  || !is_numeric($value['goo_price']) || !is_numeric($value['goo_collection_price']) || !is_numeric($value['goo_quantity'])) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品参数类型错误']);
                }
                // goo_state 商品状态1正常3回收的商品4换货商品5赠品商品6备用电池7临时商品8旧货商品
                if ($value['goo_state'] != 4) {
                    // [仓库商品id][出库类型：良品/优先]，用于判断仓库是否有库存
                    if (isset($neaten_goods_data[$value['wago_id']][$value['goo_inventory']])) {
                        $neaten_goods_data[$value['wago_id']][$value['goo_inventory']]['goo_quantity'] += $value['goo_quantity'];
                    } else {
                        $neaten_goods_data[$value['wago_id']][$value['goo_inventory']] = $value;
                    }
                    $goo_all_quantity += $value['goo_quantity'];
                    $goo_all_price += $value['goo_quantity'] * $value['goo_price'];
                }
                // 仓库类别对应的商品，库存-出入库记录
                if (isset($wago_class_goods[$value['goo_inventory']][$value['goo_waon_class']][$value['goo_id']])) {
                    $wago_class_goods[$value['goo_inventory']][$value['goo_waon_class']][$value['goo_id']]['goo_quantity'] = $wago_class_goods[$value['goo_inventory']][$value['goo_waon_class']][$value['goo_id']]['goo_quantity'] + $value['goo_quantity'];
                } else {
                    $wago_class_goods[$value['goo_inventory']][$value['goo_waon_class']][$value['goo_id']] = $value;
                }
            }
        }
        $goo_all_quantity = 0; //商品总数量
        $goo_all_price = 0; //商品总金额
        $goo_assign_all_price = 0; //商品总派单金额
        $goo_collection_price = 0; //商品代收总金额

        // 救援单可能没有商品数据
        if (!empty($goods_data)) {
            $find_order_goods = DB::table('order_goods')
                ->where('orgo_ord_id', $request['ord_id'])
                ->select('orgo_id', 'orgo_ware_id', 'orgo_waon_class', 'orgo_wago_id', 'orgo_goo_id', 'orgo_goo_name', 'orgo_tem_goo_name', 'orgo_goo_goods_encode', 'orgo_goo_ampere_hour', 'orgo_goo_type', 'orgo_goo_price', 'orgo_state', 'orgo_collection_price', 'orgo_goo_quantity', 'orgo_goo_inventory', 'orgo_assign_price', 'orgo_can_assign_quantity')
                ->get();
            $find_order_goods = json_decode(json_encode($find_order_goods, true), true);
            foreach ($find_order_goods as $key => $value) {
                // goo_state 商品状态1.正常 2.删除3.回收的商品4.换货商品5.赠品商品6.备用电池7.临时商品8.旧货商品
                // 换货商品金额处理
                if ($value['orgo_state'] == 1 || $value['orgo_state'] == 5) {
                    // 订单商品
                    $goo_all_price += $value['orgo_goo_price'] * $value['orgo_goo_quantity'];
                    $goo_assign_all_price += $value['orgo_assign_price'] * $value['orgo_goo_quantity'];

                    $goo_all_quantity += $value['orgo_goo_quantity']; //商品总数量
                    $goo_collection_price += $value['orgo_collection_price'];
                } elseif ($value['orgo_state'] == 4) { //换货商品
                } elseif ($value['orgo_state'] == 6) { //备用电池
                    $goo_all_quantity += $value['orgo_goo_quantity']; //商品总数量
                    $goo_all_price += $value['orgo_goo_price'] * $value['orgo_goo_quantity'];
                    $goo_collection_price += $value['orgo_collection_price'];
                } elseif ($value['orgo_state'] == 7) { //临时商品
                    $goo_all_price += $value['orgo_goo_price'] * $value['orgo_goo_quantity'];
                    $goo_all_quantity += $value['orgo_goo_quantity']; //商品总数量
                } elseif ($value['orgo_state'] == 8) { //旧货商品
                    $goo_all_price += $value['orgo_goo_price'] * $value['orgo_goo_quantity'];
                    $goo_assign_all_price += $value['orgo_assign_price'] * $value['orgo_goo_quantity'];
                    $goo_all_quantity += $value['orgo_goo_quantity']; //商品总数量
                    $goo_collection_price += $value['orgo_collection_price']; //商品代收总金额
                }
                // 是否为速电派到加盟店的工单1是 2否
                // 速电
                if ($find_order->ord_type == 3 && $request['sd_virtual_type'] == 2) {
                    $value['orgo_wago_id'] = DB::table('warehouse_goods')
                        ->where('wago_class', $value['orgo_waon_class'])
                        ->where('wago_goo_id', $value['orgo_goo_id'])
                        ->where('wago_ware_id', $request['wor_ware_id'])
                        ->value('wago_id');
                    $orgo_edit_data['orgo_wago_id'] = $value['orgo_wago_id']; //订单商品主键id
                }

                // 工单商品表数据
                // sd_virtual_type派单类型1外派工单2系统派单
                if ($find_order->ord_type == 3 && $request['sd_virtual_type'] == 2) {
                    $wogo_data[$key]['wogo_ware_id'] = $request['wor_ware_id'];
                } else {
                    $wogo_data[$key]['wogo_ware_id'] = $value['orgo_ware_id'];
                }
                if ($find_order->ord_type == 5) { //门店
                    $wago_id = DB::table('warehouse_goods')
                        ->where('wago_class', $value['orgo_waon_class'])
                        ->where('wago_goo_id', $value['orgo_goo_id'])
                        ->where('wago_ware_id', $request['wor_ware_id'])
                        ->value('wago_id');
                    $value['orgo_wago_id'] = $wago_id;
                    $wogo_data[$key]['wogo_ware_id'] = $request['wor_ware_id'];
                    $orgo_edit_data['orgo_wago_id'] = $wago_id; //仓库商品主键id
                }
                $wogo_data[$key]['wogo_waon_class'] = $value['orgo_waon_class'];
                $wogo_data[$key]['wogo_goo_id'] = $value['orgo_goo_id'];
                $wogo_data[$key]['wogo_actual_goo_id'] = $value['orgo_goo_id']; //实际出库商品id
                $wogo_data[$key]['wogo_wago_id'] = $value['orgo_wago_id']; //仓库商品id
                $wogo_data[$key]['wogo_orgo_id'] = $value['orgo_id']; //订单商品表主键id
                $wogo_data[$key]['wogo_tem_goo_name'] = $value['orgo_tem_goo_name'];
                $wogo_data[$key]['wogo_goo_name'] = $value['orgo_goo_name'];
                $wogo_data[$key]['wogo_goo_goods_encode'] = $value['orgo_goo_goods_encode'];
                $wogo_data[$key]['wogo_goo_type'] = $value['orgo_goo_type'];
                $wogo_data[$key]['wogo_state'] = $value['orgo_state'];
                if ($find_order->orcl_shipment_party == 4 || $find_order->orcl_shipment_party == 3 || $find_order->orcl_shipment_party == 5) {
                    $wogo_data[$key]['wogo_assign_price'] = $value['orgo_assign_price'];
                    $wogo_data[$key]['wogo_goo_price'] = $value['orgo_assign_price'];
                } else {
                    $wogo_data[$key]['wogo_goo_price'] = $value['orgo_goo_price'];
                }
                $wogo_data[$key]['wogo_collection_price'] = $value['orgo_collection_price'];
                $wogo_data[$key]['wogo_goo_amount'] = $value['orgo_goo_quantity'];
                $wogo_data[$key]['wogo_goo_inventory'] = $value['orgo_goo_inventory'];
                $wogo_data[$key]['wogo_update_time'] = date('Y-m-d H:i:s');

                if ($find_order->orcl_order_type == '3') {
                    // 出库类型
                    foreach ($goods_data as $k => $v) {
                        if ($v['orgo_id'] == $value['orgo_id']) {
                            $orgo_edit_data['orgo_goo_inventory'] = $v['goo_inventory'];
                            $wogo_data[$key]['wogo_goo_inventory'] = $orgo_edit_data['orgo_goo_inventory'];
                        }
                    }
                    // 获取订单商品成本价
                    $orgo_goo_cost = DB::table('enters_sells_saves')
                        ->where('ense_goo_warehouse', $value['orgo_ware_id'])
                        ->where('ense_goo_waretype', $value['orgo_waon_class'])
                        ->where('ense_goo_id', $value['orgo_goo_id'])
                        ->orderBy('ense_id', 'desc')
                        ->value('ense_end_price');
                    $orgo_goo_cost = $orgo_goo_cost ?: 0;
                    $orgo_edit_data['orgo_goo_cost'] = $orgo_goo_cost * 100; //商品成本
                    $orgo_edit_data['orgo_ware_id'] = $request['wor_ware_id']; //仓库id
                    $orgo_edit_data['orgo_update_time'] = date('Y-m-d H:i:s'); //更新时间
                    // 工单商品表
                    $orgo_edit_res = DB::table('order_goods')
                        ->where('orgo_ord_id', $request['ord_id'])
                        ->where('orgo_order_number', $find_order->ord_order_number)
                        ->where('orgo_id', $value['orgo_id'])
                        ->where('orgo_state', $value['orgo_state'])
                        ->update($orgo_edit_data);
                } elseif ($find_order->orcl_order_type == 5) {
                    // 出库类型
                    foreach ($goods_data as $k => $v) {
                        if ($v['orgo_id'] == $value['orgo_id']) {
                            $orgo_edit_data['orgo_goo_inventory'] = $v['goo_inventory'];
                            $wogo_data[$key]['wogo_goo_inventory'] = $orgo_edit_data['orgo_goo_inventory'];
                        }
                    }
                    $orgo_edit_data['orgo_ware_id'] = $request['wor_ware_id']; //仓库id
                    $orgo_edit_data['orgo_update_time'] = date('Y-m-d H:i:s'); //更新时间
                    $orgo_edit_res = DB::table('order_goods')
                        ->where('orgo_ord_id', $request['ord_id'])
                        ->where('orgo_order_number', $find_order->ord_order_number)
                        ->where('orgo_id', $value['orgo_id'])
                        ->where('orgo_state', $value['orgo_state'])
                        ->update($orgo_edit_data);
                } else {
                    $orgo_edit_res = true;
                }
            }
            $goo_all_price = $goo_all_price + $orcl_rescue_service_price * 100;
            $goo_assign_all_price = $goo_assign_all_price + $orcl_rescue_assign_price * 100;
        } else {
            $goo_all_price = $find_order->ord_actual_price;
            $goo_assign_all_price = $find_order->orcl_assign_price + $goo_assign_all_price;
            // $goo_assign_all_price = $price;
        }
        DB::beginTransaction();
        // 添加工单数据
        // 1. 添加工单表数据
        $wor_order_number = Common::workRule($user_info);
        $wor_data['wor_cid'] = $user_info->adm_cid;
        $wor_data['wor_shop_id'] = $user_info->adm_shop_id;
        $wor_data['wor_superior_shop_id'] = $shop_id;
        $wor_data['wor_create_id'] = $user_info->adm_id;
        $wor_data['wor_number'] = $wor_order_number; //工单
        $wor_data['wor_order_id'] = $request['ord_id']; //订单id
        $wor_data['wor_order_number'] = $find_order->ord_order_number; //订单号
        if ($request['wor_service_shop_id']) {
            // 选择服务门店
            $wor_data['wor_service_shop_id'] = $request['wor_service_shop_id']; //服务门店id
        } else {
            // 没有选择门店，就是当前门店
            $wor_data['wor_service_shop_id'] = $user_info->adm_shop_id; //服务门店id
        }
        $wor_data['wor_service_sepr_id'] = $request['wor_service_sepr_id']; //服务项目id
        $request['service_adm_id'] = $request['wor_service_adm_id']; //服务技师id
        $wor_data['wor_service_adm_id'] = $request['service_adm_id']; //服务技师id

        // 订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单
        $wor_data['wor_service_type'] = $find_order->ord_service_type;
        // 是否走技师流程  1是  2否
        if (($find_order->orcl_whether_app == 2) && ($find_order->orcl_shipment_party == 4)) {
            $wor_data['wor_service_state'] = 6;
            $wor_data['wor_state'] = 8;
            $whether_app = 2;
        } else {
            $wor_data['wor_service_state'] = 1;
            $wor_data['wor_state'] = 3;
            $whether_app = 1;
        }

        $wor_data['wor_pass'] = 1;
        $wor_data['wor_type'] = $request['wor_type']; //工单类型:1.会员零售2.客户单位3.速电派单4.门店派单
        $wor_data['wor_remark'] = $request['wor_remark'] ? $request['wor_remark'] : ''; //订单备注
        $wor_data['wor_ware_id'] = $request['wor_ware_id']; //仓库id
        // 工单金额 = 总金额 - 回收金额
        if ($find_order->orcl_shipment_party == 4 || $find_order->orcl_shipment_party == 5 || $request['sd_virtual_type'] == 1) {
            // 虚拟加盟店工单金额与订单金额相反
            if ($goo_assign_all_price > 0) {
                $goo_all_price = '-' . $goo_assign_all_price;
            } else {
                $goo_all_price = abs($goo_assign_all_price);
            }
        } else {
            $goo_all_price = $goo_all_price;
        }
        $party = $find_order->orcl_shipment_party;

        if (isset($request['wor_appoint_time'])) {
            $wor_data['wor_appoint_time'] = $request['wor_appoint_time']; //预约时间
        }
        $wor_data['wor_actual_price'] = $goo_all_price; //工单结算金额（单位：分）
        $wor_data['wor_collection_price'] = $goo_collection_price + $orcl_rescue_collection_price * 100; //商品代收金额（单位：分）
        $wor_data['wor_goo_amount'] = $goo_all_quantity; //总的商品数量
        $wor_data['wor_update_time'] = date('Y-m-d H:i:s');
        $wor_id = DB::table('work_order')->insertGetId($wor_data);

        DB::table('order_remarks')
            ->where('orre_ord_id', $request['ord_id'])
            ->update(['orre_wor_id' => $wor_id]);

        // 添加订单备注
        if (!empty($wor_data['wor_remark']) && $wor_data['wor_remark'] != $find_order->ord_remark) {
            $wor_remark = orderRemark($user_info, $request['ord_id'], $wor_id, $wor_data['wor_remark'], '工作总台');
        } else {
            $wor_remark = true;
        }

        if (!empty($goods_data)) {
            // 2. 添加工单商品表数据
            foreach ($wogo_data as $key => $value) {
                $wogo_data[$key]['wogo_wor_id'] = $wor_id;
            }
            $wogo_res = DB::table('work_good')->insert($wogo_data);
        } else {
            $wogo_res = true;
        }

        // 查询出订单客户表是否铺货类型
        $orcl_chin = DB::table('order_client')
            ->where('orcl_ord_id', $request['ord_id'])
            ->first(['orcl_chin_type', 'orcl_order_type', 'orcl_join_wor_id', 'orcl_shit_id']);

        // 城市运营中心派给门店的单 图片模板id 为城市运营中心的
        if ($find_order->ord_type == 5) {
            $shit_id = $find_order->orcl_shit_id;
            if ($shit_id) {
                $orcl_chin->orcl_shit_id = $shit_id;
            } else {
                // 订单类型为服务单、救援单的有图片上传模板，根据订单类型，获取当前门店的图片上传模板
                $image_manager = new ImageUpload();
                $find_shit_id = $image_manager->getOrderTypeImageTemplate($user_info->adm_shop_id, $find_order->ord_service_type);
                $orcl_chin->orcl_shit_id = $find_shit_id; //图片模板id
            }
        }
        // 3. 添加工单客户表数据
        $wocl_data = [
            'wocl_wor_id' => $wor_id,
            'wocl_client_id' => $request['wocl_client_id'] ? $request['wocl_client_id'] : 0,
            'wocl_adm_id' => $find_order->orcl_adm_id,
            'wocl_channel_unit' => $request['wocl_channel_unit'] ? $request['wocl_channel_unit'] : '',
            'wocl_name' => $request['wocl_name'],
            'wocl_phone' => $request['wocl_phone'],
            'wocl_car_num' => $request['wocl_car_num'] ? $request['wocl_car_num'] : '', //车牌号
            'wocl_car_vehicle_type' => $request['wocl_car_vehicle_type'] ? $request['wocl_car_vehicle_type'] : '', //车型
            'wocl_province' => $request['wocl_province'],
            'wocl_city' => $request['wocl_city'],
            'wocl_county' => $request['wocl_county'],
            'wocl_address' => $request['wocl_address'],
            'wocl_longitude' => $request['wocl_longitude'], //经度
            'wocl_latitude' => $request['wocl_latitude'], //纬度
            'wocl_chin_type' => $orcl_chin->orcl_chin_type,
            'wocl_collect_state' => isset($request['wocl_collect_state']) ? $request['wocl_collect_state'] : 0,
            'wocl_update_time' => date('Y-m-d H:i:s'),
            'wocl_wor_type' => $orcl_chin->orcl_order_type,
            'wocl_join_wor_id' => $orcl_chin->orcl_join_wor_id,
            'wocl_join_audit' => $orcl_chin->orcl_order_type == 1 ? 1 : 2,
            'wocl_junk_type' => isset($request['wocl_junk_type']) ? $request['wocl_junk_type'] : 2,
            'wocl_rescue_collection_price' => $find_order->orcl_rescue_collection_price,
            'wocl_whether_app' => $whether_app,
            'wocl_precise_lock' => isset($request['precise_lock']) ? $request['precise_lock'] : 2, //精确打卡1是 2否
            'wocl_shit_id' => $orcl_chin->orcl_shit_id,
        ];
        if ($find_order->orcl_shipment_party == 4 || $request['sd_virtual_type'] == 1) {
            $wocl_data['wocl_wor_type'] = 4;
            $wocl_data['wocl_rescue_service_price'] = $orcl_rescue_assign_price * 100;
        } else {
            $wocl_data['wocl_rescue_service_price'] = $orcl_rescue_service_price * 100;
        }
        $wocl_data['wocl_sd_virtual_type'] = $request['sd_virtual_type'];
        $wocl_id = DB::table('work_client')->insertGetId($wocl_data);

        // 5. 更改订单的工单状态，工单数量
        // ord_wor_state 订单的工单状态1未派工单2服务中3售后中4已完成
        if ($find_order->ord_wor_state == 1) {
            $ord_data['ord_wor_state'] = 2;
        }
        $ord_data['ord_wor_quantity'] = $find_order->ord_wor_quantity + 1;
        $ord_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_data['ord_service_adm_id'] = $request['wor_service_adm_id'];
        $ord_data['ord_ware_id'] = $request['wor_ware_id']; //仓库id
        $ord_res =  DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->update($ord_data);

        // 救援单没有商品数据的状态
        if (empty($goods_data)) {
            // 9. 生成操作记录
            $work_record = orderLog($user_info, $request['ord_id'], $wor_id, '生成工单');
            $assign_record = orderLog($user_info, 0, $wor_id, '派单');
            if ($work_record && $assign_record && $ord_res && $wocl_id && $wogo_res && $wor_id) {
                DB::commit();
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'派单成功']);
            } else {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'派单失败']);
            }
        }

        $find_order_goods = DB::table('order_goods')
            ->where('orgo_ord_id', $request['ord_id'])
            ->select('orgo_id', 'orgo_goo_quantity', 'orgo_can_assign_quantity')
            ->get();
        $find_order_goods = json_decode(json_encode($find_order_goods, true), true);
        foreach ($find_order_goods as $key => $value) {
            $assign_quantity = $value['orgo_can_assign_quantity'] - $value['orgo_goo_quantity'];
            if ($assign_quantity < 0) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'可派单商品数量不足，无法派单']);
            }
            $orgo_res = DB::table('order_goods')
                ->where('orgo_ord_id', $request['ord_id'])
                ->update(['orgo_can_assign_quantity' => $assign_quantity]);
        }

        // 当前仓库不是技师的技师库 生成发货单 并且订单类型不为退货单
        if ($find_order->ord_service_type != 4 && $find_order->orcl_shipment_party != 4 && $find_order->orcl_shipment_party != 5 && $request['sd_virtual_type'] != 1) {
            // 服务门店为0的话 是当前门店id
            if ($request['wor_service_shop_id'] == 0) {
                $request['service_shop_id'] = $user_info->adm_shop_id; //服务门店id
            } else {
                $request['service_shop_id'] = $request['wor_service_shop_id']; //服务门店id
            }
            $dibi_data = DispatchBill::create(
                $user_info,   //用户信息
                $request->all(),  //订单提交数据
                $goods_data,  //提交的商品数据
                2,  //类型：1.订单发货 2.工单发货
                $request['wor_ware_id'],  //出库仓库id
                $wor_order_number,  //原始单号，订单号/工单号
                $wor_id,  //发货单关联的工单/订单id
                $request['service_shop_id'],  //所属总店id
                $request['wor_type'],  //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
                $request['wocl_client_id'],  //选择的客户id,会员id/单位id
                $goo_all_quantity  //发货总数量
            );
            if ($dibi_data['code'] == 500) {
                DB::rollBack();
                return response()->json($dibi_data);
            }
            // 仓库
            $neaten_wago_id = [];
            $wagl_key = 0;
            foreach ($neaten_goods_data as $wago_id => $wago_id_value) {
                foreach ($wago_id_value as $goo_inventory => $goo_value) {
                    $ware_id[$wago_id] = $request['wor_ware_id'];
                    $wago_goo_id[$wago_id] = $goo_value['goo_id'];
                    $wago_goo_quantity[$wago_id] = $goo_value['goo_quantity'];
                    $wago_goo_inventory[$wago_id] = $goo_inventory;
                    $wago_goo_class[$wago_id] = $goo_value['goo_waon_class'];
                    $neaten_wago_id[] = $wago_id;
                    $goo_goods_encode = DB::table('goods')
                        ->where('goo_id', $goo_value['goo_id'])
                        ->where('goo_delete', 1)
                        ->value('goo_goods_encode');
                    if (empty($goo_value['wago_id'])) {
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前仓库没有该' . $goo_goods_encode . '！']);
                    }
                }

                // 仓库商品锁定表
                $wagl_data[$wagl_key]['wagl_shop_id'] = $user_info->adm_shop_id;
                $wagl_data[$wagl_key]['wagl_ware_id'] = $request['wor_ware_id'];
                $wagl_data[$wagl_key]['wagl_wago_id'] = $wago_id;
                $wagl_data[$wagl_key]['wagl_original_id'] = $request['ord_id'];
                $wagl_data[$wagl_key]['wagl_original_number'] = $find_order->ord_order_number;
                $wagl_data[$wagl_key]['wagl_original_correlation_id'] = $dibi_data['dego_id']; //关联id：订单id/发货单id/调拨单id
                $wagl_data[$wagl_key]['wagl_correlation_type'] = 2; //关联类型：1订单2发货单3调拨单
                $wagl_data[$wagl_key]['wagl_type'] = 1; //  原始单类型：1订单2调拨单
                $wagl_data[$wagl_key]['wagl_state'] = 1; //锁定状态：1下单锁定2出库解锁
                $wagl_data[$wagl_key]['wagl_lock_quantity'] = $goo_value['goo_quantity'];
                $wagl_key++;
            }
            // 如果是速电派单
            if ($find_order->ord_type == 3) {
                $wago_id = array_unique($neaten_wago_id);
                // 生成订单时锁定库存
                $order_data['data']['ord_id'] = $request['ord_id'];
                $order_data['data']['ord_order_number'] = $find_order->ord_order_number;
                $order_data['data']['shop_id'] = $user_info->adm_shop_id;
                $order_data['data']['ord_type'] = $find_order->ord_type;
                $order_data['data']['ord_client_id'] = $request['wocl_client_id'];
                $request['ware_id'] = $request['wor_ware_id'];
                $ware_lock_return = WarehouseLock::warehouseLockInventory(
                    $user_info,
                    $request->all(),
                    $order_data,
                    $neaten_goods_data
                );
                if ($ware_lock_return['code'] == 500) {
                    DB::rollBack();
                    return response()->json($ware_lock_return);
                }
                // 查询仓位商品锁定表
                $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_ware_id', $request['wor_ware_id'])
                    ->where('wfgl_correlation_type', 1)
                    ->where('wfgl_original_id', $order_data['data']['ord_id'])
                    ->where('wfgl_original_number', $order_data['data']['ord_order_number'])
                    ->where('wfgl_type', 1)
                    ->where('wfgl_state', 1)
                    ->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);
                if (!empty($goods_data) && !empty($find_wfgl_data)) {
                    $orgf_wfgl_key = 0;
                    foreach ($goods_data as $key => $value) {
                        $digo_goo_quantity = $value['goo_quantity'];
                        foreach ($find_wfgl_data as $wfgl_key => $wfgl_value) { //从仓位商品表中扣除发货数量
                            if ($wfgl_value['wfgl_wago_id'] == $value['wago_id'] && $value['goo_inventory'] == $wfgl_value['wfgl_lock_type'] && $value['goo_waon_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']; //出库商品-仓位中锁定的数量
                                    // 订单商品仓位表
                                    $orgf_data[$orgf_wfgl_key]['orgf_shop_id'] = $user_info->adm_shop_id; //门店id
                                    $orgf_data[$orgf_wfgl_key]['orgf_ord_id'] = $order_data['data']['ord_id']; //订单id
                                    $orgf_data[$orgf_wfgl_key]['orgf_order_number'] = $order_data['data']['ord_order_number']; //订单单号
                                    $orgf_data[$orgf_wfgl_key]['orgf_orgo_id'] = $value['orgo_id']; //订单商品主键id
                                    $orgf_data[$orgf_wfgl_key]['orgf_wago_id'] = $value['wago_id']; //仓库商品主键id
                                    $orgf_data[$orgf_wfgl_key]['orgf_ware_id'] = $request['ware_id']; //仓库id
                                    $orgf_data[$orgf_wfgl_key]['orgf_wafr_id'] = $wfgl_value['wfgl_wafr_id']; //仓位id
                                    $orgf_data[$orgf_wfgl_key]['orgf_wafg_id'] = 0; //仓位商品主键id
                                    $orgf_data[$orgf_wfgl_key]['orgf_original_id'] = $order_data['data']['ord_id']; //原始单的id
                                    $orgf_data[$orgf_wfgl_key]['orgf_goo_id'] = $value['goo_id']; //商品id
                                    $orgf_data[$orgf_wfgl_key]['orgf_goo_inventory'] = $value['goo_inventory']; //出库类型1良品2优先
                                    $orgf_data[$orgf_wfgl_key]['orgf_outin_type'] = 1; //出入库类型：1出库2入库
                                    if ($digo_goo_quantity <= 0) { //出库商品-仓位中锁定的数量小于0，仓位锁定出库后还有剩余，出完了，跳出
                                        $orgf_data[$orgf_wfgl_key]['orgf_goo_quantity'] = $digo_goo_quantity + $wfgl_value['wfgl_lock_quantity']; //商品数量
                                        $find_wfgl_data[$wfgl_key]['wfgl_lock_quantity'] = abs($digo_goo_quantity);
                                        $orgf_wfgl_key++;
                                        break;
                                    } else {
                                        $orgf_data[$orgf_wfgl_key]['orgf_goo_quantity'] = $wfgl_value['wfgl_lock_quantity']; //商品数量
                                        $find_wfgl_data[$wfgl_key]['wfgl_lock_quantity'] = 0;
                                        $orgf_wfgl_key++;
                                    }
                                }
                            }
                        }
                    }
                    // 添加订单商品仓位记录
                    $orgf_res = DB::table('order_goods_freight')->insert($orgf_data);
                    unset($orgf_data);
                    if (!$orgf_res) {
                        DB::rollBack();
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'派单失败001']);
                    }
                }
                $wagl_res = DB::table('warehouse_goods_lock')->insert($wagl_data);
            } elseif ($find_order->ord_type == 5) { //5运营中心给门店派单
                $wago_id = array_unique($neaten_wago_id);
                // 生成订单时锁定库存
                $order_data['data']['ord_id'] = $request['ord_id'];
                $order_data['data']['ord_order_number'] = $find_order->ord_order_number;
                $order_data['data']['shop_id'] = $user_info->adm_shop_id;
                $order_data['data']['ord_type'] = $find_order->ord_type;
                $order_data['data']['ord_client_id'] = $request['wocl_client_id'];
                $request['ware_id'] = $request['wor_ware_id'];
                $order_lock_retrun = WarehouseLock::warehouseLockInventory(
                    $user_info,
                    $request->all(),
                    $order_data,
                    $neaten_goods_data
                );
                if ($order_lock_retrun['code'] == 500) {
                    DB::rollBack();
                    return response()->json($order_lock_retrun);
                }
                $wagl_res = DB::table('warehouse_goods_lock')->insert($wagl_data);
                // 遍历仓库类型数据，处理固定仓库对应仓库类型的库存-出入库记录
                if (!empty($wago_class_goods)  && $request['ord_service_type'] != 4 && $request['orcl_shipment_party'] != 4 && $request['orcl_shipment_party'] != 5) {
                    $request['ord_type'] = $request['wor_type'];
                    $request['ord_client_id'] = $request['wocl_client_id'];
                    $request['ware_id'] = $request['wor_ware_id'];
                    $ware_return_data = WarehouseLock::warehouseLockRecord(
                        $user_info,
                        $request->all(),
                        $order_data,
                        $wago_class_goods
                    );
                    if ($ware_return_data['code'] == 500) {
                        DB::rollBack();
                        return response()->json($ware_return_data);
                    }
                }
            } else {
                $wagl_res = DB::table('warehouse_goods_lock')
                    ->where('wagl_original_id', $request['ord_id'])
                    ->where('wagl_type', 1)
                    ->update(['wagl_original_correlation_id' => $dibi_data['dego_id'], 'wagl_correlation_type' => 2]);
            }
            if (empty($wagl_res)) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'派单失败4']);
            }
        }

        // 9. 生成操作记录
        $work_record = orderLog($user_info, $request['ord_id'], $wor_id, '生成工单');
        $assign_record = orderLog($user_info, 0, $wor_id, '派单');

        // 为门店生成订单
        if ($wor_id && $wogo_res && $wocl_id && $ord_res && $work_record && $assign_record) {
            $adm_phone =  DB::table('admin')
                ->where('adm_id', $request['wor_service_adm_id'])
                ->value('adm_phone');
            $push_name['alias'][] = $adm_phone; //发送对象
            Common::addLog($user_info, getRealIp($request), '订单列表', '生成工单', $wor_order_number . '派单成功');

            if (config('apisystem.SYNC_STATE') && $find_order->ord_type == 3) {
                $url = config('apisystem.sd_server_name') . '/index.php/sync_receipt_status';
                $param['serial_number'] = $find_order->ord_other_system_number; //第三方工单号
                $param['ip'] = getRealIp($request);
                $param['type'] = 1;
                $param['install_id'] = $request['wor_service_adm_id'];
                $param['time'] = date('Y-m-d H:i:s');
                $param['token'] = md5(md5($param['time'] . config('apisystem.sd_token'))); //token
                $doPost_res = Common::doPost($param, $url, 2);
                $doPost_res = json_decode($doPost_res);
                if ($doPost_res->code == 204) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'此技师未同步至速电']);
                }
                if ($doPost_res->code != 200) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'失败']);
                }
            }
            if ($whether_app == 1) {
                $result_push = pushMessage($push_name, '您有新的工单：' . $wor_order_number . ' 请注意查收');
            }
            if (!empty($request['wor_service_adm_id']) && $whether_app == 1) {
                $wechat_msg['pushtype'] = 1; //工单推送
                $wechat_msg['adm_id'] = $request['wor_service_adm_id']; //推送人
                $wechat_msg['wor_number'] = $wor_order_number; //工单号
                $wechat_msg['ord_number'] = $find_order->ord_order_number; //订单号
                $wechat_msg['order_type'] = ordType($find_order->ord_service_type); //订单类型
                $wechat_msg['user_name'] = $request['wocl_name']; //姓名
                $wechat_msg['user_phone'] = $request['wocl_phone']; //手机号
                $wechat_msg['user_dress'] = $request['wocl_province'] . $request['wocl_city'] . $request['wocl_county'] . $request['wocl_address']; //手机号
                $wechat_msg['tittle'] = '您有新工单请及时处理'; //手机
                $wechat_msg['remark'] = isset($request['wor_remark']) ? $request['wor_remark'] : '';
                $CashierDesk = new CashierDesk;
                $CashierDesk->inforPush($wechat_msg);
            }
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'派单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'派单失败']);
        }
    }

    // 工作总台-派单，生成订单/工单+派单
    public function workOrderAssign(Request $request)
    {
        if (!isset($request['service_adm_id']) || empty($request['service_adm_id'])) {
            $request->offsetSet('service_adm_id', 0);
        }
        if (!isset($request['ware_id']) || !$request['ware_id']) {
            $request['ware_id'] = 0;
        }

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

        if ($request['orcl_shipment_party'] != 5) {
            if (empty($request['service_adm_id'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'请选择服务技师']);
            }
        }

        // ord_service_type 订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单 7救援单
        if ($request['orcl_shipment_party'] != 5) {
            if (in_array($request['ord_service_type'], [2, 3, 4, 5, 6])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单类型不需要技师服务，无法派单']);
            }
        }

        // 等于4是虚拟加盟店
        if ($request['orcl_shipment_party'] == 4) {
            if ($request['ord_type'] == 2) {
                $vish_chun_id = DB::table('virtual_shop')
                    ->where('vish_id', $request['service_shop_id'])
                    ->value('vish_chun_id');
                if ($request['ord_client_id'] == $vish_chun_id) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'虚拟加盟店与客户单位相同，无法派单']);
                }
            }
        }
        $neaten_goods_data = []; //整理后的仓库商品库存数据
        $goods_data = []; //提交的商品数据
        $goo_all_quantity = 0; //商品总数量
        $goo_all_price = 0; //商品总金额
        $goods_data = json_decode($request['goods_data'], true);
        // 判断提交的商品参数
        if (empty($goods_data)) {
            // 救援单的可以不选商品
            if ($request['ord_service_type'] != 7) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'请选择商品']);
            }
        } else {
            foreach ($goods_data as $key => $value) {
                if (!isset($value['wago_id'])) {
                    $value['wago_id'] = 0;
                    $goods_data[$key]['wago_id'] = 0;
                }
                if (!is_numeric($value['wago_id']) || !is_numeric($value['goo_id']) || !in_array($value['goo_state'], [1, 3, 4, 5, 6, 7, 8]) || !is_numeric($value['goo_waon_class']) || !in_array($value['goo_inventory'], [1, 2])  || !is_numeric($value['goo_price']) || !is_numeric($value['goo_collection_price']) || !is_numeric($value['goo_quantity'])) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品参数类型错误']);
                }
                // goo_state 商品状态1正常3回收的商品4换货商品5赠品商品6备用电池7临时商品8旧货商品
                if ($value['goo_state'] != 4) {
                    // [仓库商品id][出库类型：良品/优先]，用于判断仓库是否有库存
                    if (isset($neaten_goods_data[$value['wago_id']][$value['goo_inventory']])) {
                        $neaten_goods_data[$value['wago_id']][$value['goo_inventory']]['goo_quantity'] += $value['goo_quantity'];
                    } else {
                        $neaten_goods_data[$value['wago_id']][$value['goo_inventory']] = $value;
                    }
                    $goo_all_quantity += $value['goo_quantity'];
                    $goo_all_price += $value['goo_quantity'] * $value['goo_price'];
                }
                // 工作总台开单的时候，判断一下商品金额小于当前进销存的成本，生成待审核状态订单，需要审核通过
                if (in_array($request['ord_service_type'], [1, 5, 7]) && !in_array($value['goo_state'], [5, 6, 7])) {
                    // 获取订单商品成本价
                    $orgo_goo_cost = DB::table('enters_sells_saves')
                        ->where('ense_goo_warehouse', $request['ware_id'])
                        ->where('ense_goo_waretype', $value['goo_waon_class'])
                        ->where('ense_goo_id', $value['goo_id'])
                        ->value('ense_end_price');
                    $orgo_data[$key]['orgo_goo_cost'] = $orgo_goo_cost * 100; //商品成本
                    if ($value['goo_price'] < $orgo_goo_cost) {
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品零售金额小于成本金额，不能立即派单！']);
                    }
                }
                // 仓库类别对应的商品，库存-出入库记录
                if (isset($wago_class_goods[$value['goo_inventory']][$value['goo_waon_class']][$value['goo_id']])) {
                    $wago_class_goods[$value['goo_inventory']][$value['goo_waon_class']][$value['goo_id']]['goo_quantity'] = $wago_class_goods[$value['goo_inventory']][$value['goo_waon_class']][$value['goo_id']]['goo_quantity'] + $value['goo_quantity'];
                } else {
                    $wago_class_goods[$value['goo_inventory']][$value['goo_waon_class']][$value['goo_id']] = $value;
                }
            }
        }
        // 获取当前操作账号信息
        $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;

        if ($request['ord_type'] == 2) {
            // 判断是否通过可欠金额  可欠天数的判断
            $CashierDesk = new CashierDesk;
            $return_exceed = $CashierDesk->isExceed($request->all(), $user_info, $goo_all_price);
            if (empty($return_exceed)) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前客户单位的可欠金额、可欠天数超出设置值，无法派单']);
            }
        }

        DB::beginTransaction();
        // 订单缓存表 清除缓存数据
        $order_cache = new OrderCache();
        $clear_return = $order_cache->clearOrderCache($user_info);
        if ($clear_return['code'] == 500) {
            DB::rollBack();
            return response()->json($clear_return);
        }

        // 生成订单数据
        $service_order = new Order();
        $order_data = $service_order->createOrder($user_info, $request->all(), 2);
        if ($order_data['code'] == 500) {
            DB::rollBack();
            return response()->json($order_data);
        }

        // 2. 添加订单商品表数据
        $goo_all_quantity = 0; //商品总数量
        $goo_all_price = 0; //商品总金额
        $goo_assign_all_price = 0; //商品总派单金额
        $goo_collection_price = 0; //商品代收总金额

        // 救援单的服务项目金额
        $orcl_rescue_service_price = $request->filled('orcl_rescue_service_price') ? $request['orcl_rescue_service_price'] : 0;
        // 救援单的代收金额
        $orcl_rescue_collection_price = $request->filled('orcl_rescue_collection_price') ? $request['orcl_rescue_collection_price'] : 0;
        // 救援单派单金额
        $orcl_rescue_assign_price = $request->filled('orcl_rescue_assign_price') ? $request['orcl_rescue_assign_price'] : 0;

        if (empty($goods_data)) {
            $goo_all_price = $orcl_rescue_service_price * 100;
            $goo_assign_all_price = $orcl_rescue_assign_price * 100;
        } else {
            $find_order_goods = DB::table('order_goods')
                ->where('orgo_ord_id', $order_data['data']['ord_id'])
                ->select('orgo_id', 'orgo_ware_id', 'orgo_waon_class', 'orgo_wago_id', 'orgo_goo_id', 'orgo_goo_name', 'orgo_tem_goo_name', 'orgo_goo_goods_encode', 'orgo_goo_ampere_hour', 'orgo_goo_type', 'orgo_goo_price', 'orgo_state', 'orgo_collection_price', 'orgo_goo_quantity', 'orgo_goo_inventory', 'orgo_assign_price')
                ->get();
            $find_order_goods = json_decode(json_encode($find_order_goods, true), true);
            foreach ($find_order_goods as $key => $value) {
                // goo_state 商品状态1.正常 2.删除3.回收的商品4.换货商品5.赠品商品6.备用电池7.临时商品8.旧货商品
                // 换货商品金额处理
                if ($value['orgo_state'] == 1 || $value['orgo_state'] == 5) {
                    // 订单商品
                    $goo_all_price += $value['orgo_goo_price'] * $value['orgo_goo_quantity'];
                    $goo_assign_all_price += $value['orgo_assign_price'] * $value['orgo_goo_quantity'];

                    $goo_all_quantity += $value['orgo_goo_quantity']; //商品总数量
                    $goo_collection_price += $value['orgo_collection_price'];
                } elseif ($value['orgo_state'] == 4) { //换货商品
                } elseif ($value['orgo_state'] == 6) { //备用电池
                    $goo_all_quantity += $value['orgo_goo_quantity']; //商品总数量
                    $goo_all_price += $value['orgo_goo_price'] * $value['orgo_goo_quantity'];
                    $goo_collection_price += $value['orgo_collection_price'];
                } elseif ($value['orgo_state'] == 7) { //临时商品
                    $goo_all_price += $value['orgo_goo_price'] * $value['orgo_goo_quantity'];
                    $goo_all_quantity += $value['orgo_goo_quantity']; //商品总数量
                } elseif ($value['orgo_state'] == 8) { //旧货商品
                    $goo_all_price += $value['orgo_goo_price'] * $value['orgo_goo_quantity'];
                    $goo_assign_all_price += $value['orgo_assign_price'] * $value['orgo_goo_quantity'];
                    $goo_all_quantity += $value['orgo_goo_quantity']; //商品总数量
                    $goo_collection_price += $value['orgo_collection_price']; //商品代收总金额
                }

                // 工单商品表数据
                $wogo_data[$key]['wogo_ware_id'] = $value['orgo_ware_id'];
                $wogo_data[$key]['wogo_waon_class'] = $value['orgo_waon_class'];
                $wogo_data[$key]['wogo_goo_id'] = $value['orgo_goo_id'];
                $wogo_data[$key]['wogo_actual_goo_id'] = $value['orgo_goo_id']; //实际出库商品id
                $wogo_data[$key]['wogo_wago_id'] = $value['orgo_wago_id']; //仓库商品id
                $wogo_data[$key]['wogo_orgo_id'] = $value['orgo_id']; //订单商品表主键id
                $wogo_data[$key]['wogo_tem_goo_name'] = $value['orgo_tem_goo_name'];
                $wogo_data[$key]['wogo_goo_name'] = $value['orgo_goo_name'];
                $wogo_data[$key]['wogo_goo_goods_encode'] = $value['orgo_goo_goods_encode'];
                $wogo_data[$key]['wogo_goo_type'] = $value['orgo_goo_type'];
                $wogo_data[$key]['wogo_state'] = $value['orgo_state'];
                if ($request['orcl_shipment_party'] == 5 || $request['orcl_shipment_party'] == 4 || $request['orcl_shipment_party'] == 3) {
                    $wogo_data[$key]['wogo_assign_price'] = $value['orgo_assign_price'];
                    $wogo_data[$key]['wogo_goo_price'] = $value['orgo_assign_price'];
                } else {
                    $wogo_data[$key]['wogo_goo_price'] = $value['orgo_goo_price'];
                }
                $wogo_data[$key]['wogo_collection_price'] = $value['orgo_collection_price'];
                $wogo_data[$key]['wogo_goo_amount'] = $value['orgo_goo_quantity'];
                $wogo_data[$key]['wogo_goo_inventory'] = $value['orgo_goo_inventory'];
                $wogo_data[$key]['wogo_update_time'] = date('Y-m-d H:i:s');
            }
            $goo_all_price = $goo_all_price + $orcl_rescue_service_price * 100;
            $goo_assign_all_price = $goo_assign_all_price + $orcl_rescue_assign_price * 100;
        }

        // 虚拟加盟店
        if ($request['orcl_shipment_party'] == 4 || $request['orcl_shipment_party'] == 3 || $request['orcl_shipment_party'] == 5) {
            // 虚拟加盟店工单金额与订单金额相反
            if ($goo_assign_all_price > 0) {
                $goo_all_price = '-' . $goo_assign_all_price;
            } else {
                $goo_all_price = abs($goo_assign_all_price);
            }
        } else {
            // 工单金额 = 总金额
            $goo_all_price = $goo_all_price;
        }

        // 6. 添加工单表数据
        $wor_order_number = Common::workRule($user_info);
        $wor_data['wor_cid'] = $user_info->adm_cid;
        $wor_data['wor_shop_id'] = $user_info->adm_shop_id;
        $wor_data['wor_superior_shop_id'] = $order_data['data']['shop_id'];
        $wor_data['wor_create_id'] = $user_info->adm_id;
        $wor_data['wor_number'] = $wor_order_number; //工单
        $wor_data['wor_order_id'] = $order_data['data']['ord_id']; //订单id
        $wor_data['wor_order_number'] = $order_data['data']['ord_order_number']; //订单号
        if ($request['service_shop_id']) {
            // 选择服务门店
            $wor_data['wor_service_shop_id'] = $request['service_shop_id']; //服务门店id
        } else {
            // 没有选择门店，就是当前门店
            $wor_data['wor_service_shop_id'] = $user_info->adm_shop_id; //服务门店id
        }
        $wor_data['wor_service_sepr_id'] = $request['service_sepr_id']; //服务项目id
        $wor_data['wor_service_adm_id'] = $request['service_adm_id']; //服务技师id
        // 订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单
        $wor_data['wor_service_type'] = $request['ord_service_type'];
        // 是否走技师流程  1是  2否
        if (!empty($request['orcl_whether_app']) && ($request['orcl_whether_app'] == 2) && ($request['orcl_shipment_party'] == 4)) {
            // 虚拟加盟店，不走技师流程
            $wor_data['wor_service_state'] = 6;
            $wor_data['wor_state'] = 8;
            $whether_app = 2;
        } else {
            $wor_data['wor_service_state'] = 1;
            $wor_data['wor_state'] = 3;
            $whether_app = 1;
        }
        // 审核：1.待审核 2.合格 3.不合格
        $wor_data['wor_pass'] = 1;
        $wor_data['wor_type'] = $request['ord_type'];
        $wor_data['wor_remark'] = $request['ord_remark'] ? $request['ord_remark'] : ''; //工单备注
        $wor_data['wor_ware_id'] = $request['ware_id'] ? $request['ware_id'] : ''; //仓库id
        $wor_data['wor_actual_price'] = $goo_all_price; //工单结算金额（单位：分）
        $wor_data['wor_collection_price'] = $goo_collection_price + $orcl_rescue_collection_price * 100; //商品代收金额（单位：分）
        $wor_data['wor_goo_amount'] = $goo_all_quantity; //总的商品数量
        if (isset($request['orcl_appoint_time']) && !empty($request['orcl_appoint_time'])) {
            $wor_data['wor_appoint_time'] = $request['orcl_appoint_time']; //预约时间
        }
        $wor_data['wor_update_time'] = date('Y-m-d H:i:s');
        $wor_id = DB::table('work_order')->insertGetId($wor_data);

        // 添加工单备注
        if (!empty($request['ord_remark'])) {
            $wor_remark = orderRemark($user_info, $order_data['data']['ord_id'], $wor_id, $request['ord_remark'], '工作总台');
        } else {
            $wor_remark = true;
        }

        if (!empty($goods_data)) {
            // 7. 添加工单商品表数据
            foreach ($wogo_data as $key => $value) {
                $goods_data[$key]['orgo_id'] = $value['wogo_orgo_id'];
                $wogo_data[$key]['wogo_wor_id'] = $wor_id;
                $wogo_res = DB::table('work_good')->insert($wogo_data[$key]);
            }
        } else {
            $wogo_res = true;
        }
        // 8. 添加工单客户表数据
        if ($request['ord_type'] == '2') {
            $chun_adm_id = DB::table('channel_unit')
                ->where('chun_id', $request['ord_client_id'])
                ->value('chun_adm_id');
            if (empty($chun_adm_id)) {
                $chun_adm_id = 0;
            }
        } else {
            $chun_adm_id = 0;
        }
        $wocl_data = [
            'wocl_wor_id' => $wor_id,
            'wocl_client_id' => $request['ord_client_id'] ? $request['ord_client_id'] : 0, //渠道单位或者客户单位id
            'wocl_adm_id' => $chun_adm_id, //业务员id
            'wocl_channel_unit' => $request['orcl_channel_unit'] ? $request['orcl_channel_unit'] : '',
            'wocl_name' => $request['orcl_name'],
            'wocl_phone' => $request['orcl_phone'],
            'wocl_car_num' => $request['orcl_car_num'] ? $request['orcl_car_num'] : '', //车牌号
            'wocl_car_vehicle_type' => $request['orcl_car_vehicle_type'] ? $request['orcl_car_vehicle_type'] : '', //车型
            'wocl_province' => $request['orcl_province'],
            'wocl_city' => $request['orcl_city'],
            'wocl_county' => $request['orcl_county'],
            'wocl_address' => $request['orcl_address'],
            'wocl_longitude' => $request['longitude'], //经度
            'wocl_latitude' => $request['latitude'], //纬度
            'wocl_chin_type' => $request['chin_type'] ? $request['chin_type'] : 2, //铺货类型：1是铺货 2不是铺货
            'wocl_collect_state' => $request->input('orcl_collect_state', 0),
            // 救援单的代收金额
            'wocl_rescue_collection_price' => $orcl_rescue_collection_price * 100,
            'wocl_update_time' => date('Y-m-d H:i:s'),
            'wocl_standby_battery_type' => isset($request['orcl_standby_battery_type']) ? $request['orcl_standby_battery_type'] : 2,
            'wocl_junk_type' => isset($request['orcl_junk_type']) ? $request['orcl_junk_type'] : 2, //是否回收旧货1是2否
            'wocl_whether_app' => $whether_app, //是否走技师流程1是2否
            'wocl_precise_lock' => isset($request['precise_lock']) ? $request['precise_lock'] : 2, //精确打卡1是 2否
        ];
        // 如果是虚拟加盟店
        if ($request['orcl_shipment_party'] == 4) {
            $wocl_data['wocl_wor_type'] = 4;
            // 救援单的服务项目金额
            $wocl_data['wocl_rescue_service_price'] = $orcl_rescue_assign_price * 100;
        } elseif ($request['orcl_shipment_party'] == 5) {
            $wocl_data['wocl_wor_type'] = 5;
            // 救援单的服务项目金额
            $wocl_data['wocl_rescue_service_price'] = $orcl_rescue_assign_price * 100;
        } else {
            $wocl_data['wocl_rescue_service_price'] = $orcl_rescue_service_price * 100;
        }

        // ord_service_type 订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单 7救援单
        if (in_array($request['ord_service_type'], [1, 7])) {
            // 订单类型为服务单、救援单的有图片上传模板，根据订单类型，获取当前门店的图片上传模板
            $image_manager = new ImageUpload();
            $find_shit_id = $image_manager->getOrderTypeImageTemplate($user_info->adm_shop_id, $request['ord_service_type']);
            $wocl_data['wocl_shit_id'] = $find_shit_id; //图片模板id
        }
        $wocl_id = DB::table('work_client')->insertGetId($wocl_data);

        // 服务类型不为退货单 且 有商品数据 生成发货单  且不是虚拟加盟店
        if ($request['ord_service_type'] != 4 && !empty($goods_data) && $request['orcl_shipment_party'] != 4 && $request['orcl_shipment_party'] != 5) {
            $dibi_data = DispatchBill::create(
                $user_info,   //用户信息
                $request->all(),  //订单提交数据
                $goods_data,  //提交的商品数据
                2,  //类型：1.订单发货 2.工单发货
                $request['ware_id'],  //出库仓库id
                $wor_order_number,  //原始单号，订单号/工单号
                $wor_id,  //发货单关联的工单/订单id
                $order_data['data']['shop_id'],  //所属总店id
                $request['ord_type'],  //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
                $request['ord_client_id'],  //选择的客户id,会员id/单位id
                $goo_all_quantity  //发货总数量
            );
            if ($dibi_data['code'] == 500) {
                DB::rollBack();
                return response()->json($dibi_data);
            }

            if (!empty($neaten_goods_data)) { //仓库
                $ware_lock_return = WarehouseLock::warehouseLockInventory(
                    $user_info,
                    $request->all(),
                    $order_data,
                    $neaten_goods_data
                );
                if ($ware_lock_return['code'] == 500) {
                    DB::rollBack();
                    return response()->json($ware_lock_return);
                }
                // 查询仓位商品锁定表
                $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_ware_id', $request['ware_id'])
                    ->where('wfgl_correlation_type', 1)
                    ->where('wfgl_original_id', $order_data['data']['ord_id'])
                    ->where('wfgl_original_number', $order_data['data']['ord_order_number'])
                    ->where('wfgl_type', 1)
                    ->where('wfgl_state', 1)
                    ->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);
                if (!empty($goods_data) && !empty($find_wfgl_data)) {
                    $orgf_wfgl_key = 0;
                    foreach ($goods_data as $key => $value) {
                        $digo_goo_quantity = $value['goo_quantity'];
                        foreach ($find_wfgl_data as $wfgl_key => $wfgl_value) { //从仓位商品表中扣除发货数量
                            if ($wfgl_value['wfgl_wago_id'] == $value['wago_id'] && $value['goo_inventory'] == $wfgl_value['wfgl_lock_type'] && $value['goo_waon_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']; //出库商品-仓位中锁定的数量
                                    // 订单商品仓位表
                                    $orgf_data[$orgf_wfgl_key]['orgf_shop_id'] = $user_info->adm_shop_id; //门店id
                                    $orgf_data[$orgf_wfgl_key]['orgf_ord_id'] = $order_data['data']['ord_id']; //订单id
                                    $orgf_data[$orgf_wfgl_key]['orgf_order_number'] = $order_data['data']['ord_order_number']; //订单单号
                                    $orgf_data[$orgf_wfgl_key]['orgf_orgo_id'] = $value['orgo_id']; //订单商品主键id
                                    $orgf_data[$orgf_wfgl_key]['orgf_wago_id'] = $value['wago_id']; //仓库商品主键id
                                    $orgf_data[$orgf_wfgl_key]['orgf_ware_id'] = $request['ware_id']; //仓库id
                                    $orgf_data[$orgf_wfgl_key]['orgf_wafr_id'] = $wfgl_value['wfgl_wafr_id']; //仓位id
                                    $orgf_data[$orgf_wfgl_key]['orgf_wafg_id'] = 0; //仓位商品主键id
                                    $orgf_data[$orgf_wfgl_key]['orgf_original_id'] = $order_data['data']['ord_id']; //原始单的id
                                    $orgf_data[$orgf_wfgl_key]['orgf_goo_id'] = $value['goo_id']; //商品id
                                    $orgf_data[$orgf_wfgl_key]['orgf_goo_inventory'] = $value['goo_inventory']; //出库类型1良品2优先
                                    $orgf_data[$orgf_wfgl_key]['orgf_outin_type'] = 1; //出入库类型：1出库2入库
                                    if ($digo_goo_quantity <= 0) { //出库商品-仓位中锁定的数量小于0，仓位锁定出库后还有剩余，出完了，跳出
                                        $orgf_data[$orgf_wfgl_key]['orgf_goo_quantity'] = $digo_goo_quantity + $wfgl_value['wfgl_lock_quantity']; //商品数量
                                        $find_wfgl_data[$wfgl_key]['wfgl_lock_quantity'] = abs($digo_goo_quantity);
                                        $orgf_wfgl_key++;
                                        break;
                                    } else {
                                        $orgf_data[$orgf_wfgl_key]['orgf_goo_quantity'] = $wfgl_value['wfgl_lock_quantity']; //商品数量
                                        $find_wfgl_data[$wfgl_key]['wfgl_lock_quantity'] = 0;
                                        $orgf_wfgl_key++;
                                    }
                                }
                            }
                        }
                    }
                    // 添加订单商品仓位记录
                    $orgf_res = DB::table('order_goods_freight')->insert($orgf_data);
                    unset($orgf_data);
                    if (!$orgf_res) {
                        DB::rollBack();
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'派单失败001']);
                    }
                }
                $neaten_wago_id = []; //良品商品
                $priority_neaten_wago_id = []; //优先商品
                $wagl_key = 0;
                $wagl_lock_quantity = []; //仓库锁定表的商品锁定数量
                foreach ($neaten_goods_data as $wago_id => $wago_id_value) {
                    foreach ($wago_id_value as $goo_inventory => $goo_value) {
                        if ($goo_inventory == 1) {
                            // 良品商品锁定库存
                            $ware_id[$wago_id] = $request['ware_id'];
                            $wago_goo_id[$wago_id] = $goo_value['goo_id'];
                            $wago_goo_quantity[$wago_id] = $goo_value['goo_quantity'];
                            $wago_goo_inventory[$wago_id] = $goo_inventory;
                            $wago_goo_class[$wago_id] = $goo_value['goo_waon_class'];
                            $neaten_wago_id[] = $wago_id;
                        } else {
                            // 优先商品锁定库存
                            $priority_ware_id[$wago_id] = $request['ware_id'];
                            $priority_wago_goo_id[$wago_id] = $goo_value['goo_id'];
                            $priority_wago_goo_quantity[$wago_id] = $goo_value['goo_quantity'];
                            $priority_wago_goo_inventory[$wago_id] = $goo_inventory;
                            $priority_wago_goo_class[$wago_id] = $goo_value['goo_waon_class'];
                            $priority_neaten_wago_id[] = $wago_id;
                        }
                        // 仓库锁定表的商品锁定数量：良品+优先 总的锁定数量
                        if (isset($wagl_lock_quantity[$wago_id])) {
                            $wagl_lock_quantity[$wago_id] += $goo_value['goo_quantity'];
                        } else {
                            $wagl_lock_quantity[$wago_id] = $goo_value['goo_quantity'];
                        }
                    }

                    // 仓库商品锁定表
                    $wagl_data[$wagl_key]['wagl_shop_id'] = $user_info->adm_shop_id;
                    $wagl_data[$wagl_key]['wagl_ware_id'] = $request['ware_id'];
                    $wagl_data[$wagl_key]['wagl_wago_id'] = $wago_id;
                    $wagl_data[$wagl_key]['wagl_original_id'] = $order_data['data']['ord_id'];
                    $wagl_data[$wagl_key]['wagl_original_number'] = $order_data['data']['ord_order_number'];
                    $wagl_data[$wagl_key]['wagl_original_correlation_id'] = $order_data['data']['ord_id']; //关联id：订单id/发货单id/调拨单id
                    $wagl_data[$wagl_key]['wagl_correlation_type'] = 1; //关联类型：1订单2发货单3调拨单
                    $wagl_data[$wagl_key]['wagl_type'] = 1; //  原始单类型：1订单2调拨单
                    $wagl_data[$wagl_key]['wagl_state'] = 1; //锁定状态：1下单锁定2出库解锁
                    $wagl_data[$wagl_key]['wagl_lock_quantity'] = $wagl_lock_quantity[$wago_id]; //商品锁定库存数量
                    $wagl_key++;
                }

                foreach ($wagl_data as $key => $value) {
                    $wagl_data[$key]['wagl_original_correlation_id'] = $dibi_data['dego_id']; //关联id：订单id/发货单id/调拨单id
                    $wagl_data[$key]['wagl_correlation_type'] = 2; //关联类型：1订单2发货单3调拨单
                }
                // 锁定数量
                if (!empty($wagl_data)) {
                    $wagl_res = DB::table('warehouse_goods_lock')->insert($wagl_data);
                    if (!$wagl_res) {
                        DB::rollBack();
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'派单失败2']);
                    }
                }
            }
        }

        // 14. 生成操作记录
        $order_record_res = orderLog($user_info, $order_data['data']['ord_id'], 0, '生成订单');
        $work_record_res = orderLog($user_info, 0, $wor_id, '生成工单');
        $assign_record_res = orderLog($user_info, 0, $wor_id, '派单');
        // 判断是否是外派门店
        if ($request['orcl_shipment_party'] == 5) {
            // 给门店创建订单
            $find_user_info = DB::table('admin')
                ->where('adm_shop_id', $request['service_shop_id'])
                ->select('adm_id', 'adm_cid', 'adm_shop_id', 'adm_superior_shop_id as shop_superior_id', 'adm_name', 'adm_phone')
                ->first();

            $add_shop_order_res = $this->addShopOrder($find_user_info, $request, $wocl_id);
            if ($add_shop_order_res['code'] == 200) {
                // 将门店id与工单绑定
                $wocl_upd['wocl_join_ord_id'] = $add_shop_order_res['data'];
                $wocl_upd['wocl_update_time'] = date('Y-m-d H:i:s');
                $wc_updres = DB::table('work_client')->where('wocl_id', $wocl_id)->update($wocl_upd);
                $add_shop_order_res = true;
            } else {
                return response()->json($add_shop_order_res);
                $wc_updres = false;
                $add_shop_order_res = false;
            }
        } else {
            $wc_updres = true;
            $add_shop_order_res = true;
        }

        // 遍历仓库类型数据，处理固定仓库对应仓库类型的库存-出入库记录
        if (!empty($wago_class_goods) && $request['ord_service_type'] != 4 && $request['orcl_shipment_party'] != 4 && $request['orcl_shipment_party'] != 5) {
            $ware_return_data = WarehouseLock::warehouseLockRecord(
                $user_info,
                $request->all(),
                $order_data,
                $wago_class_goods
            );
            if ($ware_return_data['code'] == 500) {
                DB::rollBack();
                return response()->json($ware_return_data);
            }
        }

        if ($add_shop_order_res && $wc_updres && $wor_id && $wogo_res && $wocl_id && $order_record_res && $work_record_res && $assign_record_res && $wor_remark) {
            // 等于4是虚拟加盟店
            if ($whether_app == 1) {
                $adm_phone =  DB::table('admin')
                    ->where('adm_id', $request['service_adm_id'])
                    ->value('adm_phone');
                $push_name['alias'][] = $adm_phone; //发送对象
                $result_push = pushMessage($push_name, '您有新的工单：' . $wor_order_number . ' 请注意查收');
            }
            Common::addLog($user_info, getRealIp($request), '订单列表', '派单', $wor_order_number . '派单成功');
            if (!empty($request['service_adm_id']) && $whether_app == 1) {
                $wechat_msg['pushtype'] = 1; //工单推送
                $wechat_msg['adm_id'] = $request['service_adm_id']; //推送人
                $wechat_msg['wor_number'] = $wor_order_number; //工单号
                $wechat_msg['ord_number'] = $order_data['data']['ord_order_number']; //订单号
                $wechat_msg['order_type'] = ordType($request['ord_service_type']); //订单类型
                $wechat_msg['user_name'] = $request['orcl_name']; //姓名
                $wechat_msg['user_phone'] = $request['orcl_phone']; //手机号
                $wechat_msg['user_dress'] = $request['orcl_province'] . $request['orcl_city'] . $request['orcl_county'] . $request['orcl_address']; //手机号
                $wechat_msg['tittle'] = '您有新工单请及时处理'; //手机
                $wechat_msg['remark'] = isset($request['ord_remark']) ? $request['ord_remark'] : '';
                $CashierDesk = new CashierDesk;
                $CashierDesk->inforPush($wechat_msg);
            }

            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'派单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'派单失败1']);
        }
    }

    // 门店拒单 城市运营中心重新派单
    public function assignAgain(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyCashierDeskController;
        $error_message = $verify_data->assignAgainValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $find_orddata = DB::table('work_order')
            ->where('wor_id', $request['wor_id'])
            ->select('wor_order_id', 'wor_order_number')
            ->first();
        // 修改订单数据
        $ord_up['ord_wor_state'] = 2; //订单的工单状态 1未派工单2服务中3售后中4已完成5无工单6审核活动7待接单8锁定9速电撤销回收10终止11取消订单12超出可欠天数待审核
        $ord_up['ord_service_shop_id'] = $request['service_shop_id']; //服务门店id
        $ord_up['ord_service_sepr_id'] = $request['service_sepr_id']; //服务项目id
        $ord_up['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_up_res = DB::table('order')->where('ord_id', $find_orddata->wor_order_id)->update($ord_up);

        // 修改工单数据
        $wor_up['wor_service_state'] = 1; //服务状态：1待接单2已接单3预约4出发5抵达6完成待审核7完成已驳回8完成通过9终止10锁定11速电撤销回收12工单冲单',
        $wor_up['wor_state'] = 3; //工单状态 1.新订单 2未派单 3待接单/已派单 4.未出发/已接单 5.预约/已预约 6.出发/已出发  7.抵达/抵达 8.待审核/完成待审核 9驳回/完成已驳回 10完成/完成已通过 11终止 12锁定13.速电撤销回收14工单冲单
        $wor_up['wor_service_shop_id'] = $request['service_shop_id']; //服务门店id
        $wor_up['wor_service_sepr_id'] = $request['service_sepr_id']; //服务项目id
        $wor_up['wor_update_time'] = date('Y-m-d H:i:s');
        $wor_up_res = DB::table('work_order')
            ->where('wor_id', $request['wor_id'])
            ->update($wor_up);
        $wocl_id = DB::table('work_client')->where('wocl_wor_id', $request['wor_id'])->value('wocl_id');

        // 给门店创建订单
        $find_user_info = DB::table('admin')
            ->where('adm_shop_id', $request['service_shop_id'])
            ->select('adm_id', 'adm_cid', 'adm_shop_id', 'adm_superior_shop_id as shop_superior_id', 'adm_name', 'adm_phone')
            ->first();
        $find_goods = DB::table('work_good')
            ->where('wogo_wor_id', $request['wor_id'])
            ->select('wogo_ware_id', 'wogo_wago_id as wago_id', 'wogo_actual_goo_id', 'wogo_tem_goo_name as tem_goo_name', 'wogo_goo_id as goo_id', 'wogo_waon_class as goo_waon_class', 'wogo_state as goo_state', 'wogo_goo_name', 'wogo_goo_goods_encode', 'wogo_goo_type', 'wogo_collection_price as goo_collection_price', 'wogo_goo_price as goo_price', 'wogo_assign_price as goo_assign_price', 'wogo_goo_amount as goo_quantity', 'wogo_goo_amount', 'wogo_goo_inventory as goo_inventory', 'wogo_goo_exchange', 'wogo_orgo_id')
            ->get();
        foreach ($find_goods as $key => $value) {
            $find_goods[$key]->goo_assign_price = $value->goo_price / 100;
            $find_goods[$key]->goo_price = $value->goo_price / 100;
            $find_goods[$key]->goo_collection_price = $value->goo_collection_price / 100;
        }
        $find_ord = DB::table('order as o')
            ->leftJoin('order_client as oc', 'oc.orcl_ord_id', '=', 'o.ord_id')
            ->where('ord_id', $find_orddata->wor_order_id)
            ->select('ord_service_type', 'ord_client_id', 'ord_payment_way', 'orcl_rescue_service_price', 'orcl_rescue_collection_price', 'orcl_channel_unit', 'orcl_name', 'orcl_phone', 'orcl_car_num', 'orcl_province', 'orcl_city', 'orcl_county', 'orcl_address', 'orcl_chin_type as chin_type', 'orcl_collect_state', 'orcl_junk_type', 'orcl_shipment_party', 'orcl_rescue_assign_price', 'orcl_car_vehicle_type')
            ->first();
        $request['goods_data'] = $find_goods;
        $request['ord_client_id'] = $find_ord->ord_client_id;
        $request['ord_service_type'] = $find_ord->ord_service_type;
        $request['ord_payment_way'] = $find_ord->ord_payment_way;
        $request['orcl_rescue_service_price'] = $find_ord->orcl_rescue_service_price / 100;
        $request['orcl_rescue_assign_price'] = $find_ord->orcl_rescue_assign_price / 100;
        $request['orcl_rescue_collection_price'] = $find_ord->orcl_rescue_collection_price / 100;
        $request['orcl_channel_unit'] = $find_ord->orcl_channel_unit;
        $request['orcl_name'] = $find_ord->orcl_name;
        $request['orcl_phone'] = $find_ord->orcl_phone;
        $request['orcl_car_num'] = $find_ord->orcl_car_num;
        $request['orcl_car_vehicle_type'] = $find_ord->orcl_car_vehicle_type;
        $request['orcl_province'] = $find_ord->orcl_province;
        $request['orcl_city'] = $find_ord->orcl_city;
        $request['orcl_county'] = $find_ord->orcl_county;
        $request['orcl_address'] = $find_ord->orcl_address;
        $request['chin_type'] = $find_ord->chin_type;
        $request['orcl_collect_state'] = $find_ord->orcl_collect_state;
        $request['orcl_junk_type'] = $find_ord->orcl_junk_type;
        $request['orcl_shipment_party'] = $find_ord->orcl_shipment_party;
        $request['ware_id'] = 0;
        // $request['assignment'] = 1;
        $add_shop_order_res = $this->addShopOrder($find_user_info, $request, $wocl_id);
        // 修改工单客户表数据
        if ($add_shop_order_res['code'] == 200) {
            //将门店id与工单绑定
            $wocl_upd['wocl_join_ord_id'] = $add_shop_order_res['data'];
            $wocl_upd['wocl_update_time'] = date('Y-m-d H:i:s');
            $wocl_upd_res = DB::table('work_client')->where('wocl_id', $wocl_id)->update($wocl_upd);
            $add_shop_order_result = true;
        } else {
            $wocl_upd_res = false;
            $add_shop_order_result = false;
            response()->json($add_shop_order_res);
        }
        if ($add_shop_order_result && $ord_up_res && $wor_up_res && $wocl_upd_res) {
            Common::addLog($user_info, getRealIp($request), '工单列表', '派单', $find_orddata->wor_order_number . '派单成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'派单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'派单失败1']);
        }
    }

    // 为门店生成订单
    private function addShopOrder($user_info, $request, $wocl_id)
    {
        $goods_data = json_decode($request['goods_data'], true);
        // 判断是否为加盟店账号,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 (!$request['ord_remark']) {
            $request['ord_remark'] = '';
        }
        // 添加订单数据
        // 1. 添加订单表数据
        $ord_order_number = Common::orderRule($user_info);
        $ord_data['ord_cid'] = $user_info->adm_cid;
        $ord_data['ord_shop_id'] = $user_info->adm_shop_id;
        $ord_data['ord_superior_shop_id'] = $shop_id;
        $ord_data['ord_create_id'] = $user_info->adm_id;
        $ord_data['ord_wor_state'] = 7; //
        $ord_data['ord_client_id'] = $request['ord_client_id']; //选择客户id
        $ord_data['ord_order_number'] = $ord_order_number; //订单号
        //订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单 7救援单
        $ord_data['ord_service_type'] = $request['ord_service_type'];
        $ord_data['ord_payment_way'] = $request['ord_payment_way']; // 结算方式1.账期 2.现结 3微信 4支付宝
        $ord_data['ord_type'] = 5; // 买家类型：1门店零售2渠道单位3速电派单4第三方派单
        $ord_data['ord_remark'] = $request['ord_remark'] ? $request['ord_remark'] : ''; //订单备注
        $ord_data['ord_service_sepr_id'] = $request['service_sepr_id'] ? $request['service_sepr_id'] : 0; //服务项目id
        $ord_data['ord_service_shop_id'] = $request['service_shop_id']; //服务门店id
        $ord_unique_string = md5(md5($user_info->adm_id . $user_info->adm_shop_id . date('Y-m-d H:i:s') . rand(10000, 99999)) . rand(10000, 99999));
        $ord_data['ord_unique_string'] = $ord_unique_string; //门店订单唯一标识
        $ord_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_id = DB::table('order')->insertGetId($ord_data);
        // 救援单的服务项目金额
        $orcl_rescue_service_price = isset($request['orcl_rescue_service_price']) ? $request['orcl_rescue_service_price'] : 0;
        // 救援单的服务派单金额
        $orcl_rescue_assign_price = isset($request['orcl_rescue_assign_price']) ? $request['orcl_rescue_assign_price'] : 0;
        // 救援单的代收金额
        $orcl_rescue_collection_price = isset($request['orcl_rescue_collection_price']) ? $request['orcl_rescue_collection_price'] : 0;

        if ($request['ord_type'] == '2') {
            $chun_adm_id = DB::table('channel_unit')
                ->where('chun_id', $request['ord_client_id'])
                ->value('chun_adm_id');
            if (empty($chun_adm_id)) {
                $chun_adm_id = 0;
            }
        } else {
            $chun_adm_id = 0;
        }

        if (in_array($request['ord_service_type'], [1, 7])) {
            // 订单类型为服务单、救援单的有图片上传模板，根据订单类型，获取当前门店的图片上传模板
            $find_shit_id = DB::table('work_client')->where('wocl_id', $wocl_id)->value('wocl_shit_id');
            $orcl_data['orcl_shit_id'] = $find_shit_id; //图片模板id
        }

        // 添加订单客户表数据
        $orcl_data = [
            'orcl_ord_id' => $ord_id,
            'orcl_channel_unit' => isset($request['orcl_channel_unit']) ? $request['orcl_channel_unit'] : '',
            'orcl_adm_id' => $chun_adm_id, //业务员id
            'orcl_name' => $request['orcl_name'],
            'orcl_phone' => $request['orcl_phone'],
            'orcl_car_num' => isset($request['orcl_car_num']) && !empty($request['orcl_car_num']) ? $request['orcl_car_num'] : '',
            'orcl_car_vehicle_type' => isset($request['orcl_car_vehicle_type']) && !empty($request['orcl_car_vehicle_type']) ? $request['orcl_car_vehicle_type'] : '',
            'orcl_province' => $request['orcl_province'],
            'orcl_city' => $request['orcl_city'],
            'orcl_county' => $request['orcl_county'],
            'orcl_address' => $request['orcl_address'],
            'orcl_chin_type' => isset($request['chin_type']) ? $request['chin_type'] : 2, //铺货类型：1是铺货 2不是铺货
            'orcl_collect_state' => isset($request['orcl_collect_state']) ? $request['orcl_collect_state'] : 0,
            // 救援单的服务项目金额
            'orcl_rescue_service_price' => $orcl_rescue_assign_price * 100,
            // 救援单的代收金额
            'orcl_rescue_collection_price' => $orcl_rescue_collection_price * 100,
            'orcl_update_time' => date('Y-m-d H:i:s'),
            'orcl_join_wor_id' => $wocl_id, //运营中心工单id
            'orcl_order_type' => 5,
            'orcl_shipment_party' => 1,
            'orcl_junk_type' => isset($request['orcl_junk_type']) ? $request['orcl_junk_type'] : 2, //是否为旧货1是2否
            'orcl_shit_id' => $find_shit_id,
        ];
        $orcl_id = DB::table('order_client')->insertGetId($orcl_data);

        // 添加订单商品表数据
        $goo_all_quantity = 0; //商品总数量
        $goo_all_price = 0; //商品总金额
        $goo_collection_price = 0; //商品代收总金额
        $n = 0;
        $goo_state = 1; //商品状态
        // $sepr_order_money = 0;//服务项目的订单金额
        $recycle_all_price = 0; //订单回收金额
        $recycle_number = 0;
        $wor_recycle_price = 0;
        $wor_is_recycle = 2;
        $goo_all_assign_price = 0; //接单金额
        // 订单类型：7救援单，查询服务项目的订单金额
        if ($request['ord_service_type'] == 7) {
            // 没有添加商品数据
            if (empty($goods_data)) {
                // 4. 更改订单表客户id、订单金额
                $ord_edit_data['ord_orcl_id'] = $orcl_id;
                $ord_edit_data['ord_plus_minus'] = 1; //金额正负：1正值2负值
                $ord_edit_data['ord_order_price'] = $orcl_rescue_assign_price * 100; // 订单金额（单位：分）
                $ord_edit_data['ord_actual_price'] = $orcl_rescue_assign_price * 100; // 结算金额（单位：分）
                $ord_edit_data['ord_goods_quantity'] = 0; // 商品总数量
                $ord_edit_data['ord_collection_price'] = $orcl_rescue_collection_price * 100; //商品代收金额（单位：分）
                $ord_eidt_res = DB::table('order')
                    ->where('ord_id', $ord_id)
                    ->update($ord_edit_data);

                if ($ord_id && $orcl_id && $ord_eidt_res) {
                    return ['code'=>200, 'msg'=>'success', 'data'=>$ord_id];
                } else {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'门店生成订单失败'];
                }
            }
        }

        // 有商品数据
        foreach ($goods_data as $key => $value) {
            if (!isset($value['goo_assign_price'])) {
                $value['goo_assign_price'] = 0;
            }
            if (!isset($value['wago_id']) || !$value['wago_id']) {
                $value['wago_id'] = 0;
            }
            if (!is_numeric($value['wago_id']) || !is_numeric($value['goo_id']) || !in_array($value['goo_state'], [1, 3, 4, 5, 6, 7, 8]) || !is_numeric($value['goo_waon_class']) || !in_array($value['goo_inventory'], [1, 2])  || !is_numeric($value['goo_price']) || !is_numeric($value['goo_collection_price']) || !is_numeric($value['goo_assign_price']) || !is_numeric($value['goo_quantity'])) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'商品参数类型错误'];
            }
            // 搜索商品id对应的商品名称、商品编号
            $find_goods_data = DB::table('goods')
                ->where('goo_id', $value['goo_id'])
                ->select('goo_class', 'goo_name', 'goo_goods_encode', 'goo_type', 'goo_ampere_hour', 'goo_price', 'goo_fid')
                ->first();
            if ($find_goods_data->goo_class == 1) {
                // 自营商品查询匹配门店商品
                $shop_goods = DB::table('goods_correlation_system as a')
                    ->leftJoin('goods as g', 'g.goo_id', '=', 'a.goco_goo_id')
                    ->where('goco_shop_id', $shop_id)
                    ->where('goco_parent_goo_id', $value['goo_id'])
                    ->select('goo_type', 'goo_assign_price', 'goo_name', 'goo_state', 'goo_ampere_hour', 'goo_id', 'goo_bra_name', 'goo_cate_name', 'goo_bra_id', 'goo_goods_encode')
                    ->first();
                // 查询商品附属表
                $goaf_another_name = DB::table('goods_affiliate')
                    ->where('goaf_goo_id', $value['goo_id'])
                    ->where('goaf_shop_id', $user_info->adm_shop_id)
                    ->value('goaf_another_name');
                if (!empty($goaf_another_name)) {
                    $find_goods_data->goo_name = $goaf_another_name;
                }
            } else {
                // 系统商品查询当前门店是否设置系统价格
                $system_res = DB::table('goods_system_affiliate')
                    ->where('gosa_shop_id', $shop_id)
                    ->where('gosa_goo_id', $value['goo_id'])
                    ->select('gosa_assign_price', 'gosa_another_name')
                    ->first();
                if (!empty($system_res->gosa_another_name)) {
                    $find_goods_data->goo_name = $system_res->gosa_another_name;
                }
            }
            // goo_state 商品状态1.正常 2.删除3.回收的商品4.换货商品5.赠品商品6.备用电池7.临时商品8.旧货商品
            // 换货商品金额处理
            if ($value['goo_state'] == 1 || $value['goo_state'] == 5) {
                // 订单商品
                $goo_all_price += $value['goo_assign_price'] * $value['goo_quantity'];
                $goo_all_assign_price += $value['goo_assign_price'] * $value['goo_quantity'];
                $goo_all_quantity += $value['goo_quantity']; //商品总数量
                $goo_collection_price += $value['goo_collection_price'] * 100;
                $cost_price = 0;
                $sell_res = true;
            } elseif ($value['goo_state'] == 4) { //换货商品
                return ['code'=>500, 'msg'=>'success', 'data'=>'换货单生成订单失败'];
            } elseif ($value['goo_state'] == 6) { //备用电池
                if ($value['goo_inventory'] != '1' && $request['ord_service_type'] != 4) {
                    return ['code'=>500, 'msg'=>'success', 'data'=>'备用电池请选择备用品！'];
                }
                $goo_all_quantity += $value['goo_quantity']; //商品总数量
                $goo_all_price += $value['goo_assign_price'] * $value['goo_quantity'];
                $goo_collection_price += $value['goo_collection_price'] * 100;
            } elseif ($value['goo_state'] == 7) { //临时商品
                $goo_all_price += $value['goo_assign_price'] * $value['goo_quantity'];
                $goo_all_quantity += $value['goo_quantity']; //商品总数量
            } elseif ($value['goo_state'] == 8) { //旧货商品
                $goo_all_price += $value['goo_assign_price'] * $value['goo_quantity'];
                $goo_all_assign_price += $value['goo_assign_price'] * $value['goo_quantity'];
                $goo_all_quantity += $value['goo_quantity']; //商品总数量
                $goo_collection_price += $value['goo_collection_price'] * 100; //商品代收总金额
            }
            if ($request['orcl_shipment_party'] != 4 || $request['orcl_shipment_party'] != 5) {
                $request['ware_id'] =  0;
            }
            // 订单商品表
            $orgo_data[$key]['orgo_ord_id'] = $ord_id;
            $orgo_data[$key]['orgo_order_number'] = $ord_order_number;
            $orgo_data[$key]['orgo_ware_id'] = $request['ware_id'];
            $orgo_data[$key]['orgo_wago_id'] = $value['wago_id'];
            $orgo_data[$key]['orgo_waon_class'] = $value['goo_waon_class'];
            $orgo_data[$key]['orgo_actual_goo_id'] = $find_goods_data->goo_class == 1 ? $shop_goods->goo_id : $value['goo_id'];
            $orgo_data[$key]['orgo_goo_id'] = $find_goods_data->goo_class == 1 ? $shop_goods->goo_id : $value['goo_id'];
            $orgo_data[$key]['orgo_goo_price'] = $value['goo_assign_price'] * 100;
            $orgo_data[$key]['orgo_goo_quantity'] = $value['goo_quantity'];
            $orgo_data[$key]['orgo_can_assign_quantity'] = $value['goo_quantity'];
            $orgo_data[$key]['orgo_collection_price'] = $value['goo_collection_price'] * 100;
            $orgo_data[$key]['orgo_goo_inventory'] = 0;
            $orgo_data[$key]['orgo_update_time'] = date('Y-m-d H:i:s');
            if (!empty($value['tem_goo_name'])) {
                $orgo_data[$key]['orgo_tem_goo_name'] = $value['tem_goo_name'];
            } else {
                $orgo_data[$key]['orgo_tem_goo_name'] = '';
            }
            $orgo_data[$key]['orgo_goo_name'] = $find_goods_data->goo_class == 1 ? $shop_goods->goo_name : $find_goods_data->goo_name;
            $orgo_data[$key]['orgo_goo_goods_encode'] = $find_goods_data->goo_class == 1 ? $shop_goods->goo_goods_encode : $find_goods_data->goo_goods_encode;
            $orgo_data[$key]['orgo_goo_type'] = $find_goods_data->goo_class == 1 ? $shop_goods->goo_type : $find_goods_data->goo_type;
            $orgo_data[$key]['orgo_goo_ampere_hour'] = $find_goods_data->goo_class == 1 ? $shop_goods->goo_ampere_hour : $find_goods_data->goo_ampere_hour;
            $orgo_data[$key]['orgo_state'] = $value['goo_state'];

            $orgo_data[$key]['orgo_assign_price'] = $value['goo_assign_price'];
        }
        $goo_all_price = $goo_all_price + $orcl_rescue_assign_price * 100; //合计金额=商品总金额+服务项目的订单金额
        $goo_all_price = $goo_all_price - $recycle_all_price * 100;
        if ($goo_all_price < 0 || $request['ord_service_type'] == 4) {
            // 金额小于0，或者退货单类型，金额为负
            $ord_edit_data['ord_plus_minus'] = 2; //金额正负：1正值2负值
        } else {
            $ord_edit_data['ord_plus_minus'] = 1; //金额正负：1正值2负值
        }
        // 外派工单
        $goo_all_assign_price = $goo_all_assign_price + $orcl_rescue_assign_price; //合计金额=商品总金额+服务项目的订单金额
        $goo_all_assign_price = $goo_all_assign_price - $recycle_all_price;
        if ($goo_all_assign_price < 0 || $request['ord_service_type'] == 4) {
            // 金额小于0，或者退货单类型，金额为负
            $wocl_data['wocl_plus_minus'] = 2; //金额正负：1正值2负值
            $ord_edit_data['orcl_plus_minus'] = 2; //金额正负：1正值2负值
        } else {
            $wocl_data['wocl_plus_minus'] = 1; //金额正负：1正值2负值
            $ord_edit_data['orcl_plus_minus'] = 1; //金额正负：1正值2负值
        }
        $orgo_res = DB::table('order_goods')->insert($orgo_data);

        // 4. 更改订单表客户id、订单金额
        $ord_edit_data['ord_orcl_id'] = $orcl_id;
        $ord_edit_data['ord_order_price'] = abs($goo_all_assign_price) * 100; // 订单金额（单位：分）
        $ord_edit_data['ord_actual_price'] = abs($goo_all_assign_price) * 100; // 结算金额（单位：分）
        $ord_edit_data['ord_goods_quantity'] = $goo_all_quantity; // 商品总数量
        $ord_edit_data['ord_collection_price'] = ($goo_collection_price + $orcl_rescue_collection_price * 100); //商品代收金额（单位：分）
        $ord_edit_data['orcl_assign_price'] = abs($goo_all_assign_price) * 100; //派单金额（单位：分）

        if (isset($request['assignment']) && $request['assignment'] == 1) {
            $ord_edit_data['ord_wor_quantity'] = 1;
        }
        $ord_eidt_res = DB::table('order as ord')
            ->leftjoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
            ->where('ord_id', $ord_id)
            ->update($ord_edit_data);

        if ($ord_id && $orgo_res  && $orcl_id && $ord_eidt_res) {
            return ['code'=>200, 'msg'=>'success', 'data'=>$ord_id];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'生成门店订单失败'];
        }
    }

    // 搜索服务门店
    public function searchShop(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $search_data = $request->all();
        $list_data = DB::table('shop')
            ->where('shop_cid', $user_info->adm_cid)
            ->where('shop_superior_id', $user_info->adm_shop_id)
            ->where('shop_state', 1)
            ->where('shop_type', '!=', 3)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['shop_store_name'])) {
                    $query->where('shop_store_name', 'like', '%' . $search_data['shop_store_name'] . '%');
                }
            })
            ->select('shop_id', 'shop_store_name')
            ->orderBy('shop_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 searchGoods(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyCashierDeskController;
        $error_message = $verify_data->searchGoodsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        if (!isset($request['goo_type']) || !in_array($request['goo_type'], [1, 2])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品类型错误']);
        }

        // 获取当前操作账号信息
        $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('goods')
            ->where('goo_cid', $user_info->adm_cid)
            ->where('goo_shop_id', $shop_id)
            ->where('goo_type', $request['goo_type'])
            ->where('goo_delete', 1)
            ->where('goo_state', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_name'])) {
                    $query->where('goo_name', 'like', '%' . $search_data['goo_name'] . '%')
                        ->orwhere('goo_goods_encode', 'like', '%' . $search_data['goo_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_bra_id'])) {
                    $query->where('goo_bra_id', $search_data['goo_bra_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_cate_id'])) {
                    $query->where('goo_cate_id', $search_data['goo_cate_id']);
                }
            })
            ->select('goo_id', 'goo_type', 'goo_name', 'goo_goods_encode', 'goo_price', 'goo_ampere_hour', 'goo_bra_name', 'goo_class')
            ->orderBy('goo_goods_encode', 'asc')
            ->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();                //返回数据
        $goods_data = $list_data->items();
        // 客户单位设置价格替换
        $list_chgoo_data = DB::table('channel_unit_goods_correlation')
            ->where('cugc_shop_id', $shop_id)
            ->where('cugc_chun_id', $request['chun_id'])
            ->select('cugc_goo_id', 'cugc_set_goo_price')
            ->get();
        $goo_id = array_column($goods_data, 'goo_id');
        // 查询商品附属表信息
        $goaf_data = DB::table('goods_affiliate')
            ->where('goaf_shop_id', $user_info->adm_shop_id)
            ->whereIn('goaf_goo_id', $goo_id)
            ->pluck('goaf_another_name', 'goaf_goo_id')
            ->toArray();
        // 查询系统商品属性表信息
        $gosa_data = DB::table('goods_system_affiliate')
            ->where('gosa_shop_id', $user_info->adm_shop_id)
            ->whereIn('gosa_goo_id', $goo_id)
            ->pluck('gosa_another_name', 'gosa_goo_id')
            ->toArray();
        if (!empty($list_chgoo_data)) {
            // 系统商品替换价格
            $list_chgoo_data = json_decode(json_encode($list_chgoo_data, true), true);
            foreach ($goods_data as $k => $v) {
                foreach ($list_chgoo_data as $chgookey => $chgooval) {
                    if ($chgooval['cugc_goo_id'] == $v->goo_id) {
                        $goods_data[$k]->goo_price = $chgooval['cugc_set_goo_price'];
                    }
                }
            }
        }

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

    // 获取商品库存数量
    public function goodsStock(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyCashierDeskController;
        $error_message = $verify_data->goodsStockValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $list_data = DB::table('warehouse_goods')
            ->where('wago_ware_id', $request['ware_id'])
            ->where('wago_goo_id', $request['goo_id'])
            ->first(['wago_stock_number', 'wago_priority_stock_number']);
        $data['wago_stock_number'] = $list_data ? $list_data->wago_stock_number : 0;
        $data['wago_priority_stock_number'] = $list_data ? $list_data->wago_priority_stock_number : 0;
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }

    // 获取商品库存信息
    public function getGoodsStock(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyCashierDeskController;
        $error_message = $verify_data->searchGoodsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        if (isset($request['show_count']) && !empty($request['show_count'])) {
            $show_count = $request['show_count'];
        } else {
            $show_count = $this->show_count;
        }
        // 获取当前操作账号信息
        $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;
        $ware_id = [];
        // 判断是否传仓库id
        if ($request['ware_id']) {
            $ware_id[] = $request['ware_id'];
        }/* else {
            // 获取到该账号下勾选的服务门店id
            $ware_id = DB::table('admin_set')
                ->where('adms_adm_id', $user_info->adm_id)
                ->value('adms_ware_id');
            if (empty($ware_id)) {
                $ware_id = [];
            } else {
                $ware_id = explode(',', $ware_id);
            }
        }*/

        $shop_state = true;
        if (in_array($shop_id, config('apisystem.NO_SHOPID'))) {
            $shop_state = false;
        }
        $post['string'] = 'goo_';
        $post['user_info'] = $user_info;
        $type = 3;
        $where_data = whereFunction($post,$type);

        $search_data = $request->all();
        $list_data = DB::table('goods as g')
            ->leftjoin('warehouse_goods as wg', 'wg.wago_goo_id', '=', 'g.goo_id')
            ->leftjoin('warehouse as w', 'w.ware_id', '=', 'wg.wago_ware_id')
            ->where(function ($query) use ($user_info, $shop_state) {
                if ($shop_state) {
                    $query->where('goo_cid', 0)
                        ->orwhere('goo_cid', $user_info->adm_cid);
                } else {
                    $query->where('goo_cid', $user_info->adm_cid);
                }
            })
            ->where(function ($query) use ($user_info, $where_data) {
                $query->whereIn($where_data['string'], $where_data['shop_id']);
            })
            ->where('goo_delete', 1)
            ->where('goo_state', 1)
            ->where('goo_type', 1)
            // ->where('ware_state', 1)
            ->where(function ($query) use ($ware_id) {
                if (!empty($ware_id)) {
                    $query->whereIn('wago_ware_id', $ware_id)
                        ->where('ware_state', 1);
                }
            })
            // ->whereIn('wago_ware_id', $ware_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_name'])) {
                    $query->where('goo_name', 'like', '%' . $search_data['goo_name'] . '%')
                        ->orwhere('goo_goods_encode', 'like', '%' . $search_data['goo_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data, $ware_id) {
                if (!empty($search_data['waon_class']) && $ware_id) {
                    $query->where('wago_class', $search_data['waon_class']);
                }
            }) //仓库类别
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_type'])) {
                    $query->where('goo_type', $search_data['goo_type']);
                }
            }) //商品类型
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_bra_id'])) {
                    $query->where('goo_bra_id', $search_data['goo_bra_id']);
                }
            }) //品牌
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_cate_id'])) {
                    $query->where('goo_cate_id', $search_data['goo_cate_id']);
                }
            }) //品类
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_brse_id'])) {
                    $query->where('goo_brse_id', $search_data['goo_brse_id']);
                }
            }) //品牌系列id
            ->select('goo_class', 'goo_id', 'goo_name', 'goo_type', 'goo_goods_encode', 'goo_wholesale_price as goo_price', 'goo_ampere_hour', 'goo_brse_id', 'goo_bra_name', 'goo_unta_id', 'goo_unit', 'goo_unit_conversion', 'goo_level', 'goo_fid')
            ->orderBy('goo_id', 'desc')
            // ->orderBy('goo_goods_encode', 'asc')
            ->groupBy('goo_id')
            ->paginate($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;       //一页显示多少个

        $goods_data = $list_data->items();
        //计算会员价格 20231124  pc会员价格下单暂时屏蔽
        /*$meml_discount = 0;
        if(isset($search_data['mem_id'])){
            $level = DB::table('member')
                ->where('mem_shop_id', $user_info->adm_shop_id)
                ->where('mem_id', $search_data['mem_id'])
                ->value('mem_level');
            if($level == 5){
                $meml_discount = DB::table('member_level')
                    ->where('meml_shop_id', $user_info->adm_shop_id)
                    ->where('meml_level', 5)
                    ->value('meml_discount');
            }
        }
        if ($goods_data) {
            foreach ($goods_data as $key => $value) {
                $goods_data[$key]->mem_price = $value->goo_price;
                if($meml_discount > 0){
                    $goods_data[$key]->mem_price = $value->goo_price * $meml_discount / 10;
                }
            }
        }*/
        if ($goods_data) {
            foreach ($goods_data as $k => $v) {
                if ($v->goo_level == 1 || ($v->goo_level ==2 && $v->goo_fid)) {
                    $goods_data[$k]->goo_change = 1;
                } else {
                    $goods_data[$k]->goo_change = 2;
                }
            }
        }
        $data_info['goods_data'] = $goods_data;
        $data_info['brse_data'] = []; //品牌系列数据
        if ($data_info['goods_data']) {
            $goo_id = array_column($goods_data, 'goo_id');
            foreach ($goods_data as $k => $v) {
                $goods_data[$k]->new_goo_unit = $v->goo_unit;
                if (isset($request['search_admin_id']) && !empty($request['search_admin_id'])) {
                    $goods_performance = DB::table('goods_performance')
                        ->where('gppe_goo_id', $v->goo_id)
                        ->where('gppe_type',1)//类型1商品2服务
                        ->where('gppe_sale_id',$request['search_admin_id'])
                        ->value('gppe_performance');
                    $goods_data[$k]->gppe_performance = $goods_performance??0;
                }
            }

            // 判断是否传仓库id
            if ($request['ware_id']) {
                $ware_id[] = $request['ware_id'];
            }/* else {
                // 获取到该账号下勾选的服务门店id
                $ware_id = DB::table('admin_set')
                    ->where('adms_adm_id', $user_info->adm_id)
                    ->value('adms_ware_id');
                if (empty($ware_id)) {
                    $ware_id = [];
                } else {
                    $ware_id = explode(',', $ware_id);
                }
            }*/

            if ($ware_id) {
                // 仓库商品表数据
                $stock_data = DB::table('warehouse as a')
                    ->leftJoin('warehouse_goods as b', 'b.wago_ware_id', '=', 'a.ware_id')
                    ->where('ware_superior_shop_id', $shop_id)
                    ->where('ware_state', 1) //  状态1启用2停用3撤仓
                    ->where(function ($query) use ($search_data) {
                        if (!empty($search_data['waon_class'])) {
                            $query->where('wago_class', $search_data['waon_class']);
                        }
                    }) //商品编码
                    ->whereIn('ware_id', $ware_id)
                    ->whereIn('wago_goo_id', $goo_id)
                    ->select('wago_id', 'wago_goo_id', 'ware_id', 'ware_name', 'wago_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity')
                    ->orderBy('wago_stock_number', 'desc')
                    ->get()->toArray();
                $data_info['stock_data'] = $stock_data;
            } else {
                $data_info['stock_data'] = '';
            }
            // 查询品牌系列数据
            $goo_brse_id = array_filter(array_unique(array_column($data_info['goods_data'], 'goo_brse_id')));
            if ($goo_brse_id) {
                $data_info['brse_data'] = DB::table('brand_serie')
                    ->whereIn('brse_id', $goo_brse_id)
                    ->select('brse_id', 'brse_name')
                    ->get();
            }
        } else {
            $data_info['stock_data'] = '';
        }

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

    // 工作台-搜索会员-车辆信息
    public function searchMember(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $shop_id = $user_info->adm_shop_id;
        $post['string'] = 'mem_';
        $post['user_info'] = $user_info;
        $type = 1;
        $where_data = whereFunction($post,$type);
        $search_data = $request->all();
        if (empty($search_data['search_data'])) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>[]]);
        }
        $list = DB::table('member')
            ->where([
                'mem_cid' => $user_info->adm_cid
            ])
            ->whereIn($where_data['string'], $where_data['shop_id'])
            ->where('mem_state', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('mem_name', $search_data['search_data'])
                        ->orwhere('mem_phone', $search_data['search_data']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['mem_id'])) {
                    $query->where('mem_id', $search_data['mem_id']);
                }
            })
            ->select('mem_id', 'mem_name', 'mem_phone', 'mem_province', 'mem_city', 'mem_county', 'mem_address', 'mem_bership', 'mem_car_num', 'mem_source', 'mem_car_series', 'mem_sex', 'mem_birthday', 'mem_rec_banlance', 'mem_gift_banlance', 'mem_level', 'mem_salesman_id', 'mem_4sname')
            ->paginate(30);
        $data = $list->items();
        //查找折扣
        $level_id = array_column($data, 'mem_level'); //等级id
        $level_id = array_unique($level_id);
        $level_list = DB::table('member_level')
            ->where([
                'meml_cid' => $user_info->adm_cid,
                'meml_shop_id' => $shop_id
            ])
            ->whereIn('meml_level',$level_id)
            ->get()->toArray();
        if(!empty($level_list)){
            foreach ($level_list as $l_key => $l_value){
                $level_data[$l_value->meml_level] = $l_value->meml_discount;
            }
        }
        foreach ($data as $key => $value) {
            $data[$key]->mem_banlance = $value->mem_rec_banlance + $value->mem_gift_banlance;
            $data[$key]->mem_salesman_name = DB::table('admin')->where('adm_id', $value->mem_salesman_id)->value('adm_name');
            if($value->mem_level > 0 && isset($level_data[$value->mem_level])){
                $data[$key]->mem_discount = $level_data[$value->mem_level];
            }else{
                $data[$key]->mem_discount = '';
            }
        }

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

    // 工作台-搜索企业客户-账户
    public function searchBusinessacc(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $shop_id = $user_info->adm_shop_id;

        $search_data = $request->all();
        if (empty($search_data['search_data'])) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>[]]);
        }
        $list = DB::table('business_client as bucl')
            ->leftjoin('business_account as buac', 'buac.buac_bucl_id', '=', 'bucl_id')
            ->where([
                'bucl_cid' => $user_info->adm_cid,
                'bucl_shop_id' => $shop_id
            ])
            ->where('buac_del', 1)
            ->where('bucl_del', 1)
            ->where('bucl_state', 1)
            ->where('buac_state', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('buac_name',  $search_data['search_data'])
                        ->orwhere('buac_phone',  $search_data['search_data']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['bucl_id'])) {
                    $query->where('bucl_id', $search_data['bucl_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['buac_id'])) {
                    $query->where('buac_id', $search_data['buac_id']);
                }
            })
            ->select('buac_id', 'buac_name', 'buac_phone', 'bucl_name', 'bucl_id', 'bucl_province', 'bucl_city', 'bucl_county', 'bucl_address', 'bucl_rec_banlance', 'bucl_gift_banlance')
            ->paginate(30);
        $list_items = $list->items();
        foreach ($list_items as $key => $value) {
            $list_items[$key]->mem_banlance = $value->bucl_rec_banlance + $value->bucl_gift_banlance;
            if (empty($list_items[$key]->mem_banlance)) {
                $list_items[$key]->mem_banlance = 0;
            }
        }
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_items]);
    }

    // 工作台-搜索企业客户
    public function searchBusiness(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $shop_id = $user_info->adm_shop_id;

        $search_data = $request->all();
        $shop = DB::table('shop')
            ->where('shop_id', $shop_id)
            ->where('shop_cid', $user_info->adm_cid)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('shop_store_name', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->select('shop_id as bucl_id', 'shop_store_name as bucl_name')
            ->get()->toArray();
        $list = DB::table('business_client as bucl')
            ->where([
                'bucl_cid' => $user_info->adm_cid,
                'bucl_shop_id' => $shop_id
            ])
            ->where('bucl_del', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('bucl_name', 'like', '%' . $search_data['search_data'] . '%')
                    ->orwhere('bucl_user_phone', 'like', '%' . $search_data['search_data'] . '%')
                    ->orwhere('bucl_user_name', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->select('bucl_id', 'bucl_user_phone', 'bucl_user_name', 'bucl_name', 'bucl_province', 'bucl_city', 'bucl_county', 'bucl_address')
            ->paginate(30);
        if ($shop) {
            $shop[0]->id = $shop[0]->bucl_id."-1";
            $shop[0]->address_type = 1;
            $shop[0]->bucl_name = $shop[0]->bucl_name.'(本店)';
        }
        $list_data = $list->items();
        foreach ($list_data as $key => $value) {
            $list_data[$key]->id = $value->bucl_id."-2";
            $list_data[$key]->address_type = 2;
        }
        $shop = json_decode(json_encode($shop, true), true);
        $list_data = json_decode(json_encode($list_data, true), true);
        $new_list = array_merge($shop, $list_data);
        // $bind_shop = DB::table('bind_shop')
        //     ->leftJoin('shop', 'shop_id', '=', 'bish_lshop_id')
        //     ->where('bish_fshop_id', $shop_id)
        //     ->select('shop_id as bucl_id', 'shop_store_name as bucl_name')
        //     ->get()->toArray();
        // if ($bind_shop) {
        //     foreach ($bind_shop as $key => $value) {
        //         $bind_shop[$key]->id = $value->bucl_id."-3";
        //         $bind_shop[$key]->address_type = 3;
        //     }
        //     $bind_shop = json_decode(json_encode($bind_shop, true), true);
        //     $new_list = array_merge($shop, $bind_shop);
        // }

        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$new_list]);
    }

    // 工作台-搜索企业客户/门店名称
    public function searchAllBusiness(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if ($user_info->shop_superior_id) {
            // 总店id
            $shop_id = $user_info->shop_superior_id;
        } else {
            $shop_id = $user_info->adm_shop_id;
        }

        $search_data = $request->all();
        $list = DB::table('business_client as bucl')
            ->where([
                'bucl_cid' => $user_info->adm_cid,
                'bucl_shop_id' => $shop_id
            ])
            ->where('bucl_del', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('bucl_name', 'like', '%' . $search_data['search_data'] . '%')
                    ->orwhere('bucl_user_phone', 'like', '%' . $search_data['search_data'] . '%')
                    ->orwhere('bucl_user_name', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->select('bucl_id', 'bucl_name', 'bucl_province')
            ->get()->toArray();
        $shop = DB::table('shop')
            ->where('shop_id', $shop_id)
            ->select('shop_id', 'shop_store_name')
            ->first();
        $new_list = [];
        if ($shop) {
            $new_list[0]['name'] = $shop->shop_store_name;
            $new_list[0]['id'] = $shop->shop_id;
            $new_list[0]['type'] = 1;
            $i = 1;
        } else {
            $i = 0;
        }
        
        foreach ($list as $key => $value) {
            $new_list[$i]['name'] = $value->bucl_name;
            $new_list[$i]['id'] = $value->bucl_id;
            $new_list[$i]['type'] = 2;
            $i++;
        }
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$new_list]);
    }

    // 获取会员车辆信息
    public function getMemberCar(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyCashierDeskController;
        $error_message = $verify_data->getMemberCarValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if ($user_info->shop_superior_id) {
            // 总店id
            $shop_id = $user_info->shop_superior_id;
        } else {
            $shop_id = $user_info->adm_shop_id;
        }

        $search_data = $request->all();
        $list = DB::table('member_car')
            ->where([
                'meca_cid' => $user_info->adm_cid,
                'meca_shop_id' => $shop_id,
                'meca_mem_id' => $request['mem_id']
            ])
            ->select('meca_car_num', 'meca_car_model')
            ->orderBy('meca_update_time', 'desc')
            ->first();
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list]);
    }

    // 搜索会员车辆信息
    public function searchMemberCar(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyCashierDeskController;
        $error_message = $verify_data->getMemberCarValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if ($user_info->shop_superior_id) {
            // 总店id
            $shop_id = $user_info->shop_superior_id;
        } else {
            $shop_id = $user_info->adm_shop_id;
        }

        $search_data = $request->all();
        $list = DB::table('member_car')
            ->where([
                'meca_cid' => $user_info->adm_cid,
                'meca_shop_id' => $shop_id,
                'meca_mem_id' => $request['mem_id']
            ])
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('meca_car_num', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->select('meca_car_num')
            ->paginate(10);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list->items()]);
    }

    // 搜索会员-其他地方搜索使用
    public function getMember(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $search_data = $request->all();

        $list = DB::table('member')
            ->where([
                'mem_cid' => $user_info->adm_cid,
                'mem_shop_id' => $user_info->adm_shop_id
            ])
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('mem_name', 'like', '%' . $search_data['search_data'] . '%')
                        ->orwhere('mem_phone', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->get(['mem_id', 'mem_name', 'mem_phone']);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list]);
    }

    // 搜索客户单位
    public function searchChannelUnit(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $search_data = $request->all();

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

        $list = DB::table('channel_unit as u')
            ->leftJoin('channel_info as i', 'i.chin_chun_id', '=', 'u.chun_id')
            ->where([
                'chun_cid' => $user_info->adm_cid,
                'chun_superior_shop_id' => $shop_id,
                'chun_state' => 1
            ])
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['chun_chty_id'])) {
                    $query->where('chun_chty_id', $search_data['chun_chty_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('chun_phone', 'like', '%' . $search_data['search_data'] . '%')
                        ->orwhere('chun_unit_name', 'like', '%' . $search_data['search_data'] . '%')
                        ->orwhere('chun_name', 'like', '%' . $search_data['search_data'] . '%')
                        ->orwhere('chun_search_letter', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->select('chun_id', 'chun_unit_name', 'chun_name', 'chun_phone', 'chun_province', 'chun_city', 'chun_county', 'chun_address', 'chun_payment_way', 'chin_level', 'chin_main_brand', 'chin_second_brand', 'chin_owe_day', 'chin_owe_money', 'chin_caution_day', 'chin_type', 'chin_longitude', 'chin_latitude', 'chin_remarks')
            ->paginate($this->show_count);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list->items()]);
    }

    // 搜索服务项目
    public function searchProject(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 搜索服务项目
        $public_search = new PublicSearch;
        $list_data = $public_search->searchProject($user_info, $request->all());
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_data['data']]);
    }

    // 搜索供货仓库
    public function searchWarehouse(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyCashierDeskController;
        $error_message = $verify_data->searchTechnicianValidator($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();
        if ($search_data['shop_id']) {
            $shop_id = $search_data['shop_id'];
        } else {
            $shop_id = $user_info->adm_shop_id;
        }

        $list = DB::table('warehouse as w')
            ->leftJoin('admin as a', 'a.adm_id', '=', 'w.ware_leader_id')
            ->where([
                'ware_cid' => $user_info->adm_cid,
                'ware_shop_id' => $shop_id,
                'ware_state' => 1,
            ])
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('ware_name', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ware_type'])) {
                    $query->where('ware_type', '=', 1);
                }
            })
            // ->get(['ware_id','ware_type','adm_work_state','ware_default','ware_name']);
            ->get(['ware_id', 'ware_type', 'ware_default', 'ware_name']);
        // $data = array();
        // foreach ($list as $key => $value) {
        //     if ($value->ware_type == 2) {
        //         // 移动仓，过滤以下班的仓库
        //         if ($value->adm_work_state == 2) {
        //             $data[$key]['ware_id'] = $value->ware_id;
        //             $data[$key]['ware_default'] = $value->ware_default;
        //             $data[$key]['ware_name'] = $value->ware_name;
        //         }
        //     }else{
        //         $data[$key]['ware_id'] = $value->ware_id;
        //         $data[$key]['ware_default'] = $value->ware_default;
        //         $data[$key]['ware_name'] = $value->ware_name;
        //     }
        // }
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list]);
    }

    // 搜索服务技师
    public function searchTechnician(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyCashierDeskController;
        $error_message = $verify_data->searchTechnicianValidator($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();
        if ($search_data['shop_id']) {
            $shop_id = $search_data['shop_id'];
        } else {
            $shop_id = $user_info->adm_shop_id;
        }

        $list = DB::table('admin')
            ->where('adm_cid', $user_info->adm_cid)
            ->where('adm_shop_id', $shop_id)
            ->where('adm_state', 1)
            ->where('adm_work_state', 2)
            ->whereIn('adm_leave', [3, 5])
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('adm_name', 'like', '%' . $search_data['search_data'] . '%')
                        ->orwhere('adm_phone', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->get(['adm_id', 'adm_name', 'adm_phone']);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list]);
    }

    // 搜索技师定位数据
    public function searchLocation(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyCashierDeskController;
        $error_message = $verify_data->searchLocationValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        /* if ($request['shop_id']) {
            $shop_id = $request['shop_id'];
        } else {
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            $shop_id = $user_info->adm_shop_id;
        } */
        //使用此函数计算得到结果后，带入sql查询
        // $point = $this->roundness(117.0046793920,39.4251679868);   //计算经纬度的周围某段距离的正方形的四个点(国际企业社区的位置)
        // $point = $this->roundness($request['longitude'], $request['latitude']);   //计算经纬度的周围某段距离的正方形的四个点(国际企业社区的位置)

        // $right_bottom_lng = $point['right_bottom']['lng']; //右下经度
        // $right_bottom_lat = $point['right_bottom']['lat']; //右下纬度
        // $left_top_lat = $point['left_top']['lat']; //左上纬度
        // $left_top_lng = $point['left_top']['lng'];  //左上经度

        $work = DB::table('work_order as wo')
            ->leftjoin('work_client as wc', 'wc.wocl_wor_id', '=', 'wo.wor_id')
            ->where('wor_id', $request['wor_id'])
            ->first(['wocl_wor_type', 'wor_service_shop_id']);
        if (!empty($work) && $work->wocl_wor_type == 4) {
            $arr_adm = DB::table('virtual_adm')
                ->where(function ($query) use ($request, $work) {
                    if (!empty($request['service_shop_id'])) {
                        $query->where('viad_vish_id', $request['service_shop_id']);
                    } else {
                        $query->where('viad_vish_id', $work->wor_service_shop_id);
                    }
                })
                ->pluck('viad_adm_id', 'viad_id');
            $adm_type = [];
        } else {
            $adm_type = [1, 3];
            $arr_adm = [];
        }

        $search_data = $request->all();
        // 查询门店下技师的当前的定位信息
        $list_data = DB::table('lat as l')
            ->leftJoin('admin as a', 'a.adm_id', '=', 'l.lat_aid')
            ->where('adm_state', 1)
            ->where('lat_shop_id', $request['shop_id'])
            ->where('lat_work_state', 2)
            // ->where('lat_time', '>=', date('Y-m-d H:i:s', strtotime('-30 Minute')))
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('adm_name', 'like', '%' . $search_data['search_data'] . '%')
                        ->orwhere('adm_phone', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->where(function ($query) use ($arr_adm) {
                if (!empty($arr_adm)) {
                    $query->whereIn('adm_id', $arr_adm);
                }
            })
            ->where(function ($query) use ($adm_type) {
                if (!empty($adm_type)) {
                    $query->whereIn('adm_type', $adm_type);
                }
            })
            // ->where('lat_lon','<',$right_bottom_lng)
            // ->where('lat_lat','>',$right_bottom_lat)
            // ->where('lat_lat','<',$left_top_lat)
            // ->where('lat_lon','>',$left_top_lng)
            ->get(['lat_id', 'lat_lat', 'lat_lon', 'lat_aid', 'lat_ord_state', 'lat_work_state', 'lat_ord_id', 'lat_time', 'adm_name', 'adm_phone']);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_data]);
    }

    /**
     * [roundness 计算某个经纬度的周围某段距离的正方形的四个点]
     * @param  [float]  $lng      [经度]
     * @param  [float]  $lat      [纬度]
     * @param  integer $distance [该点所在圆的半径，该圆与此正方形内切，默认值为5千米]
     * @return [array]            [正方形的四个点的经纬度坐标]
     */
    private function roundness($lng, $lat, $distance = 5)
    {
        error_reporting(0);
        $earthdata = 6371; //地球半径，平均半径为6371km
        $dlng = 2 * asin(sin($distance / (2 * $earthdata)) / cos(deg2rad($lat)));
        $dlng = rad2deg($dlng);
        $dlat = $distance / $earthdata;
        $dlat = rad2deg($dlat);
        $arr = [
            'left_top'     => ['lat' => $lat + $dlat, 'lng' => $lng - $dlng], //西北
            'right_top'    => ['lat' => $lat + $dlat, 'lng' => $lng + $dlng], //东北
            'left_bottom'  => ['lat' => $lat - $dlat, 'lng' => $lng - $dlng], //西南
            'right_bottom' => ['lat' => $lat - $dlat, 'lng' => $lng + $dlng]  //东南
        ];

        return $arr;
    }

    // 搜索移动仓数据
    public function searchMobileSilo(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyCashierDeskController;
        $error_message = $verify_data->searchMobileSiloValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $wor_type = DB::table('work_client')->where('wocl_wor_id', $request['wor_id'])->value('wocl_wor_type');
        //虚拟加盟店
        if ($wor_type == 4) {
            // 查询技师所在的仓库信息
            $ware_data = DB::table('admin')
                ->where('adm_id', $request['adm_id'])
                ->select('adm_name', 'adm_phone')
                ->first();
            $ware_data->ware_id = 0;
            $ware_data->ware_name = 0;
        } else {
            // 查询技师所在的仓库信息
            $ware_data = DB::table('warehouse as a')
                ->leftJoin('admin as c', 'c.adm_id', '=', 'a.ware_leader_id')
                ->where('ware_leader_id', $request['adm_id'])
                ->where('ware_type', 2)
                ->select('ware_id', 'ware_name', 'adm_name', 'adm_phone')
                ->first();
            if (empty($ware_data)) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前技师暂未绑定移动仓']);
            }
        }

        // 查询仓库的商品信息
        $goods_data = DB::table('warehouse_goods as a')
            ->leftJoin('goods as c', 'c.goo_id', '=', 'a.wago_goo_id')
            ->where('wago_ware_id', $ware_data->ware_id)
            ->get(['goo_name', 'goo_goods_encode', 'wago_stock_number', 'goo_class', 'goo_id'])->toArray();
        $goo_id = array_column($goods_data, 'goo_id');
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 查询商品附属表信息
        $goaf_data = DB::table('goods_affiliate')
            ->where('goaf_shop_id', $user_info->adm_shop_id)
            ->whereIn('goaf_goo_id', $goo_id)
            ->pluck('goaf_another_name', 'goaf_goo_id')
            ->toArray();
        // 查询系统商品属性表信息
        $gosa_data = DB::table('goods_system_affiliate')
            ->where('gosa_shop_id', $user_info->adm_shop_id)
            ->whereIn('gosa_goo_id', $goo_id)
            ->pluck('gosa_another_name', 'gosa_goo_id')
            ->toArray();
        foreach ($goods_data as $key => $value) {
            if ($value->goo_class == 2 && isset($gosa_data[$value->goo_id]) && !empty($gosa_data[$value->goo_id])) {
                $goods_data[$key]->goo_name = $gosa_data[$value->goo_id];
            }
            if (isset($goaf_data[$value->goo_id]) && !empty($goaf_data[$value->goo_id])) { // 商品别名
                $goods_data[$key]->goo_name = $goaf_data[$value->goo_id];
            }
            unset($goods_data[$key]->goo_id);
            unset($goods_data[$key]->goo_class);
        }
        $data['ware_data'] = $ware_data;
        $data['goods_data'] = $goods_data;
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }

    // 搜索服务技师--控制器
    public function getTechnician(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyCashierDeskController;
        $error_message = $verify_data->getTechnicianValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $find_adm = DB::table('warehouse as w')
            ->leftJoin('admin as a', 'w.ware_leader_id', '=', 'a.adm_id')
            ->where('ware_id', $request['ware_id'])
            ->where('ware_type', 2)
            ->first(['adm_id', 'adm_name']);

        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$find_adm]);
    }

    // 搜索供货仓库--控制器
    public function searchWare(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyCashierDeskController;
        $error_message = $verify_data->searchWareValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $find_ware = DB::table('warehouse')
            ->where('ware_leader_id', $request['adm_id'])
            ->where('ware_type', 2)
            ->select('ware_id', 'ware_name', 'ware_type')
            ->first();

        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$find_ware]);
    }

    // 扫码搜索-根据商品编码搜索商品
    public function searchGoodsEncode(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyCashierDeskController;
        $error_message = $verify_data->searchGoodsEncodeValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $user_info = Common::getUserInfo($request['api_token']);
        $find_goods_data = DB::table('goods')
            ->where('goo_cid', $user_info->adm_cid)
            ->where('goo_shop_id', $user_info->adm_shop_id)
            ->where('goo_state', 1)
            ->where('goo_delete', 1)
            ->where('goo_goods_encode', $request['goo_goods_encode'])
            ->select('goo_id', 'goo_name', 'goo_goods_encode', 'goo_price')
            ->get();

        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$find_goods_data]);
    }

    // 搜索服务技师--不论上班与否都可以搜索出来
    public function searchAllTechnician(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();

        if (!empty($request['vish_id'])) {
            $list = DB::table('virtual_adm as va')
                ->leftjoin('admin as a', 'a.adm_id', '=', 'va.viad_adm_id')
                ->where('adm_cid', $user_info->adm_cid)
                ->where('adm_superior_shop_id', $shop_id)
                ->where('viad_state', 1)
                ->where(function ($query) use ($request) {
                    if (!empty($request['vish_id'])) {
                        $query->where('viad_vish_id', $request['vish_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['search_data'])) {
                        $query->where('adm_name', 'like', '%' . $search_data['search_data'] . '%');
                    }
                })
                ->get(['adm_id', 'adm_name', 'adm_phone']);
        // $list = DB::table('virtual_admin')
            //     ->where('viad_cid', $user_info->adm_cid)
            //     ->where('viad_superior_shop_id', $shop_id)
            //     ->where('viad_state', 1)
            //     ->whereIn('viad_leave', [3, 5])
            //     ->where(function ($query) use ($request) {
            //         if (!empty($request['vish_id'])) {
            //             $query->where('viad_vish_id', $request['vish_id']);
            //         }
            //     })
            //     ->where(function ($query) use ($search_data) {
            //         if (!empty($search_data['search_data'])) {
            //             $query->where('viad_name', 'like', '%'.$search_data['search_data'] . '%');
            //         }
            //     })
            //     ->get(['viad_id as adm_id', 'viad_name as adm_name', 'viad_phone as adm_phone']);
        } else {
            $list = DB::table('admin')
                ->where('adm_cid', $user_info->adm_cid)
                ->where('adm_superior_shop_id', $shop_id)
                ->where('adm_state', 1)
                ->whereIn('adm_leave', [3, 5])
                ->where('adm_type', '!=', 2)  //不等于虚拟加盟店
                ->where(function ($query) use ($request) {
                    if (!empty($request['vish_id'])) {
                        $query->where('adm_vish_id', $request['vish_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['search_data'])) {
                        $query->where('adm_name', 'like', '%' . $search_data['search_data'] . '%');
                    }
                })
                ->get(['adm_id', 'adm_name', 'adm_phone']);
        }
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list]);
    }

    // 搜索勾选过的服务门店
    public function searchAllShop(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 获取到该账号下勾选的服务门店id
        $shop_id = DB::table('admin_set')
            ->where('adms_adm_id', $user_info->adm_id)
            ->where('adms_shop_id', $user_info->adm_shop_id)
            ->value('adms_shop_id');
        if (empty($shop_id)) {
            $shop_id = [];
        } else {
            $shop_id = explode(',', $shop_id);
        }

        // 获取到服务门店信息
        $search_data = $request->all();

        $list_data = DB::table('shop')
            ->whereIn('shop_id', $shop_id)
            ->where('shop_state', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('shop_store_name', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->select('shop_id', 'shop_store_name')
            ->orderBy('shop_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 getAllShop(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 获取到该账号下勾选的服务门店id
        $shop_id = DB::table('admin_set')
            ->where('adms_adm_id', $user_info->adm_id)
            ->where('adms_shop_id', $user_info->adm_shop_id)
            ->value('adms_shop_id');
        if (empty($shop_id)) {
            $shop_id = [];
        } else {
            $shop_id = explode(',', $shop_id);
        }

        // 获取到服务门店信息
        $search_data = $request->all();
        $list_data = DB::table('shop')
            ->whereIn('shop_id', $shop_id)
            ->where('shop_type', 3)
            ->where('shop_state', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('shop_store_name', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->select('shop_id', 'shop_store_name')
            ->orderBy('shop_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 getVirtualShop(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $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('virtual_shop')
            ->leftjoin('channel_unit as cu', 'cu.chun_id', '=', 'virtual_shop.vish_chun_id')
            ->where('vish_superior_shop_id', $shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('chun_unit_name', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (empty($search_data['type'])) {
                    $query->where('vish_state', 1);
                }
            })
            ->select('vish_id', 'vish_store_name')
            ->orderBy('vish_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 searchAllWarehouse(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;

        // 获取到该账号下勾选的仓库id
        $ware_id = 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');
        if (empty($ware_id)) {
            $ware_id = [];
        } else {
            $ware_id = explode(',', $ware_id);
        }
        $search_data = $request->all();

        if ($request['ware_type'] == 1) {
            // 只搜索被设置的固定仓
            $data = DB::table('warehouse')
                ->where('ware_cid', $user_info->adm_cid)
                ->where('ware_superior_shop_id', $shop_id)
                ->whereIn('ware_id', $ware_id)
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['search_data'])) {
                        $query->where('ware_name', 'like', '%' . $search_data['search_data'] . '%');
                    }
                })
                ->get(['ware_id', 'ware_default', 'ware_name']);
        } else {
            // 搜索被设置的固定仓、移动仓,搜索启用的仓库
            $data = DB::table('warehouse')
                ->where('ware_cid', $user_info->adm_cid)
                ->where('ware_superior_shop_id', $shop_id)
                ->where('ware_state', 1)
                ->where('ware_type', '<>', 2)
                ->whereIn('ware_id', $ware_id)
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['search_data'])) {
                        $query->where('ware_name', 'like', '%' . $search_data['search_data'] . '%');
                    }
                })
                ->get(['ware_id', 'ware_default', 'ware_name']);
        }

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

    // 快速查询仓库权限
    public function quickSearchWarehouse(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;

        // 获取到该账号下勾选的仓库id，快速查询仓库权限字段
        $ware_id = DB::table('admin_set')
            ->where('adms_adm_id', $user_info->adm_id)
            ->where('adms_shop_id', $user_info->adm_shop_id)
            ->value('adms_ware_ids');
        if (empty($ware_id)) {
            $ware_id = [];
        } else {
            $ware_id = explode(',', $ware_id);
        }
        $search_data = $request->all();

        if ($request['ware_type'] == 1) {
            // 只搜索被设置的固定仓
            $data = DB::table('warehouse')
                ->where('ware_cid', $user_info->adm_cid)
                ->where('ware_superior_shop_id', $shop_id)
                ->whereIn('ware_id', $ware_id)
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['search_data'])) {
                        $query->where('ware_name', 'like', '%' . $search_data['search_data'] . '%');
                    }
                })
                ->get(['ware_id', 'ware_default', 'ware_name']);
        } else {
            // 搜索被设置的固定仓、移动仓,搜索启用的仓库
            $data = DB::table('warehouse')
                ->where('ware_cid', $user_info->adm_cid)
                ->where('ware_superior_shop_id', $shop_id)
                ->where('ware_state', 1)
                ->where('ware_type', '<>', 2)
                ->whereIn('ware_id', $ware_id)
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['search_data'])) {
                        $query->where('ware_name', 'like', '%' . $search_data['search_data'] . '%');
                    }
                })
                ->get(['ware_id', 'ware_default', 'ware_name']);
        }

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

    // 根据仓库id 商品id 搜索良品/优先库存
    public function searchInventory(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyCashierDeskController;
        $error_message = $verify_data->searchInventoryValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        if (!isset($request['wafr_id'])) {
            $request['wafr_id'] = [];
            // $request->offset('wafr_id', []);
        }
        $data['freight'] = DB::table('warehouse_freight_goods')
            ->where('wafg_ware_id', $request['ware_id'])
            ->whereIn('wafg_wafr_id', $request['wafr_id'])
            ->whereIn('wafg_goo_id', $request['goo_id'])
            ->whereIn('wafg_class', $request['goo_waon_class'])
            ->select('wafg_id', 'wafg_wafr_id', 'wafg_goo_id', 'wafg_class', 'wafg_stock_number', 'wafg_priority_stock_number')
            ->get()->toArray();
        if (!empty($data['freight'])) {
            // 查询仓位数据
            $wafg_wafr_id = array_column($data['freight'], 'wafg_wafr_id');
            $wafr_data = DB::table('warehouse_freight')
                ->whereIn('wafr_id', $wafg_wafr_id)
                ->pluck('wafr_name', 'wafr_id')
                ->toArray();
            foreach ($data['freight'] as $key => $value) {
                if (!empty($value->wafg_wafr_id)) {
                    $data['freight'][$key]->wafg_wafr_name = $wafr_data[$value->wafg_wafr_id];
                } else {
                    $data['freight'][$key]->wafg_wafr_name = '';
                }
            }
        } else {
            $data['freight'] = [];
        }

        $data['warehouse'] = DB::table('warehouse_goods')
            ->where('wago_ware_id', $request['ware_id'])
            ->whereIn('wago_goo_id', $request['goo_id'])
            ->whereIn('wago_class', $request['goo_waon_class'])
            ->select('wago_id', 'wago_goo_id', 'wago_class', 'wago_stock_number', 'wago_priority_stock_number')
            ->get()->toArray();
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }

    // 信息缓存提交
    public function infoCache(Request $request)
    {
        $verify_data = new VerifyCashierDeskController;
        $error_message = $verify_data->infoCacheValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

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

        // 判断新增还是修改
        $find_ord = DB::table('order_cache')
            ->where('orca_create_id', $user_info->adm_id)
            ->select('orca_id')
            ->first();

        foreach ($request['goo_id'] as $key => $value) {
            if (!is_numeric($value) || !is_numeric($request['goo_price'][$key]) || !is_numeric($request['goo_quantity'][$key]) || !in_array($request['goo_state'][$key], [1, 3, 4, 5, 6, 7, 8]) || !is_numeric($request['goo_collection_price'][$key])) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'商品参数类型错误'];
            }
            $goo_data[$key]['orgc_goo_id'] = $value;
            $goo_data[$key]['orgc_wago_id'] = isset($request['wago_id'][$key]) ? $request['wago_id'][$key] : 0;
            $goo_data[$key]['orgc_wafr_id'] = isset($request['wafr_id'][$key]) ? $request['wafr_id'][$key] : 0;
            $goo_data[$key]['orgc_wafg_id'] = isset($request['wafg_id'][$key]) ? $request['wafg_id'][$key] : 0;
            $goo_data[$key]['orgc_ware_id'] = isset($request['ware_id']) ? $request['ware_id'] : 0;
            $goo_data[$key]['orgc_waon_class'] = isset($request['goo_waon_class'][$key]) ? $request['goo_waon_class'][$key] : 0;
            $goo_data[$key]['orgc_goo_price'] = $request['goo_price'][$key] * 100;
            $goo_data[$key]['orgc_goo_quantity'] = $request['goo_quantity'][$key];
            $goo_data[$key]['orgc_collection_price'] = $request['goo_collection_price'][$key] * 100;
            $goo_data[$key]['orgc_goo_inventory'] = isset($request['goo_inventory'][$key]) ? $request['goo_inventory'][$key] : 1;
            $goo_data[$key]['orgc_state'] = $request['goo_state'][$key];
            $goo_data[$key]['orgc_update_time'] = date('Y-m-d H:i:s');
            // 搜索商品id对应的商品名称、商品编号
            $find_goods_data = DB::table('goods')
                ->where('goo_id', $value)
                ->select('goo_name', 'goo_goods_encode', 'goo_type', 'goo_ampere_hour', 'goo_class')
                ->first();
            if ($find_goods_data->goo_class == 1) { //类型：1自营商品2系统商品
                // 查询商品附属表
                $goaf_another_name = DB::table('goods_affiliate')
                    ->where('goaf_goo_id', $value['goo_id'])
                    ->where('goaf_shop_id', $user_info->adm_shop_id)
                    ->value('goaf_another_name');
                if (!empty($goaf_another_name)) {
                    $find_goods_data->goo_name = $goaf_another_name;
                }
            } else {
                // 查询系统商品属性表
                $gosa_another_name = DB::table('goods_system_affiliate')
                    ->where('gosa_goo_id', $value['goo_id'])
                    ->where('gosa_shop_id', $user_info->adm_shop_id)
                    ->value('gosa_another_name');
                if (!empty($gosa_another_name)) {
                    $find_goods_data->goo_name = $gosa_another_name;
                }
            }
            if (!empty($request['tem_goo_name'][$key])) {
                $tem_goo_name = $request['tem_goo_name'][$key];
            } else {
                $tem_goo_name = '';
            }
            $goo_data[$key]['orgc_tem_goo_name'] = $tem_goo_name;
            $goo_data[$key]['orgc_goo_name'] = $find_goods_data->goo_name;
            $goo_data[$key]['orgc_goo_goods_encode'] = $find_goods_data->goo_goods_encode;
            $goo_data[$key]['orgc_goo_type'] = isset($request['goo_type'][$key]) ? $request['goo_type'][$key] : $find_goods_data->goo_type;
            $goo_data[$key]['orgc_goo_ampere_hour'] = $find_goods_data->goo_ampere_hour;
            $goo_data[$key]['orgc_assign_price'] = $request['goo_assign_price'][$key] * 100; //派单金额
        }

        DB::beginTransaction();
        // $ord_data['orca_shipment_party'] = $request['shipment_party'];
        // 出货方为1是仓库当前门店，为2是加盟店
        if ($request['shipment_party'] == 1) {
            // 服务门店id，是当前账号的门店
            $ord_data['orca_service_shop_id'] = $user_info->adm_shop_id;
        } else {
            // 服务门店是加盟店id
            $ord_data['orca_service_shop_id'] = $request['ord_service_shop_id'];
        }
        //选择客户id
        $ord_data['orca_client_id'] = $request['ord_client_id'] ? $request['ord_client_id'] : '';
        // 订单类型：1门店零售2渠道单位
        $ord_data['orca_type'] = $request['ord_type'] ? $request['ord_type'] : '';
        $ord_data['orca_orla_id'] = $request['orla_id'] ? $request['orla_id'] : 0;
        //服务类型：1其他 2派工安装 3送货 4送货安装 5补单 6救援单 7到店安装
        $ord_data['orca_service_type'] = $request['ord_service_type'] ? $request['ord_service_type'] : '';
        //服务项目id
        $ord_data['orca_service_sepr_id'] = $request['ord_service_sepr_id'] ? $request['ord_service_sepr_id'] : '';
        //服务技师id
        $ord_data['orca_service_adm_id'] = $request['ord_service_adm_id'] ? $request['ord_service_adm_id'] : 0;
        //仓库id
        $ord_data['orca_ware_id'] = $request['ware_id'] ? $request['ware_id'] : 0;
        // 结算方式1.账期 2.现结 3微信 4支付宝
        $ord_data['orca_payment_way'] = $request['ord_payment_way'] ? $request['ord_payment_way'] : 0;
        // 结算金额（单位：分）
        $ord_data['orca_actual_price'] = $request['ord_actual_price'] ? $request['ord_actual_price'] * 100 : 0;
        //订单备注
        $ord_data['orca_remark'] = $request['ord_remark'] ? $request['ord_remark'] : '';
        //商品代收金额（单位：分）
        $ord_data['orca_collection_price'] =  $request['ord_collection_price'] ? $request['ord_collection_price'] * 100 : 0;
        // 活动id
        $ord_data['orca_acti_id'] =  $request['orca_acti_id'] ? $request['orca_acti_id'] : 0;
        // 活动条数
        $ord_data['orca_acti_row'] =  $request['orca_acti_row'] ? $request['orca_acti_row'] : 0;

        // 订单客户缓存表
        $orcl_data['orcc_name'] = $request['orcl_name'] ? $request['orcl_name'] : '';
        $orcl_data['orcc_phone'] = $request['orcl_phone'] ? $request['orcl_phone'] : '';
        $orcl_data['orcc_car_num'] = $request['orcl_car_num'] ? $request['orcl_car_num'] : ''; //车牌号
        $orcl_data['orcc_car_vehicle_type'] = $request['orcl_car_vehicle_type'] ? $request['orcl_car_vehicle_type'] : ''; //车型【新增字段】
        $orcl_data['orcc_province'] = $request['orcl_province'] ? $request['orcl_province'] : '';
        $orcl_data['orcc_city'] = $request['orcl_city'] ? $request['orcl_city'] : '';
        $orcl_data['orcc_county'] = $request['orcl_county'] ? $request['orcl_county'] : '';
        $orcl_data['orcc_address'] = $request['orcl_address'] ? $request['orcl_address'] : '';
        $orcl_data['orcc_chin_type'] = isset($request['orcc_chin_type']) ? $request['orcc_chin_type'] : 2; //是否铺货：1是2否
        $orcl_data['orcc_collect_state'] = $request->filled('orcl_collect_state') ? $request['orcl_collect_state'] : 0;
        $orcl_data['orcc_rescue_service_price'] = $request->filled('orcl_rescue_service_price') * 100 ? $request['orcl_rescue_service_price'] * 100 : 0; //救援单的服务项目金额
        $orcl_data['orcc_rescue_collection_price'] = $request->filled('orcl_rescue_collection_price') * 100 ? $request['orcl_rescue_collection_price'] * 100 : 0; //救援单的代收金额
        $orcl_data['orcc_update_time'] = date('Y-m-d H:i:s');
        $orcl_data['orcc_standby_battery_type'] = isset($request['orcl_standby_battery_type']) ? $request['orcl_standby_battery_type'] : 2; //是否为备用电池1是2否
        $orcl_data['orcc_shipment_party'] = isset($request['orcc_shipment_party']) ? $request['orcc_shipment_party'] : 2; //是否为备用电池1是2否
        $orcl_data['orcc_assign_price'] = $request['orcl_assign_price'] * 100 ? $request['orcl_assign_price'] * 100 : 0; //派单总金额
        $orcl_data['orcc_plus_minus'] = $request['orcc_plus_minus']; //金额正负：1正值2负值
        $orcl_data['orcc_assign_plus_minus'] = isset($request['orcc_assign_plus_minus']) ? $request['orcc_assign_plus_minus'] : ''; //派单金额正负：1正值2负值
        $orcl_data['orcc_junk_type'] = isset($request['orcc_junk_type']) ? $request['orcc_junk_type'] : 2; //是否为旧货1是2否
        $orcl_data['orcc_whether_app'] = isset($request['whether_app']) ? $request['whether_app'] : 1; //是否走技师流程1是2否
        $orcl_data['orcc_precise_lock'] = isset($request['precise_lock']) ? $request['precise_lock'] : 2; //精确打卡1是 2否
        if (isset($request['orcc_appoint_time'])) {
            $orcl_data['orcc_appoint_time'] = $request['orcc_appoint_time'] ?? ''; //预约时间
        }
        if ($find_ord) {
            // 1. 编辑订单缓存表数据
            // 编辑
            $ord_data['orca_update_time'] = date('Y-m-d H:i:s');
            $ord_id = DB::table('order_cache')
                ->where('orca_id', $find_ord->orca_id)
                ->update($ord_data);

            // 2. 查询原来订单商品缓存表 有该订单下的商品: 删除后新增 没有该订单下的商品：直接新增
            $orgc_data = DB::table('order_goods_cache')
                ->where('orgc_orca_id', $find_ord->orca_id)
                ->first();
            if (!empty($goo_data)) {
                if ($orgc_data) {
                    $del_res = DB::table('order_goods_cache')
                        ->where('orgc_orca_id', $find_ord->orca_id)
                        ->delete();
                } else {
                    $del_res = true;
                }
                foreach ($goo_data as $key => $value) {
                    $goo_data[$key]['orgc_orca_id'] = $find_ord->orca_id;
                }

                $orgc_res = DB::table('order_goods_cache')->insert($goo_data);
            } else {
                if ($orgc_data) {
                    $del_res = DB::table('order_goods_cache')
                        ->where('orgc_orca_id', $find_ord->orca_id)
                        ->delete();
                } else {
                    $del_res = true;
                }
                $orgc_res = true;
            }
            $orcc_id = DB::table('order_client_cache')
                ->where('orcc_orca_id', $find_ord->orca_id)
                ->select('orcc_id')
                ->first();
            if ($orcc_id->orcc_id) {
                // 3. 更新订单客户缓存表
                $orcl_res = DB::table('order_client_cache')
                    ->where('orcc_orca_id', $find_ord->orca_id)
                    ->update($orcl_data);
            } else {
                // 添加客户缓存数据
                $orcl_data['orcc_orca_id'] = $find_ord->orca_id;
                $orcl_res = DB::table('order_client_cache')->insert($orcl_data);
            }
        } else {
            // 新增
            // 1. 添加订单缓存表数据
            $ord_data['orca_cid'] = $user_info->adm_cid;
            $ord_data['orca_shop_id'] = $user_info->adm_shop_id;
            $ord_data['orca_create_id'] = $user_info->adm_id;

            $ord_id = DB::table('order_cache')->insertGetId($ord_data);

            // 2. 添加订单商品缓存表
            if (empty($request['goo_id'])) {
                $orgc_res = true;
            } else {
                foreach ($goo_data as $key => $value) {
                    $goo_data[$key]['orgc_orca_id'] = $ord_id;
                }
                $orgc_res = DB::table('order_goods_cache')->insert($goo_data);
            }
            $del_res = true;

            // 3. 添加订单客户缓存表
            $orcl_data['orcc_orca_id'] = $ord_id;
            $orcl_res = DB::table('order_client_cache')->insert($orcl_data);
        }

        if ($ord_id && $orgc_res && $del_res && $orcl_res) {
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'缓存成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'缓存失败']);
        }
    }

    // 可换商品搜索
    public function searchExchangeGoods(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyCashierDeskController;
        $error_message = $verify_data->searchExchangeGoodsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

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

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

        $search_data = $request->all();

        $ord_res = DB::table('order as ord')
            ->leftjoin('order_goods as orgo', 'orgo.orgo_ord_id', '=', 'ord.ord_id')
            ->where('ord_cid', $user_info->adm_cid)
            ->where('ord_superior_shop_id', $shop_id)
            ->where('ord_delete', 1)
            ->where('ord_type', $request['ord_type'])
            ->where('ord_client_id', $request['ord_client_id'])
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ord_create_time'])) {
                    $query->where('ord_create_time', 'like', '%' . $search_data['ord_create_time'] . '%');
                }
            }) //录单时间
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orgo_goo_goods_encode'])) {
                    $query->where('orgo_goo_goods_encode', 'like', '%' . $search_data['orgo_goo_goods_encode'] . '%');
                }
            }) //检索编码
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orgo_goo_name'])) {
                    $query->where('orgo_goo_name', 'like', '%' . $search_data['orgo_goo_name'] . '%');
                }
            }) //商品名称
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ord_state'])) {
                    $query->where('ord_state', $search_data['ord_state']);
                }
            }) //结算状态1未结算2已结算
            ->select('orgo_goo_id', 'orgo_goo_name', 'orgo_goo_goods_encode', 'orgo_goo_price', 'orgo_goo_quantity', 'ord_state', 'ord_create_time')
            ->orderBy('ord_create_time', 'desc')
            ->offset(0)->limit(5)
            ->get();

        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$ord_res]);
    }

    // 可换商品搜索
    public function searchExchangeGoods2(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyCashierDeskController;
        $error_message = $verify_data->searchGoodsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $search_data = $request->all();
        if (!isset($search_data['shop_id'])) {
            $search_data['shop_id'] = 0;
        }
        $shop_state = true;
        if (in_array($shop_id, config('apisystem.NO_SHOPID'))) {
            $shop_state = false;
        }

        $list_data = DB::table('goods as a')
            ->leftJoin('goods_correlation_system as b', 'a.goo_id', '=', 'b.goco_parent_goo_id')
            ->where(function ($query) use ($user_info, $shop_state) {
                if ($shop_state) {
                    $query->where('goo_cid', 0)
                        ->orwhere('goo_cid', $user_info->adm_cid);
                } else {
                    $query->where('goo_cid', $user_info->adm_cid);
                }
            })
            ->where(function ($query) use ($user_info, $shop_state, $search_data) {
                if ($shop_state) {
                    if ($search_data['shop_id']) {
                        $query->where('goo_shop_id', 0)
                            ->orwhere(function ($query) use ($user_info, $shop_state, $search_data) {
                                $query->where('goo_shop_id', $user_info->adm_shop_id)
                                    ->where('goco_shop_id', $search_data['shop_id'])
                                    ->where('goco_state', 2);
                            });
                    } else {
                        $query->where('goo_shop_id', 0)
                            ->orwhere('goo_shop_id', $user_info->adm_shop_id);
                    }
                } else {
                    if ($search_data['shop_id']) {
                        $query->where(function ($query) use ($user_info, $shop_state, $search_data) {
                            $query->where('goo_shop_id', $user_info->adm_shop_id)
                                ->where('goco_shop_id', $search_data['shop_id'])
                                ->where('goco_state', 2);
                        });
                    } else {
                        $query->where('goo_shop_id', $user_info->adm_shop_id);
                    }
                }
            })
            ->where('goo_delete', 1)
            ->where('goo_state', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_name'])) {
                    $query->where('goo_name', 'like', '%' . $search_data['goo_name'] . '%')
                        ->orwhere('goo_goods_encode', 'like', '%' . $search_data['goo_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_bra_id'])) {
                    $query->where('goo_bra_id', $search_data['goo_bra_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_cate_id'])) {
                    $query->where('goo_cate_id', $search_data['goo_cate_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_type'])) {
                    $query->where('goo_type', $search_data['goo_type']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_brse_id'])) {
                    $query->where('goo_brse_id', $search_data['goo_brse_id']);
                }
            }) //品牌系列id
            ->select('goo_class', 'goo_id', 'goo_name', 'goo_type', 'goo_goods_encode', 'goo_assign_price', 'goo_wholesale_price as goo_price', 'goo_ampere_hour', 'goo_brse_id', 'goo_bra_name')
            ->orderBy('goo_goods_encode', '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;       //一页显示多少个
        $goods_data = $list_data->items();
        $goo_id = array_column($goods_data, 'goo_id');
        // 查询商品附属表信息
        $goaf_data = DB::table('goods_affiliate')
            ->where('goaf_shop_id', $user_info->adm_shop_id)
            ->whereIn('goaf_goo_id', $goo_id)
            ->pluck('goaf_another_name', 'goaf_goo_id')
            ->toArray();
        //系统商品替换价格
        foreach ($goods_data as $k => $v) {
            if ($v->goo_class == 2) {
                $gosa_where['gosa_shop_id'] = $shop_id;
                $gosa_where['gosa_goo_id'] = $v->goo_id;
                $gosa_res = DB::table('goods_system_affiliate')->where($gosa_where)->select('gosa_wholesale_price', 'gosa_assign_price')->first();
                if ($gosa_res) {
                    $goods_data[$k]->goo_price = $gosa_res->gosa_wholesale_price;
                    $goods_data[$k]->goo_assign_price = $gosa_res->gosa_assign_price;
                }
                if (isset($goaf_data[$v->goo_id])) { // 商品别名
                    $data_info['data'][$k]->goaf_another_name = $goaf_data[$v->goo_id];
                }
            }
        }
        $data_info['data'] = $goods_data;                //返回数据
        $data_info['brse_data'] = []; //品牌系列数据
        if ($data_info['data']) {
            // 查询品牌系列数据
            $goo_brse_id = array_filter(array_unique(array_column($data_info['data'], 'goo_brse_id')));
            if ($goo_brse_id) {
                $data_info['brse_data'] = DB::table('brand_serie')
                    ->whereIn('brse_id', $goo_brse_id)
                    ->select('brse_id', 'brse_name')
                    ->get();
            }
        }

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

    // 验证可欠/警示天数
    public function oweDay(Request $request)
    {
        $verify_data = new VerifyCashierDeskController;
        $error_message = $verify_data->oweDayValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

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

        // 查询出 当前渠道单位的可欠天数/警示天数/铺货类型：1是铺货 2不是铺货
        $chun_info = DB::table('channel_info')
            ->where('chin_chun_id', $request['chun_id'])
            ->first(['chin_type', 'chin_owe_day', 'chin_caution_day', 'chin_owe_money', 'chin_caution_money']);
        if (empty($chun_info)) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>[]]);
        }
        // 查询出该客户最早未结算的订单距离今天的天数
        $ord_time = DB::table('receivable_credit')
            ->where('recr_cid', $user_info->adm_cid)
            ->where('recr_shop_id', $user_info->adm_shop_id)
            ->where('recr_state', '!=', 2) //未核销 2.已核销 3已收款
            ->where('recr_belongs_id', '=', 0)
            ->where('recr_plus_minus', 1) //金额正值
            ->where('recr_client_id', $request['chun_id'])
            ->where('recr_client_type', 2)
            ->orderBy('recr_order_time', 'asc')
            ->value('recr_order_time');
        if ($ord_time) {
            $diff_day = (strtotime(date('Y-m-d')) - strtotime(substr($ord_time, 0, 10))) / 86400;
        } else {
            $diff_day = 0;
        }

        $data = [];

        //剩余可欠天数
        $remain_day = $chun_info->chin_owe_day - $diff_day;

        //可欠天数 - 警示天数
        $warning_day  = $chun_info->chin_owe_day - $chun_info->chin_caution_day;

        if ($chun_info->chin_owe_day != 0) {
            $data['day']['diff_day'] = $diff_day; //已欠天数
            $data['day']['chin_owe_day'] = $chun_info->chin_owe_day; //可欠天数
            $data['day']['chin_caution_day'] = $chun_info->chin_caution_day; //可欠预警天数
        } else {
            $data['day'] = (object)[];
        }

        // 判断是否为加盟店账号,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 ($chun_info->chin_owe_money != 0) {
            $cashierDesk = new CashierDesk;
            //客户单位应收正值
            $positive = $cashierDesk->positive($user_info, $request['chun_id'], $shop_id);
            //客户单位应收负值
            $minus = $cashierDesk->minus($user_info, $request['chun_id'], $shop_id);
            // //虚拟加盟店
            // $vish_id = DB::table('virtual_shop')
            //     ->where('vish_chun_id',$request['chun_id'])
            //     ->value('vish_id');
            // if(!empty($vish_id)){
            //     //负数
            //     $minus_virtual = DB::table('receivable_credit')
            //         ->where('recr_cid', $user_info->adm_cid)
            //         ->where('recr_shop_superior_id', $shop_id)
            //         ->where('recr_state', 1)//未核销
            //         ->where('recr_statistics_type', 1)//1统计状态
            //         ->where('recr_plus_minus', 2)//金额正值
            //         ->where('recr_client_id',$vish_id)
            //         ->where('recr_client_type',7)
            //         ->select(DB::raw('sum(recr_settle_price) as recr_settle_price,sum(recr_actual_price) as recr_actual_price,sum(recr_yet_receipt) as recr_yet_receipt,sum(recr_zero_price) as recr_zero_price'))
            //         ->first();
            //     $minus->recr_settle_price += $minus_virtual->recr_settle_price;
            //     $minus->recr_yet_receipt += $minus_virtual->recr_yet_receipt;
            //     $minus->recr_zero_price += $minus_virtual->recr_zero_price;
            // }

            $recr_settle_price = $positive['recr_settle_price'] - $minus['recr_settle_price']; //实际金额
            $recr_yet_receipt = $positive['recr_yet_receipt'] - $minus['recr_yet_receipt']; //已收金额
            $recr_zero_price = $positive['recr_zero_price'] - $minus['recr_zero_price']; //抹零金额
            // 欠收 = 结算金额 - 已收 - 抹零
            $total_client_price = ($recr_settle_price - $recr_yet_receipt - $recr_zero_price) / 100;
            $data['money']['diff_money'] = $total_client_price;
            $data['money']['chin_owe_money'] = $chun_info->chin_owe_money;
            $data['money']['chin_caution_money'] = $chun_info->chin_caution_money;
        } else {
            $data['money'] = (object)[];
        }
        if (!empty($data)) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        } else {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>[]]);
        }
    }

    // 获取信息缓存数据
    public function getCache(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 获取订单缓存表数据
        $orca_data = DB::table('order_cache as oc')
            ->where('orca_create_id', $user_info->adm_id)
            ->select('orca_id', 'orca_client_id', 'orca_type', 'orca_service_type', 'orca_service_sepr_id', 'orca_service_shop_id', 'orca_service_adm_id', 'orca_ware_id', 'orca_payment_way', 'orca_actual_price', 'orca_remark', 'orca_collection_price', 'orca_acti_id', 'orca_acti_row')
            ->first();
        if (empty($orca_data)) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>[]]);
        }
        if ($orca_data->orca_service_shop_id) {
            $find_shop = DB::table('shop')
                ->where('shop_id', $orca_data->orca_service_shop_id)
                ->select('shop_store_name', 'shop_type')
                ->first();
            $orca_data->orca_service_shop_store_name = $find_shop->shop_store_name;
            $orca_data->orca_service_shop_type = $find_shop->shop_type;
        } else {
            $orca_data->orca_service_shop_store_name = '';
            $orca_data->orca_service_shop_type = '';
            $orca_data->orca_service_shop_id = '';
        }

        // 获取服务项目名称
        $orca_data->ord_service_sepr_name = DB::table('service_project')
            ->where('sepr_id', $orca_data->orca_service_sepr_id)
            ->value('sepr_name');

        // 获取仓库名称
        $orca_data->ware_name = DB::table('warehouse')
            ->where('ware_id', $orca_data->orca_ware_id)
            ->value('ware_name');

        // 获取技师名称
        $orca_data->orca_service_adm_name = DB::table('admin')
            ->where('adm_id', $orca_data->orca_service_adm_id)
            ->value('adm_name');

        // 获取订单商品缓存表数据
        $orgc_data = DB::table('order_goods_cache')
            ->where('orgc_orca_id', $orca_data->orca_id)
            ->select('orgc_wago_id', 'orgc_goo_id', 'orgc_goo_name', 'orgc_goo_goods_encode', 'orgc_goo_price', 'orgc_goo_quantity', 'orgc_is_recycle', 'orgc_collection_price', 'orgc_goo_inventory', 'orgc_state', 'orgc_goo_type', 'orgc_recycle_price', 'orgc_recycle_quantity', 'orgc_goo_ampere_hour', 'orgc_ware_id', 'orgc_waon_class', 'orgc_tem_goo_name as tem_goo_name', 'orgc_assign_price', 'orgc_wafr_id', 'orgc_wafg_id')
            ->get()->toArray();
        // 查询仓位数据
        $orgc_wafr_id = array_column($orgc_data, 'orgc_wafr_id');
        $wafr_data = DB::table('warehouse_freight')
            ->whereIn('wafr_id', $orgc_wafr_id)
            ->pluck('wafr_name', 'wafr_id')
            ->toArray();
        foreach ($orgc_data as $key => $value) {
            if (!empty($value->orgc_wafr_id)) {
                $orgc_data[$key]->orgc_wafr_name = $wafr_data[$value->orgc_wafr_id];
            } else {
                $orgc_data[$key]->orgc_wafr_name = '';
            }
        }
        if (empty($orgc_data)) {
            $orgc_data = [];
        }

        // 获取订单客户缓存表数据
        $orcc_info = DB::table('order_client_cache')
            ->where('orcc_orca_id', $orca_data->orca_id)
            ->select('orcc_name', 'orcc_phone', 'orcc_province', 'orcc_city', 'orcc_county', 'orcc_address', 'orcc_car_num', 'orcc_chin_type', 'orcc_collect_state', 'orcc_rescue_service_price', 'orcc_rescue_collection_price', 'orcc_standby_battery_type', 'orcc_shipment_party', 'orcc_assign_price', 'orcc_plus_minus', 'orcc_assign_plus_minus', 'orcc_car_vehicle_type', 'orcc_junk_type', 'orcc_appoint_time')
            ->first();
        if (empty($orcc_info)) {
            $orcc_data = [];
        } else {
            // 判断是 1.门店零售  2.客户单位
            if ($orca_data->orca_type == 2) {
                // 客户单位数据
                if ($orca_data->orca_client_id == 0) {
                    $orcc_data = [];
                } else {
                    $orcc_data = DB::table('channel_info')
                        ->where('chin_chun_id', $orca_data->orca_client_id)
                        ->select('chin_level', 'chin_main_brand', 'chin_second_brand', 'chin_owe_day', 'chin_caution_day')
                        ->first();
                    // 查询出客户单位名称
                    $orcc_data->chun_unit_name = DB::table('channel_unit')
                        ->where('chun_id', $orca_data->orca_client_id)
                        ->value('chun_unit_name');
                    // 追加可以修改的 联系人姓名 电话 地址
                    $orcc_data->chun_name = $orcc_info->orcc_name;
                    $orcc_data->chun_phone = $orcc_info->orcc_phone;
                    $orcc_data->chun_address = $orcc_info->orcc_address;
                    $orcc_data->chun_car_num = $orcc_info->orcc_car_num; //车牌号
                    $orcc_data->chun_car_vehicle_type = $orcc_info->orcc_car_vehicle_type; //车型
                }
            } else {
                if ($orca_data->orca_client_id != '0') {
                    // 门店零售数据
                    $orcc_data = DB::table('member')
                        ->where('mem_id', $orca_data->orca_client_id)
                        ->select('mem_name', 'mem_phone')
                        ->first();
                    // 追加可以修改的 地址 车牌号
                    $orcc_data->mem_address = $orcc_info->orcc_address; //地址
                    $orcc_data->meca_car_num = $orcc_info->orcc_car_num; //车牌号
                    $orcc_data->meca_car_vehicle_type = $orcc_info->orcc_car_vehicle_type; //车型
                } else {
                    $orcc_data['mem_name'] = $orcc_info->orcc_name;
                    $orcc_data['mem_phone'] = $orcc_info->orcc_phone;
                    $orcc_data['meca_car_num'] = $orcc_info->orcc_car_num;
                    $orcc_data['meca_car_vehicle_type'] = $orcc_info->orcc_car_vehicle_type; //车型
                    $orcc_data['orcc_province'] = $orcc_info->orcc_province;
                    $orcc_data['orcc_city'] = $orcc_info->orcc_city;
                    $orcc_data['orcc_county'] = $orcc_info->orcc_county;
                    $orcc_data['mem_address'] = $orcc_info->orcc_address;
                }
            }
            $orca_data->orcc_collect_state = $orcc_info->orcc_collect_state; //技师是否收钱:0未选择1是2否
            $orca_data->orcc_province = $orcc_info->orcc_province; //省
            $orca_data->orcc_city = $orcc_info->orcc_city; //市
            $orca_data->orcc_county = $orcc_info->orcc_county; //区县
            $orca_data->orcc_rescue_service_price = $orcc_info->orcc_rescue_service_price; //救援单的服务项目金额
            $orca_data->orcc_rescue_collection_price = $orcc_info->orcc_rescue_collection_price; //救援单的代收金额
            $orca_data->orcc_standby_battery_type = $orcc_info->orcc_standby_battery_type; //是否为备用电池1是2否
            $orca_data->orcc_shipment_party = $orcc_info->orcc_shipment_party; //出库方
            $orca_data->orcc_assign_price = $orcc_info->orcc_assign_price; //派单总金额
            $orca_data->orcc_plus_minus = $orcc_info->orcc_plus_minus; //金额正负1正2负
            $orca_data->orcc_assign_plus_minus = $orcc_info->orcc_assign_plus_minus; //派单金额正负1正2负
            $orca_data->orcc_junk_type = $orcc_info->orcc_junk_type; //派单金额正负1正2负
            $orca_data->orcc_appoint_time = $orcc_info->orcc_appoint_time; //预约时间
            $orca_data->orcc_chin_type = $orcc_info->orcc_chin_type; //是否铺货：1是2否
        }

        // 获取活动数据
        if ($orca_data->orca_acti_id != '0') {
            $find_acti = DB::table('activity')
                ->where('acti_id', $orca_data->orca_acti_id)
                ->select('acti_name', 'acti_activity_type')
                ->first();
            // 根据活动类型判定
            if ($find_acti->acti_activity_type == '1') { //折扣
                $acdi_id = DB::table('activity_discount')
                    ->where('acdi_acti_id', $orca_data->orca_acti_id)
                    ->where('acdi_row', $orca_data->orca_acti_row)
                    ->select('acdi_discount', 'acdi_row')
                    ->first();
                $find_data['find_acdi'] = $acdi_id;
            } elseif ($find_acti->acti_activity_type == '2') { //买送
                $acdo_id = DB::table('activity_donate')
                    ->where('acdo_acti_id', $orca_data->orca_acti_id)
                    ->where('acdo_row', $orca_data->orca_acti_row)
                    ->select('acdo_purchase_quantity', 'acdo_attached_quantity', 'acdo_row')
                    ->first();
                $find_data['find_acdo'] = $acdo_id;
            } elseif ($find_acti->acti_activity_type == '3') { //买赠
                $acdo_id = DB::table('activity_donate')
                    ->where('acdo_acti_id', $orca_data->orca_acti_id)
                    ->where('acdo_row', $orca_data->orca_acti_row)
                    ->select('acdo_purchase_quantity', 'acdo_attached_quantity', 'acdo_row')
                    ->first();
                $find_data['find_acdo'] = $acdo_id;
            } elseif ($find_acti->acti_activity_type == '4') { //满减
                $acdr_id = DB::table('activity_discount_reduction')
                    ->where('acdr_acti_id', $orca_data->orca_acti_id)
                    ->where('acdr_row', $orca_data->orca_acti_row)
                    ->select('acdr_reduction_price', 'acdr_credit_price', 'acdr_row')
                    ->first();
                $find_data['find_acdr'] = $acdr_id;
            } elseif ($find_acti->acti_activity_type == '5') { //现结折扣
                $acdr_id = DB::table('activity_discount_reduction')
                    ->where('acdr_acti_id', $orca_data->orca_acti_id)
                    ->where('acdr_row', $orca_data->orca_acti_row)
                    ->select('acdr_reduction_price', 'acdr_discount', 'acdr_row')
                    ->first();
                $find_data['find_acdr'] = $acdr_id;
            } elseif ($find_acti->acti_activity_type == '6') { //累计返点
            } elseif ($find_acti->acti_activity_type == '7') { //高价回收
                $achr_id = DB::table('activity_high_recycling')
                    ->where('achr_acti_id', $orca_data->orca_acti_id)
                    ->where('achr_row', $orca_data->orca_acti_row)
                    ->select('achr_recycle_quantity', 'achr_recycle_price', 'achr_row')
                    ->first();
                $find_data['find_achr'] = $achr_id;
            } elseif ($find_acti->acti_activity_type == '8') { //大批量采购
                $acpr_id = DB::table('activity_procurement')
                    ->where('acpr_acti_id', $orca_data->orca_acti_id)
                    ->where('acpr_row', $orca_data->orca_acti_row)
                    ->select('acpr_goods_quantity', 'acpr_recycle_quantity', 'acpr_row')
                    ->first();
                $find_data['find_acpr'] = $acpr_id;
            }
            $find_data['find_acti'] = $find_acti;
        } else {
            $find_data = [];
        }

        // 数据合并
        $data = ['orca_data'=>$orca_data, 'orgc_data'=>$orgc_data, 'orcc_data'=>$orcc_data, 'find_data'=>$find_data];
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }

    // 工作总台-删除缓存数据
    public function deleteCache(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 删除缓存数据
        $ord_data = DB::table('order_cache')
            ->where('orca_create_id', $user_info->adm_id)
            ->select('orca_id')
            ->first();
        if (empty($ord_data->orca_id)) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'缓存删除成功']);
        }
        $orca_res = DB::table('order_cache')
            ->where('orca_id', $ord_data->orca_id)
            ->delete();

        $orcc_res = DB::table('order_client_cache')
            ->where('orcc_orca_id', $ord_data->orca_id)
            ->delete();
        $orgc_res = DB::table('order_goods_cache')
            ->where('orgc_orca_id', $ord_data->orca_id)
            ->delete();
        if ($orca_res) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'缓存删除成功']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'缓存删除失败']);
        }
    }

    // 搜索会计科目
    public function searchAccount(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $search_data = $request->all();
        $list_data = DB::table('account_title')
            ->where('acti_shop_id', $user_info->adm_shop_id)
            ->where('acti_state', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('acti_course_title', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->select('acti_id', 'acti_course_title')
            ->orderBy('acti_id', 'desc')
            ->get();

        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_data]);
    }

    // 搜索备用电池
    public function searchStandbyBattery(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;

        // 判断是否传仓库id
        if ($request['ware_id']) {
            $ware_id[] = $request['ware_id'];
        } else {
            // 获取到该账号下勾选的服务门店id
            $ware_id = 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');
            if (empty($ware_id)) {
                $ware_id = [];
            } else {
                $ware_id = explode(',', $ware_id);
            }
        }

        $search_data = $request->all();
        $waog_stock_type = true; //查询库存数量状态值：true查询有库存数量的，false查询所有的
        $list_data = DB::table('goods as g')
            ->join('warehouse_goods as wg', 'wg.wago_goo_id', '=', 'g.goo_id')
            ->join('warehouse as w', 'w.ware_id', '=', 'wg.wago_ware_id')
            ->where('goo_cid', $user_info->adm_cid)
            ->where('goo_shop_id', $shop_id)
            ->where('goo_delete', 1)
            ->where('goo_state', 1)
            ->where('ware_state', 1)
            ->whereIn('wago_ware_id', $ware_id)
            ->where('wago_class', 3)
            ->where(function ($query) use ($waog_stock_type) {
                $query->where('wago_stock_number', '>', 0)
                    ->orWhere('wago_priority_stock_number', '>', 0);
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_name'])) {
                    $query->where('goo_name', 'like', '%' . $search_data['goo_name'] . '%')
                        ->orwhere('goo_goods_encode', 'like', '%' . $search_data['goo_name'] . '%');
                }
            })
            // ->where(function ($query) use ($search_data) {
            //     if (!empty($search_data['waon_class'])) {
            //         $query->where('wago_class', $search_data['waon_class']);
            //     }
            // }) //仓库类别
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_type'])) {
                    $query->where('goo_type', $search_data['goo_type']);
                }
            }) //商品类型
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_bra_id'])) {
                    $query->where('goo_bra_id', $search_data['goo_bra_id']);
                }
            }) //品牌
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_cate_id'])) {
                    $query->where('goo_cate_id', $search_data['goo_cate_id']);
                }
            }) //品类
            ->select('goo_id', 'goo_name', 'goo_type', 'goo_goods_encode', 'goo_ampere_hour', 'goo_class')
            ->orderBy('goo_goods_encode', 'asc')
            ->groupBy('goo_id')
            ->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['goods_data'] = $list_data->items();
        if ($data_info['goods_data']) {
            $goo_id = array_column($data_info['goods_data'], 'goo_id');
            // 查询商品附属表信息
            $goaf_data = DB::table('goods_affiliate')
                ->where('goaf_shop_id', $user_info->adm_shop_id)
                ->whereIn('goaf_goo_id', $goo_id)
                ->pluck('goaf_another_name', 'goaf_goo_id')
                ->toArray();
            // 查询系统商品属性表信息
            $gosa_data = DB::table('goods_system_affiliate')
                ->where('gosa_shop_id', $user_info->adm_shop_id)
                ->whereIn('gosa_goo_id', $goo_id)
                ->pluck('gosa_another_name', 'gosa_goo_id')
                ->toArray();
            foreach ($data_info['goods_data'] as $key => $value) {
                if ($value->goo_class == 2 && isset($gosa_data[$value->goo_id]) && !empty($gosa_data[$value->goo_id])) {
                    $data_info['goods_data'][$key]->gosa_another_name = $gosa_data[$value->goo_id];
                }
                if (isset($goaf_data[$value->goo_id]) && !empty($goaf_data[$value->goo_id])) { // 商品别名
                    $data_info['goods_data'][$key]->goaf_another_name = $goaf_data[$value->goo_id];
                }
            }
            // 判断是否传仓库id
            if ($request['ware_id']) {
                $ware_id[] = $request['ware_id'];
            } else {
                // 获取到该账号下勾选的服务门店id
                $ware_id = 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');
                if (empty($ware_id)) {
                    $ware_id = [];
                } else {
                    $ware_id = explode(',', $ware_id);
                }
            }

            if ($ware_id) {
                $stock_data = DB::table('warehouse as a')
                    ->leftJoin('warehouse_goods as b', 'b.wago_ware_id', '=', 'a.ware_id')
                    ->where('ware_superior_shop_id', $shop_id)
                    ->where('ware_state', 1) //  状态1启用2停用3撤仓
                    ->whereIn('ware_id', $ware_id)
                    ->whereIn('wago_goo_id', $goo_id)
                    ->where(function ($query) use ($waog_stock_type) {
                        $query->where('wago_stock_number', '>', 0)
                            ->orWhere('wago_priority_stock_number', '>', 0);
                    })
                    ->select('wago_id', 'wago_goo_id', 'ware_id', 'ware_name', 'wago_class', 'wago_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity')
                    ->orderBy('wago_stock_number', 'desc')
                    ->get();
                $data_info['stock_data'] = $stock_data;
            } else {
                $data_info['stock_data'] = '';
            }
        } else {
            $data_info['stock_data'] = '';
        }

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

    // 获取运营中心下的门店
    public function getStoreShop(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;

        $shop_res = DB::table('shop')
            ->where('shop_parent_id', $shop_id)
            ->where('shop_state', 1)
            ->select('shop_store_name as shop_name', 'shop_id')
            ->get();
        if ($request['goo_id']) {
            $gocs_goods_id = DB::table('goods_correlation_system')
                ->where('goco_parent_goo_id', $request['goo_id'])
                ->select('goco_shop_id')
                ->get();
            foreach ($shop_res as $key => $value) {
                if (in_array($value['shop_id'], $gocs_goods_id)) {
                    unset($shop_res[$key]);
                }
            }
        }
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$shop_res]);
    }
}
