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

use Illuminate\Http\Request;
use App\Http\Controllers\Api\Verify\OrderManage\VerifyOrderController;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\Export;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Http\Models\Api\ReceivableBill;
use App\Http\Models\Api\AccountSubject;
use App\Http\Models\Api\AccountingSettlement;
use App\Http\Models\Api\Warehouse;
use App\Http\Models\Api\CashierDesk;
use App\Http\Models\Api\DispatchBill;
use App\Http\Models\Api\ReceivableCredit;
use App\Http\Models\Services\ImageUpload;
use App\Http\Models\Services\Order;
use App\Http\Models\Services\WarehouseLock;

// 业务系统 -- 订单列表
class OrderController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderController;
        $error_message = $verify_data->indexValidator($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 (!empty($search_data['min_price'])) {
            if (empty($search_data['ord_plus_minus'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
            }
            $search_data['min_price'] = $search_data['min_price'] * 100;
            if ($search_data['ord_plus_minus'] == 2) {
                $search_data['min_price'] = -$search_data['min_price'];
            }
        }
        // 实际金额最大钱数
        if (!empty($search_data['max_price'])) {
            if (empty($search_data['ord_plus_minus'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
            }
            $search_data['max_price'] = $search_data['max_price'] * 100;
            if ($search_data['ord_plus_minus'] == 2) {
                $search_data['max_price'] = -$search_data['max_price'];
                $max_price = $search_data['max_price'];
                $search_data['max_price'] = $search_data['min_price'];
                $search_data['min_price'] = $max_price;
            }
        }
        if (!empty($search_data['goo_goods_encode'])) { //订单列表-检索编码搜索
            $orgt_id = DB::table('order_goods_temporary')
                ->where('orgt_type', 1)
                ->where('orgt_adm_id', $user_info->adm_id)
                ->where('orgt_goods_encode', 'like', '%' . $search_data['goo_goods_encode'] . '%')
                ->value('orgt_id');
            if (empty($orgt_id)) {
                $this->goodsIndex($user_info, $shop_id, $search_data);
            }
            $list_data = DB::table('order as ord')
                ->leftJoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
                ->leftJoin('order_goods_temporary as orgt', 'orgt.orgt_ord_id', '=', 'ord.ord_id')
                ->where('ord_cid', $user_info->adm_cid)
                ->where('ord_superior_shop_id', $shop_id)
                ->where('ord_collection_bill', 1) //是否代收账单：1正常订单2代收账单
                ->where('orgt_adm_id', $user_info->adm_id)
                ->where('orgt_type', 1)
                ->where(function ($query) use ($search_data) { //仓库名称
                    if (!empty($search_data['ware_id'])) {
                        $query->where('ord_ware_id', $search_data['ware_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //业务员搜索
                    if (!empty($search_data['orcl_adm_id'])) {
                        $query->where('chun_adm_id', $search_data['orcl_adm_id'])
                            ->where('ord_type', 2);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_order_number'])) {
                        $query->where('ord_order_number', 'like', '%' . $search_data['ord_order_number'] . '%')
                            ->Orwhere('ord_other_system_number', 'like', '%' . $search_data['ord_order_number'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['orcl_name'])) {
                        $query->where('orcl_name', 'like', '%' . $search_data['orcl_name'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['orcl_phone'])) {
                        $query->where('orcl_phone', 'like', '%' . $search_data['orcl_phone'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['orcl_car_num'])) {
                        $query->where('orcl_car_num', 'like', '%' . $search_data['orcl_car_num'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //车型
                    if (!empty($search_data['orcl_car_vehicle_type'])) {
                        $query->where('orcl_car_vehicle_type', 'like', '%' . $search_data['orcl_car_vehicle_type'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_type'])) {
                        $query->where('ord_type', $search_data['ord_type']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_service_type'])) {
                        $query->where('ord_service_type', $search_data['ord_service_type']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_create_id'])) {
                        $query->where('ord_create_id', $search_data['ord_create_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_state'])) {
                        $query->where('ord_state', $search_data['ord_state']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_wor_state'])) {
                        $query->where('ord_wor_state', $search_data['ord_wor_state']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_payment_way'])) {
                        $query->where('ord_payment_way', $search_data['ord_payment_way']);
                    }
                })
                ->where(function ($query) use ($search_data) { //备注
                    if (!empty($search_data['ord_remark'])) {
                        $query->where('ord_remark', 'like', '%' . $search_data['ord_remark'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //创建时间
                    // 如果选择开始时间并且选择结束时间
                    if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                        $query->whereBetween('ord_create_time', [$search_data['create_time_start'], $search_data['create_time_end'] . ' 23:59:59']);
                    } else {
                        // 如果选择开始时间
                        if (!empty($search_data['create_time_start'])) {
                            $query->where('ord_create_time', '>=', $search_data['create_time_start']);
                        } else {
                            // 如果选择结束时间
                            if (!empty($search_data['create_time_end'])) {
                                $query->where('ord_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                            }
                        }
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_form_type'])) {
                        $query->where('ord_form_type', $search_data['ord_form_type']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['orcl_shipment_party'])) {
                        $query->where('orcl_shipment_party', $search_data['orcl_shipment_party']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_service_shop_id'])) {
                        $query->where('ord_service_shop_id', $search_data['ord_service_shop_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_client_id'])) {
                        $query->where('ord_client_id', $search_data['ord_client_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //实际金额区间搜索
                    // 如果选择最小钱数并且选择最大钱数
                    if (!empty($search_data['min_price']) && !empty($search_data['max_price'])) {
                        $query->whereBetween('ord_actual_price', [$search_data['min_price'], $search_data['max_price']]);
                    } else {
                        // 如果选择最小钱数
                        if (!empty($search_data['min_price'])) {
                            $query->where('ord_actual_price', '>=', $search_data['min_price']);
                        } else {
                            // 如果选择最大钱数
                            if (!empty($search_data['max_price'])) {
                                $query->where('ord_actual_price', '<=', $search_data['max_price']);
                            }
                        }
                    }
                })
                ->where(function ($query) use ($search_data) { //检索编码
                    if (!empty($search_data['goo_goods_encode'])) {
                        $query->where('orgt_goods_encode', 'like', '%' . $search_data['goo_goods_encode'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //速电单号（第三方系统单号）
                    if (!empty($search_data['ord_other_system_number'])) {
                        $query->where('ord_other_system_number', 'like', '%' . $search_data['ord_other_system_number'] . '%');
                    }
                })
                ->select('ord_id', 'ord_create_id', 'ord_order_number', 'ord_goods_quantity', 'ord_actual_price', 'ord_payment_way', 'ord_state', 'ord_wor_state', 'ord_wor_quantity', 'ord_type', 'ord_service_type', 'orcl_channel_unit', 'orcl_name', 'orcl_phone', 'orcl_car_num', 'orcl_province', 'orcl_city', 'orcl_county', 'orcl_address', 'ord_remark', 'ord_create_time', 'ord_order_price', 'ord_delete', 'ord_plus_minus', 'ord_service_shop_id', 'orcl_order_type', 'orcl_consent_state', 'orcl_consent_type', 'orcl_reminder_state', 'ord_order_state', 'orcl_assign_price', 'orcl_plus_minus', 'ord_order_plus_minus', 'orcl_shipment_party', 'orcl_rescue_service_price', 'orcl_rescue_collection_price', 'ord_service_sepr_id', 'orcl_client_id', 'orcl_appoint_time', 'orcl_appoint_remark', 'ord_ware_id', 'ord_other_system_number', 'ord_client_id', 'orcl_chin_type')
                ->orderBy('ord_id', 'desc')
                ->paginate($this->show_count);
        } else {
            $orderby_type = 'desc'; //排序类型，默认倒序查询
            // 当查询待接单状态订单时，按正序查询
            if (!empty($request['ord_wor_state']) && $request['ord_wor_state'] == 7) {
                $orderby_type = 'asc'; //默认排序类型
            }
            $list_data = DB::table('order as ord')
                ->leftJoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
                ->where('ord_cid', $user_info->adm_cid)
                ->where('ord_superior_shop_id', $shop_id)
                ->where('ord_collection_bill', 1) //是否代收账单：1正常订单2代收账单
                ->where(function ($query) use ($search_data) { //仓库名称
                    if (!empty($search_data['ware_id'])) {
                        $query->where('ord_ware_id', $search_data['ware_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //业务员搜索
                    if (!empty($search_data['orcl_adm_id'])) {
                        $query->where('chun_adm_id', $search_data['orcl_adm_id'])
                            ->where('ord_type', 2);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_order_number'])) {
                        $query->where('ord_order_number', 'like', '%' . $search_data['ord_order_number'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['orcl_name'])) {
                        $query->where('orcl_name', 'like', '%' . $search_data['orcl_name'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['orcl_phone'])) {
                        $query->where('orcl_phone', 'like', '%' . $search_data['orcl_phone'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['orcl_car_num'])) {
                        $query->where('orcl_car_num', 'like', '%' . $search_data['orcl_car_num'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //车型
                    if (!empty($search_data['orcl_car_vehicle_type'])) {
                        $query->where('orcl_car_vehicle_type', 'like', '%' . $search_data['orcl_car_vehicle_type'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_type'])) {
                        $query->where('ord_type', $search_data['ord_type']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_service_type'])) {
                        $query->where('ord_service_type', $search_data['ord_service_type']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_create_id'])) {
                        $query->where('ord_create_id', $search_data['ord_create_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_state'])) {
                        $query->where('ord_state', $search_data['ord_state']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_wor_state'])) {
                        $query->where('ord_wor_state', $search_data['ord_wor_state']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_payment_way'])) {
                        $query->where('ord_payment_way', $search_data['ord_payment_way']);
                    }
                })
                ->where(function ($query) use ($search_data) { //备注
                    if (!empty($search_data['ord_remark'])) {
                        $query->where('ord_remark', 'like', '%' . $search_data['ord_remark'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //铺货类型：1是铺货2不是铺货
                    if (!empty($search_data['orcl_chin_type'])) {
                        $query->where('orcl_chin_type', $search_data['orcl_chin_type']);
                    }
                })
                ->where(function ($query) use ($search_data) { //创建时间
                    // 如果选择开始时间并且选择结束时间
                    if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                        $query->whereBetween('ord_create_time', [$search_data['create_time_start'], $search_data['create_time_end'] . ' 23:59:59']);
                    } else {
                        // 如果选择开始时间
                        if (!empty($search_data['create_time_start'])) {
                            $query->where('ord_create_time', '>=', $search_data['create_time_start']);
                        } else {
                            // 如果选择结束时间
                            if (!empty($search_data['create_time_end'])) {
                                $query->where('ord_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                            }
                        }
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_form_type'])) {
                        $query->where('ord_form_type', $search_data['ord_form_type']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['orcl_shipment_party'])) {
                        $query->where('orcl_shipment_party', $search_data['orcl_shipment_party']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_service_shop_id'])) {
                        $query->where('ord_service_shop_id', $search_data['ord_service_shop_id']);
                    }
                })
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['ord_client_id'])) {
                        $query->where('ord_client_id', $search_data['ord_client_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //实际金额区间搜索
                    // 如果选择最小钱数并且选择最大钱数
                    if (!empty($search_data['min_price']) && !empty($search_data['max_price'])) {
                        $query->whereBetween('ord_actual_price', [$search_data['min_price'], $search_data['max_price']]);
                    } else {
                        // 如果选择最小钱数
                        if (!empty($search_data['min_price'])) {
                            $query->where('ord_actual_price', '>=', $search_data['min_price']);
                        } else {
                            // 如果选择最大钱数
                            if (!empty($search_data['max_price'])) {
                                $query->where('ord_actual_price', '<=', $search_data['max_price']);
                            }
                        }
                    }
                })
                ->where(function ($query) use ($search_data) { //速电单号（第三方系统单号）
                    if (!empty($search_data['ord_other_system_number'])) {
                        $query->where('ord_other_system_number', 'like', '%' . $search_data['ord_other_system_number'] . '%');
                    }
                })
                ->select('ord_id', 'ord_create_id', 'ord_order_number', 'ord_goods_quantity', 'ord_actual_price', 'ord_payment_way', 'ord_state', 'ord_wor_state', 'ord_wor_quantity', 'ord_type', 'ord_service_type', 'orcl_channel_unit', 'orcl_name', 'orcl_phone', 'orcl_car_num', 'orcl_province', 'orcl_city', 'orcl_county', 'orcl_address', 'ord_remark', 'ord_create_time', 'ord_order_price', 'ord_delete', 'ord_service_shop_id', 'orcl_order_type', 'orcl_consent_state', 'orcl_consent_type', 'orcl_reminder_state', 'ord_order_state', 'orcl_assign_price', 'orcl_plus_minus', 'ord_order_plus_minus', 'orcl_shipment_party', 'orcl_rescue_service_price', 'orcl_rescue_collection_price', 'ord_service_sepr_id', 'orcl_client_id', 'orcl_appoint_time', 'orcl_appoint_remark', 'ord_ware_id', 'ord_other_system_number', 'ord_client_id', 'orcl_chin_type')
                ->orderBy('ord_id', $orderby_type)
                ->paginate($this->show_count);
        }
        $ord_service_shop_id = [];
        $virtual_shop_id = [];
        $list_items = $list_data->items();

        if ($list_items) {
            $ord_id = array_column($list_items, 'ord_id'); //订单id
            $ord_create_id = array_unique(array_column($list_items, 'ord_create_id')); //录单人id
            $ord_service_sepr_id = array_unique(array_column($list_items, 'ord_service_sepr_id')); //服务项目id
            $ord_ware_id = array_unique(array_column($list_items, 'ord_ware_id')); //仓库id
            $ord_client_id = array_unique(array_column($list_items, 'ord_client_id')); //选择的客户id，会员id/单位id

            // 查询商品信息
            $order_goods = DB::table('order_goods as orgo')
                ->leftjoin('goods as goo', 'goo.goo_id', '=', 'orgo.orgo_goo_id')
                ->whereIn('orgo_ord_id', $ord_id)
                ->select('orgo_ord_id', 'orgo_goo_id', 'orgo_goo_name', 'orgo_goo_goods_encode', 'orgo_goo_price', 'orgo_goo_quantity', 'orgo_is_recycle', 'orgo_collection_price', 'orgo_state', 'orgo_can_assign_quantity', 'orgo_goo_type', 'orgo_recycle_price', 'orgo_recycle_quantity', 'orgo_tem_goo_name as tem_goo_name', 'orgo_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);
            }
            // 查询备注信息
            $order_reamrks = DB::table('order_remarks')
                ->whereIn('orre_ord_id', $ord_id)
                ->select('orre_create_adm_name', 'orre_content', 'orre_time', 'orre_ord_id', 'orre_module')
                ->orderby('orre_id', 'desc')
                ->get();

            // 查询服务项目信息
            $find_sepr = DB::table('service_project')
                ->whereIn('sepr_id', $ord_service_sepr_id)
                ->select('sepr_id', 'sepr_name')
                ->get();

            // 查询录单人信息
            $find_adm = DB::table('admin')
                ->whereIn('adm_id', $ord_create_id)
                ->pluck('adm_name', 'adm_id')->toArray();

            // 查找操作记录
            $order_log = DB::table('order_log')
                ->whereIn('orlo_ord_id', $ord_id)
                ->orderBy('orlo_id', 'desc')
                ->select('orlo_ord_id', 'orlo_time', 'orlo_create_adm_name', 'orlo_content')
                ->get();

            // 查询客户单位
            $channel = DB::table('channel_unit')
                ->whereIn('chun_id', $ord_client_id)
                ->where('chun_shop_id', $shop_id)
                ->where('chun_state', '1')
                ->pluck('chun_unit_name', 'chun_id')
                ->toArray();
            // 查找仓库id对应的仓库名称
            $find_ware_data = DB::table('warehouse')
                ->whereIn('ware_id', $ord_ware_id)
                ->where('ware_shop_id', $user_info->adm_shop_id)
                ->pluck('ware_name', 'ware_id')
                ->toArray();
            foreach ($list_items as $key => $value) {
                if ($value->ord_wor_state == '7') {
                    $list_items[$key]->orcl_name = substituteCharacter($list_items[$key]->orcl_name);
                    $list_items[$key]->orcl_phone = substr_replace($list_items[$key]->orcl_phone, '****', 3, 8);
                    $list_items[$key]->orcl_car_num = substr_replace($list_items[$key]->orcl_car_num, '****', 3, 9);
                    $list_items[$key]->orcl_city = '***';
                    $list_items[$key]->orcl_county = '***';
                    $list_items[$key]->orcl_address = '***';
                }
                if ($value->orcl_shipment_party == 4) {
                    $virtual_shop_id[] = $value->ord_service_shop_id;
                } else {
                    $ord_service_shop_id[] = $value->ord_service_shop_id;
                }
                if ($value->ord_create_id) {
                    $list_items[$key]->adm_name = $find_adm[$value->ord_create_id];
                } else {
                    $list_items[$key]->adm_name = '';
                }
                // 客户单位名称
                if (isset($channel[$value->ord_client_id])) {
                    $list_items[$key]->orcl_channel_unit = $channel[$value->ord_client_id];
                } else {
                    if ($value->ord_type == 3) {
                        $list_items[$key]->orcl_channel_unit = '速电快保';
                    } else {
                        $list_items[$key]->orcl_channel_unit = $value->orcl_channel_unit;
                    }
                }
                // 仓库
                if ($value->ord_ware_id == '0') {
                    $list_items[$key]->ware_name = '';
                } else {
                    $list_items[$key]->ware_name = $find_ware_data[$value->ord_ware_id];
                }
                unset($list_items[$key]->ord_ware_id);
                unset($list_items[$key]->ord_client_id);
            }

            // 查找服务门店id
            $shop_name = DB::table('shop')
                ->whereIn('shop_id', $ord_service_shop_id)
                ->select('shop_id', 'shop_store_name', 'shop_type')
                ->get();
            // 查找虚拟加盟店数据
            $virtual_shop = DB::table('virtual_shop')
                ->whereIn('vish_id', $virtual_shop_id)
                ->get(['vish_id', 'vish_store_name']);
        } else {
            $order_goods = [];
            $order_log = [];
            $shop_name = [];
            $order_reamrks = [];
            $virtual_shop = [];
            $find_sepr = [];
        }

        $state_count = DB::table('order')
            ->where('ord_cid', $user_info->adm_cid)
            ->where('ord_superior_shop_id', $shop_id)
            ->where('ord_delete', 1)
            ->select(DB::raw('count(*) as count, ord_wor_state'))
            ->groupBy('ord_wor_state')
            ->get();
        // 查询门店打印模板
        $shpt_data = DB::table('shop_print_template')
            ->where('shpt_shop_id', $user_info->adm_shop_id)
            ->whereIn('shpt_print_type', [4, 5, 6])
            ->where('shpt_delete', 1)
            ->select('shpt_id', 'shpt_print_type', 'shpt_isdefault')
            ->get()->toArray();
        if (empty($shpt_data)) {
            $shpt_data = [];
        }
        $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_items;                        //返回数据
        $data_info['order_goods'] = $order_goods;                //订单商品数据
        $data_info['state_count'] = $state_count;
        $data_info['order_log'] = $order_log;                    //操作记录
        $data_info['shop_name'] = $shop_name;                    //门店名称
        $data_info['order_reamrks'] = $order_reamrks;            //订单备注
        $data_info['virtual_shop'] = $virtual_shop;              //虚拟加盟店
        $data_info['find_sepr'] = $find_sepr;                    //服务项目
        $data_info['now_time'] = date('Y-m-d H:i:s');            //当前时间
        $data_info['shpt_data'] = $shpt_data;                    //模板id

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info, 'list_button'=>$list_button]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    // 订单列表-检索编码搜索
    public function goodsIndex($user_info, $shop_id, $search_data)
    {
        set_time_limit(0);

        $list_items = DB::table('order_goods')
            ->where('orgo_state', '!=', 2)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_goods_encode'])) {
                    $query->where('orgo_goo_goods_encode', $search_data['goo_goods_encode']);
                }
            }) //商品检索编码
            ->select('orgo_ord_id', 'orgo_goo_name', 'orgo_goo_goods_encode', 'orgo_order_number')
            ->groupBy('orgo_order_number')
            ->get()->toArray();
        foreach ($list_items as $key => $value) {
            // 查询该单是否存在
            $orgt_id = DB::table('order_goods_temporary')
                ->where('orgt_ord_id', $value->orgo_ord_id)
                ->where('orgt_type', 1)
                ->where('orgt_adm_id', $user_info->adm_id)
                ->value('orgt_id');
            if (empty($orgt_id)) {
                $orgt_data['orgt_ord_id'] = $value->orgo_ord_id; //订单id
                $orgt_data['orgt_order_number'] = $value->orgo_order_number; //订单单号
                $orgt_data['orgt_adm_id'] = $user_info->adm_id; //操作人
                $orgt_data['orgt_goods_encode'] = $value->orgo_goo_goods_encode; //检索编码
                $orgt_data['orgt_type'] = 1; //类型：1订单2工单
                $orgt_data['orgt_update_time'] = date('Y-m-d H:i:s');
                $orgt_id = DB::table('order_goods_temporary')->insert($orgt_data);
            }
        }
    }

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

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

        // 订单详情
        $order_res = Order::info(
            $user_info,
            $request
        );
        return response()->json($order_res);
    }

    // 门店结算后核对更改为确认
    private function storesCheck($user_info, $request)
    {
        // 判断当前结款明细是否存在
        $settlement_data = DB::table('accounting_settlement')
            ->where('acset_id', $request['acset_id'])
            ->first(['acset_id', 'acset_original_number', 'acset_type', 'acset_state', 'acset_original_id', 'acset_inex_type', 'acset_actual_price', 'acset_zero_price', 'acset_acti_id', 'acset_payment_type', 'acset_merge_type', 'acset_price', 'acset_number', 'acset_zero_plus_minus', 'acset_price']);
        if (empty($settlement_data)) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'当前结款明细不存在'];
        }
        if ($settlement_data->acset_state == 2) {
            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. 更改状态、汇款时间、备注
        $update_data['acset_state'] = 2; //状态：1未核对2已核对
        $update_data['acset_affirm_time'] = date('Y-m-d H:i:s'); //确认时间
        $update_data['acset_remit_time'] = $request['acset_with_time']; //汇款时间
        $update_data['acset_remark'] = isset($request['acset_remark']) ? $request['acset_remark'] : ''; //备注
        $update_data['acset_update_time'] = date('Y-m-d H:i:s'); //更新时间
        $update_data['acset_adm_id'] = $user_info->adm_id;
        $acset_res = DB::table('accounting_settlement')
            ->where('acset_id', $request['acset_id'])
            ->update($update_data);
        // 如果类型是订单代收
        if ($settlement_data->acset_type == 9) {
            $type = DB::table('receivable_credit')
                ->where('recr_original_id', $settlement_data->acset_original_id)
                ->where('recr_original_number', $settlement_data->acset_original_number)
                ->where('recr_account_type', 2)
                ->value('recr_leisurely_type');
            if ($type == 1) {
                $type = 2;
            }
            if ($type == 3) {
                $type = 4;
            }
            $leisurely_data['recr_leisurely_type'] = $type;
            $leisurely_data['recr_update_time'] = date('Y-m-d H:i:s');
            // 如果等于4把状态改为消核
            if ($type == 4) {
                $leisurely_data['recr_state'] = 2;
            }
            $leisurely_type = DB::table('receivable_credit')
                ->where('recr_original_id', $settlement_data->acset_original_id)
                ->where('recr_original_number', $settlement_data->acset_original_number)
                ->where('recr_account_type', 2)
                ->update($leisurely_data);
        } else {
            $leisurely_type = true;
        }
        // 是否操作科目数据1操作  2不操作
        $deduction = 1;
        // acset_payment_type 结款类型1.抹零 2.分期结款 3.预收款抵账4正常5收款6还款
        // acset_type单据类型1订单结算2订单账单3工单账单4采购账单5销售账单6预收款7采购入库单现金8预付款9订单代收10采购入库单预付款11订单退款12工单代收13订单完成后结算14非实物开单15.订单冲单16.加盟店订单收款17.加盟店订单代收18.工单结算19.旧货回收20售后单结算21销售出库单22采购单23采购退货单24采购款到发货(预付款)25批量结算26期初账单
        // $deduction 1操作科目数据  2不操作科目数据
        if ($deduction == 1) {
            // 2. 将结款明细中的金额，在对应的科目中添加/减去，是以汇款时间为准
            $acti_res = AccountSubject::Subject(
                $user_info, //用户信息
                $settlement_data->acset_inex_type, //类型：1借(汇入)2贷(汇出)
                $settlement_data->acset_actual_price, //金额
                // $settlement_data->acset_acti_id,//科目id
                !empty($request['recr_acti_id']) ? $request['recr_acti_id'] : $settlement_data->acset_acti_id, //科目id
                $request['acset_with_time'] //汇款时间
            );
            if ($acti_res['code'] == 500) {
                DB::rollBack();
                return response()->json($acti_res);
            } else {
                $acti_res = true;
            }
        } else {
            $acti_res = true;
        }
        // 订单结算核对之后修改订单状态
        if ($settlement_data->acset_type == 1) {
            $order_update = DB::table('order')
                ->where('ord_id', $settlement_data->acset_original_id)
                ->where('ord_order_number', $settlement_data->acset_original_number)
                ->update(['ord_state' => 3, 'ord_update_time' => date('Y-m-d H:i:s')]);
        } else {
            $order_update = true;
        }

        // 订单账单核对完之后修改此账单下订单状态
        if ($settlement_data->acset_type == 2) {
            $order_bill_update = DB::table('order')
                ->where('ord_orbi_id', $settlement_data->acset_original_id)
                ->update(['ord_state' => 3, 'ord_update_time' => date('Y-m-d H:i:s')]);
        } else {
            $order_bill_update = true;
        }

        // 3. 将应收账款中对应的数据改为核销状态
        // acset_type 单据类型1订单结算2订单账单3工单账单4采购账单5销售账单6预收款7采购入库单现金8预付款9订单代收10采购入库单预付款11订单退款12工单代收13订单完成后结算14非实物开单15.订单冲单16.加盟店订单收款17.加盟店订单代收18.工单结算19.旧货回收20售后单结算21销售出库单22采购单23采购退货单24采购款到发货(预付款)25批量结算26期初账单
        // recr_type 类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 6.销售账单 7.销售出库单 8非实物开单 9.账单冲红 10订单冲单 11.加盟店订单收款 12.加盟店订单代收13.旧货回收14售后单15采购单16采购退货单17采购款到发货(预付款)18期初账单
        $recr_account_type = 0;
        switch ($settlement_data->acset_type) {
            case '1':
                $recr_type = 1;
                break;
            case '9': //订单代收
                $recr_type = 3; //订单账单
                $recr_account_type = 2; // 2受托代收（订单代收）
                break;
            case '11': //订单退款
                $recr_type = 3; //订单账单
                $recr_account_type = 10; //10订单退款
                break;
            case '12': //工单代收
                $recr_type = 4; //4工单账单
                $recr_account_type = 3; //3委托代收（工单代收）
                break;
            case '13': //订单完成后结算
                $recr_type = 3; //3.订单账单
                $recr_account_type = 1; //1订单收款
                break;
            default:
                return ['code'=>500, 'msg'=>'error', 'data'=>'核对失败1'];
                break;
        }
        if (config('apiu8cloud.CODE_STARTS') && in_array($user_info->adm_shop_id, config('apiu8cloud.u8cloud_shop'))) {
            $request_voucher['subjcode'] = $request['subjcode']; //会计科目
            $request_voucher['recr_acti_id'] = $request['recr_acti_id']; //银行账号id
            if (isset($request['recr_yet_receipt']) && !empty($request['recr_yet_receipt'])) {
                // 分多次付款
                $request_voucher['voucher_price'] = $request['recr_yet_receipt']; //确认金额
            } else {
                $request_voucher['voucher_price'] = $settlement_data->acset_actual_price / 100; //结款明细金额
            }
            $settlement_data->acset_id = $request['acset_id'];
            $return = AccountingSettlement::accountVoucher($user_info, (array)$settlement_data, $request_voucher); //调用u8接口
            if ($return['code'] == 500) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'凭证上传失败！'];
            }
        }
        if ($recr_type == 1) { //销售订单
            // 3.1 判断单据类型：订单结算类型的可以直接把应收账款改为核销状态
            $recr_update['recr_state'] = 2; //状态：1.未核销 2.已核销
            $recr_update['recr_update_time'] = date('Y-m-d H:i:s');
            $recr_res = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $shop_id)
                ->where('recr_type', $recr_type)
                ->where('recr_original_id', $settlement_data->acset_original_id)
                ->where('recr_original_number', $settlement_data->acset_original_number)
                ->update($recr_update);
        } else {
            if ($recr_account_type == 10 || $recr_account_type == 1) {
                // 订单退款类型核对，或者是订单完成后结算，对应的应收账款改成已核销状态，
                // 对应的订单改成已核销状态
                if ($settlement_data->acset_merge_type == 2) {
                    $type = [$recr_account_type, 2];
                } else {
                    $type = [$recr_account_type];
                }
                $find_recr_data = DB::table('receivable_credit')
                    ->where('recr_cid', $user_info->adm_cid)
                    ->where('recr_shop_superior_id', $shop_id)
                    ->where('recr_type', $recr_type)
                    ->whereIn('recr_account_type', $type)
                    ->where('recr_original_id', $settlement_data->acset_original_id)
                    ->where('recr_original_number', $settlement_data->acset_original_number)
                    ->select('recr_id', 'recr_settle_price')
                    ->get()->toArray();
                foreach ($find_recr_data as $key => $value) {
                    $recr_update['recr_state'] = 2; //状态：1.未核销 2.已核销
                    $recr_update['recr_yet_receipt'] = $value->recr_settle_price; //已收金额
                    $recr_update['recr_update_time'] = date('Y-m-d H:i:s');
                    $recr_edit_res = DB::table('receivable_credit')
                        ->where('recr_id', $value->recr_id)
                        ->update($recr_update);
                }
                $ord_edit_data['ord_state'] = 3; //状态：1.未核销 2.已核销
                $ord_edit_data['ord_update_time'] = date('Y-m-d H:i:s');
                $ord_res = DB::table('order')
                    ->where('ord_cid', $user_info->adm_cid)
                    ->where('ord_superior_shop_id', $shop_id)
                    ->where('ord_id', $settlement_data->acset_original_id)
                    ->where('ord_order_number', $settlement_data->acset_original_number)
                    ->update($ord_edit_data);
                if ($recr_edit_res && $ord_res) {
                    $recr_res = true;
                } else {
                    $recr_res = false;
                }
            } elseif ($recr_account_type == 2) {
                // $recr_res = true;
                $recr_update['recr_yet_receipt'] = $settlement_data->acset_actual_price; //已收金额
                $recr_update['recr_state'] = 2; //状态：1.未核销 2.已核销
                $recr_update['recr_update_time'] = date('Y-m-d H:i:s');
                $recr_update['recr_settle_time'] = $request['acset_with_time']; //结款时间
                $recr_res = DB::table('receivable_credit')
                    ->where('recr_cid', $user_info->adm_cid)
                    ->where('recr_shop_superior_id', $shop_id)
                    ->where('recr_type', $recr_type)
                    ->where('recr_account_type', $recr_account_type)
                    ->where('recr_original_id', $settlement_data->acset_original_id)
                    ->where('recr_original_number', $settlement_data->acset_original_number)
                    ->update($recr_update);
            } else {
                // 订单账单
                if ($recr_type == 3 && $recr_account_type == 0) {
                    $sequence_res = $this->checkSequence($settlement_data->acset_original_id, $request['acset_id'], 1);
                    if (!empty($sequence_res)) {
                        return ['code'=>500, 'msg'=>'error', 'data'=>'请按照账单结款顺序进行确认'];
                    }
                }
                $not_price = 0;
                $recr = DB::table('receivable_credit')
                    ->where('recr_type', $recr_type)
                    ->where('recr_original_number', $settlement_data->acset_original_number)
                    ->orderBy('recr_id', 'desc')
                    ->select('recr_yet_receipt', 'recr_zero_price', 'recr_settle_price', 'recr_account_type', 'recr_id', 'recr_paid_price')
                    ->first();

                if ($settlement_data->acset_zero_plus_minus == 1) {
                    $not_price = $not_price - $settlement_data->acset_zero_price;
                } else {
                    $not_price = $not_price + $settlement_data->acset_zero_price;
                }
                $settle_price = $settlement_data->acset_actual_price + $recr->recr_paid_price + $not_price;
                $recr_update['recr_update_time'] = date('Y-m-d H:i:s');
                if ($settle_price == $recr->recr_settle_price || !empty($settlement_data->acset_zero_price)) {
                    $recr_update['recr_state'] = 2; //状态：1.未核销 2.已核销
                    $recr_update['recr_settle_time'] = $request['acset_with_time']; //结款时间
                    $recr_update['recr_paid_price'] = $recr->recr_settle_price; //已结金额
                }
                $recr_update['recr_paid_price'] = $recr->recr_paid_price + $settlement_data->acset_actual_price + $not_price;
                $recr_res = DB::table('receivable_credit')
                    ->where(function ($query) use ($recr_type, $settlement_data) {
                        $query->where('recr_type', $recr_type)
                            ->where('recr_original_id', $settlement_data->acset_original_id)
                            ->where('recr_original_number', $settlement_data->acset_original_number);
                    }) //账单相关的应收账款
                    ->orwhere(function ($query) use ($recr_type, $settlement_data) {
                        $query->where('recr_type', $recr_type)
                            ->where('recr_belongs_id', $settlement_data->acset_original_id);
                    }) //所属账单的订单应收账款
                    ->update($recr_update);
            }
        }
        if ($acset_res && $acti_res && $recr_res && $leisurely_type && $order_update && $order_bill_update) {
            return ['code'=>200, 'msg'=>'success', 'data'=>'核对成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'核对失败'];
        }
    }

    // 撤销结算
    public function cancelSettlement(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderController;
        $error_message = $verify_data->cancelSettlementtValidator($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_order = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->select('ord_order_number', 'ord_state', 'ord_actual_price')
            ->first();
        if ($find_order->ord_state != 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单不是已结算状态']);
        }

        // 判断一下结款明细是否核对,如果核对了,就不能撤销了
        $settlement_data = DB::table('accounting_settlement')
            ->where('acset_original_id', $request['ord_id']) //与单据类型对应的id
            ->where('acset_type', 1)
            ->value('acset_state');
        if ($settlement_data == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'结款明细已核对,不能撤销']);
        }

        // 1. 订单表改状态
        $ord_data['ord_state'] = 1; //结算状态1未结算2已结算
        $ord_data['ord_remark'] = $request['ord_remark'];
        $ord_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_res = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->update($ord_data);

        // 2.删除应收账款
        $del_credit = DB::table('receivable_credit')
            ->where('recr_original_id', $request['ord_id']) //与类型所对应的id
            ->where('recr_type', 1) //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 6.销售账单
            ->delete();

        // 3.删除结款明细
        $del_settlement = DB::table('accounting_settlement')
            ->where('acset_original_id', $request['ord_id'])
            ->where('acset_state', 1) //状态：1未核对2已核对
            ->where('acset_type', 1)
            ->delete();

        // 生成操作记录
        $cancel_Record = orderLog($user_info, $request['ord_id'], 0, '撤销结算');

        if ($ord_res && $cancel_Record && $del_settlement && $del_credit) {
            Common::addLog($user_info, getRealIp($request), '订单列表', '撤销结算', $find_order->ord_order_number . '撤销结算成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'撤销结算成功']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'撤销结算失败']);
        }
    }

    // 取消订单
    public function cancel(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderController;
        $error_message = $verify_data->cancelValidator($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_order = DB::table('order as ord')
            ->leftJoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
            ->where('ord_id', $request['ord_id'])
            ->where('ord_shop_id', $user_info->adm_shop_id)
            ->select('ord_order_number', 'ord_state', 'ord_delete', 'ord_wor_quantity', 'ord_wor_state', 'ord_service_type', 'ord_type', 'ord_client_id', 'ord_goods_quantity', 'ord_actual_price', 'ord_service_shop_id', 'ord_create_id', 'orcl_shipment_party', 'ord_ware_id', 'ord_create_time')
            ->first();
        if (empty($find_order)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单不存在！']);
        }
        if ($find_order->ord_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已结算，无法取消！']);
        }
        if ($find_order->ord_delete == 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_service_type == 6) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'结清单无法取消！']);
        }

        $create_year_month = substr($find_order->ord_create_time, 0, 7); //创建时间年月
        $now_year_month = date('Y-m'); //当前年月
        if ($now_year_month != $create_year_month && $user_info->adm_id != 46) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'不是本月订单，无法取消！']);
        }
        // 查询出该订单下所有的工单
        $find_work = DB::table('work_order')
            ->where('wor_order_id', $request['ord_id'])
            ->select('wor_delete', 'wor_id')
            ->get();
        // 验证当前订单下工单 是否已经全部取消
        foreach ($find_work as $key => $value) {
            if ($value->wor_delete == 1) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单存在未取消的工单']);
            }
            $wor_id[$key] = $value->wor_id;
        }
        if (isset($wor_id)) {
            // 验证 订单下 工单的商品是否都已回库
            $find_recycle = DB::table('recede_recycle')
                ->where('rec_source_type', 2) //来源类型1.售后 2.取消工单 3.页面新增
                ->where('rec_state', 1) //回收状态 1.未回收 2.已回收
                ->whereIn('rec_ord_id', $wor_id)
                ->first();
            if ($find_recycle) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单下有工单的商品未回库']);
            }
        }

        DB::beginTransaction();

        // 取消订单
        $order_res = Order::cancel(
            $user_info,
            $request,
            $find_order,
            1
        );
        // 生成操作记录
        $cancel_record = orderLog($user_info, $request['ord_id'], 0, '取消订单');
        // 添加备注
        orderRemark($user_info, $request['ord_id'], '', $request['remark'], '订单列表');

        $ord_data['ord_delete'] = 2; //是否删除：1正常订单2取消订单

        if ($order_res['code'] == 200 && $cancel_record) {
            // 添加新增订单信息的提示
            $inhi_data['inhi_original_adm_id'] = $find_order->ord_create_id; //原始单号创建人
            $inhi_data['inhi_original_id'] = $request['ord_id']; //原始单id
            $inhi_data['inhi_original_number'] = $find_order->ord_order_number; //原始单号
            $inhi_data['inhi_original_state'] = $ord_data['ord_delete']; //原始单状态
            $inhi_data['inhi_original_operation'] = '取消订单'; //操作
            $inhi_data['inhi_operation_state'] = 12; //操作状态：12取消订单
            addInformationHint($user_info, $inhi_data, 1);
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '订单列表', '取消订单', '取消订单：' . $find_order->ord_order_number . '成功');
            return response()->json($order_res);
        } else {
            DB::rollBack();
            return response()->json($order_res);
        }
    }

    // 终止订单
    public function termination(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderController;
        $error_message = $verify_data->infoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $find_order = DB::table('order as o')
            ->leftJoin('order_client as oc', 'oc.orcl_ord_id', '=', 'o.ord_id')
            ->where('ord_id', $request['ord_id'])
            ->select('ord_order_number', 'ord_state', 'ord_delete', 'ord_wor_quantity', 'ord_wor_state', 'ord_service_type', 'ord_type', 'ord_client_id', 'ord_goods_quantity', 'ord_actual_price', 'ord_service_shop_id', 'ord_create_id', 'orcl_shipment_party', 'ord_ware_id', 'ord_create_time')
            ->first();
        if ($find_order->ord_wor_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单不是待派工单状态，无法终止']);
        }
        if ($find_order->orcl_shipment_party == 4) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单为虚拟加盟店订单，无法终止']);
        }
        if ($find_order->ord_delete == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已经取消']);
        }
        if ($find_order->ord_type == 3) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单为速电订单，无法终止']);
        }

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

        $now_time = date('Y-m-d H:i:s');
        DB::beginTransaction();

        // 查询仓库id是否为移动仓库，移动仓库没有锁定库存
        // ware_type 类型：1固定仓2技师库3移动仓
        $ware_type = DB::table('warehouse')
            ->where('ware_id', $find_order->ord_ware_id)
            ->value('ware_type');
        // 不是虚拟加盟店、退货单的情况，需要取消锁定库存
        if ($find_order->orcl_shipment_party != 4 && $find_order->ord_service_type != 4 && $ware_type != 2 && $find_order->orcl_shipment_party != 5) {
            // 查询订单商品信息
            $find_order_goods = DB::table('order_goods')
                ->where('orgo_ord_id', $request['ord_id'])
                ->whereNotIn('orgo_state', [2, 3, 4])
                ->select('orgo_ware_id', 'orgo_waon_class', 'orgo_wago_id', 'orgo_goo_id', 'orgo_goo_quantity', 'orgo_goo_inventory', 'orgo_wafr_id', 'orgo_wafg_id')
                ->get()->toArray();

            $order_cawast_res = Order::cancelOrderChangeWafgstock(
                $user_info,
                $ware_type,
                $request,
                $find_order_goods,
                $find_order
            );
            if ($order_cawast_res['code'] == 500) {
                DB::rollBack();
                return response()->json($order_cawast_res);
            } else {
                $wagl_res = true;
            }
        } else {
            $wagl_res = true;
        }

        $ord_data['ord_wor_state'] = 10;
        $ord_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_res = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->update($ord_data);

        // 选择的客户id，对应的订单退换次数增加
        if ($find_order->ord_client_id) {
            if ($find_order->ord_type == 1) {
                $client_res = DB::table('member')
                    ->where('mem_id', $find_order->ord_client_id)
                    ->increment('mem_retreat_trade');
                // 会员列表订单总量减少
                $mem_id = DB::table('member')
                    ->where('mem_id', $find_order->ord_client_id)
                    ->decrement('mem_order_all');
            } else {
                $client_res = true;
                $mem_id = true;
            }
        } else {
            $client_res = true;
            $mem_id = true;
        }
        $orgo_id = DB::table('order_goods')
            ->where('orgo_ord_id', $request['ord_id'])
            ->select('orgo_goo_id')
            ->get()->toArray();

        // 更新订单商品表时间
        $edit_orgo_data['orgo_update_time'] = $now_time;
        if (!empty($orgo_id)) {
            $edit_orgo_res = DB::table('order_goods')
                ->where('orgo_ord_id', $request['ord_id'])
                ->update($edit_orgo_data);
        } else {
            $edit_orgo_res = true;
        }

        // 生成操作记录
        $cancel_record = orderLog($user_info, $request['ord_id'], 0, '终止订单');
        if ($ord_res && $edit_orgo_res && $cancel_record && $client_res && $mem_id && $wagl_res) {
            // 添加新增订单信息的提示
            // $inhi_data['inhi_original_adm_id'] = $find_order->ord_create_id;//原始单号创建人
            // $inhi_data['inhi_original_id'] = $request['ord_id'];//原始单id
            // $inhi_data['inhi_original_number'] = $find_order->ord_order_number;//原始单号
            // $inhi_data['inhi_original_state'] = $ord_data['ord_delete'];//原始单状态
            // $inhi_data['inhi_original_operation'] = '取消订单';//操作
            // $inhi_data['inhi_operation_state'] = 12;//操作状态：12取消订单
            // addInformationHint($user_info, $inhi_data, 1);
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '订单列表', '终止订单', '终止订单：' . $find_order->ord_order_number . '成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'终止订单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'终止订单失败']);
        }
    }

    // 完成订单-加盟店订单使用
    public function achieve(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderController;
        $error_message = $verify_data->infoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $find_order = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->select('ord_order_number', 'ord_state', 'ord_delete', 'ord_service_shop_id', 'ord_service_type')
            ->first();
        if ($find_order->ord_delete == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已经取消']);
        }
        if ($find_order->ord_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已结算，无法完成']);
        }
        if ($find_order->ord_service_type == 6) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'结清单无法取消']);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if ($find_order->ord_service_shop_id == $user_info->adm_shop_id) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单不是加盟店订单，无法完成']);
        }

        DB::beginTransaction();

        $ord_data['ord_wor_state'] = 4; //订单的工单状态1未派工单2服务中3售后中4已完成5无工单
        $ord_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_res = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->update($ord_data);
        // 生成操作记录
        $order_log_res = orderLog($user_info, $request['ord_id'], 0, '完成订单');
        if ($ord_res && $order_log_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '订单列表', '完成订单', '完成订单' . $find_order->ord_order_number . '成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'完成订单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'完成订单失败']);
        }
    }

    // 编辑
    public function edit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderController;
        $error_message = $verify_data->editShowValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 没有结算，没有派工单的可以编辑
        $order_data = DB::table('order as o')
            ->leftjoin('order_client as oc', 'oc.orcl_ord_id', '=', 'o.ord_id')
            ->leftjoin('order_label as ol', 'ol.orla_id', '=', 'o.ord_orla_id')
            ->where('ord_id', $request['ord_id'])
            ->select('ord_id', 'ord_orcl_id', 'ord_service_type', 'ord_state', 'ord_wor_quantity', 'ord_payment_way', 'ord_actual_price', 'ord_type', 'ord_remark', 'ord_ware_id', 'ord_client_id', 'ord_service_sepr_id', 'ord_service_adm_id', 'ord_orla_id', 'orla_name', 'orla_recycle_state', 'ord_service_shop_id', 'ord_order_number', 'ord_plus_minus', 'ord_order_plus_minus', 'orcl_shipment_party', 'orcl_rescue_assign_price', 'orcl_junk_type', 'orcl_whether_app', 'orcl_precise_lock', 'orcl_appoint_time', 'ord_delete', 'ord_wor_state', 'ord_create_time', 'ord_superior_shop_id as shop_id')
            ->first();
        if ($order_data->ord_state == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已结算不允许编辑']);
        }
        if ($order_data->ord_delete == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已取消，无法编辑']);
        }
        if ($order_data->ord_wor_quantity > 0) {
            // 工单数量大于0，已经派工单
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已经派工单，无法编辑']);
        }
        if ($order_data->ord_wor_state == 4) {
            // 发货单发货之后，退货单退货入库之后订单就是完成状态
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已经完成，无法编辑']);
        }
        $create_year_month = substr($order_data->ord_create_time, 0, 7); //创建时间年月
        $now_year_month = date('Y-m'); //当前年月
        if ($now_year_month != $create_year_month) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'不是本月订单，无法编辑！']);
        }
        $order_data->ord_service_adm_name = DB::table('admin')
            ->where('adm_id', $order_data->ord_service_adm_id)
            ->value('adm_name');

        // 判断发货单是否发货，已发货的不允许编辑
        $dego_type = DB::table('dispatch_bill')
            ->where('dego_order_type', 1)
            ->where('dego_wor_id', $request['ord_id'])
            ->where('dego_original_number', $order_data->ord_order_number)
            ->value('dego_type');
        if ($dego_type == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单的发货单已发货不允许编辑']);
        }

        // 判断退货单是否入库，已入库的不允许编辑
        $rec_type = DB::table('recede_recycle')
            ->where('rec_ord_id', $request['ord_id'])
            ->where('rec_ord_order_number', $order_data->ord_order_number)
            ->value('rec_state');
        if ($rec_type == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单的退货单已入库不允许编辑']);
        }

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

        if ($request['type'] == 1) { //获取页面数据
            // 获取订单数据
            if ($order_data->orcl_shipment_party == 4) {
                $find_shop = DB::table('virtual_shop')
                    ->where('vish_id', $order_data->ord_service_shop_id)
                    ->select('vish_store_name as shop_store_name')
                    ->first();
                $find_shop->shop_type = 4;
            } elseif ($order_data->orcl_shipment_party == 5) {
                $find_shop = DB::table('shop')
                    ->where('shop_id', $order_data->ord_service_shop_id)
                    ->select('shop_store_name', 'shop_type')
                    ->first();
            } else {
                $find_shop = DB::table('shop')
                    ->where('shop_id', $order_data->ord_service_shop_id)
                    ->select('shop_store_name', 'shop_type')
                    ->first();
                if ($order_data->orcl_shipment_party != 5) {
                    // 获取仓库数据
                    $find_ware = DB::table('warehouse')
                        ->where('ware_id', $order_data->ord_ware_id)
                        ->select('ware_name', 'ware_type')
                        ->first();
                    $order_data->ware_type = $find_ware->ware_type;
                }
                $order_data->ord_ware_name = $find_ware->ware_name;
            }

            $order_data->ord_service_shop_store_name = $find_shop->shop_store_name; //服务门店名称
            $order_data->ord_service_shop_type = $find_shop->shop_type; //服务门店类型

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

            $order_client_info = [];
            if ($order_data->ord_orcl_id) {
                // 客户信息
                $order_client_data = DB::table('order_client')
                    ->where('orcl_id', $order_data->ord_orcl_id)
                    ->select('orcl_channel_unit', 'orcl_name', 'orcl_phone', 'orcl_car_num', 'orcl_province', 'orcl_city', 'orcl_county', 'orcl_address', 'orcl_chin_type', 'orcl_collect_state', 'orcl_rescue_service_price', 'orcl_rescue_collection_price', 'orcl_standby_battery_type', 'orcl_shipment_party', 'orcl_assign_price', 'orcl_plus_minus', 'orcl_car_vehicle_type', 'orcl_rescue_assign_price', 'orcl_whether_app', 'orcl_precise_lock', 'orcl_appoint_time')
                    ->first();
                if ($order_data->ord_type == 2) {
                    $order_client_info = DB::table('channel_info')
                        ->where('chin_chun_id', $order_data->ord_client_id)
                        ->select('chin_level', 'chin_main_brand', 'chin_second_brand', 'chin_owe_day', 'chin_owe_money', 'chin_caution_day', 'chin_type', 'chin_remarks')
                        ->first();
                }
            } else {
                $order_client_data = [];
            }

            // 查询商品信息
            $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'])
                ->select('orgo_wago_id', 'orgo_goo_id', 'orgo_goo_name', 'orgo_goo_goods_encode', 'orgo_goo_price', 'orgo_goo_quantity', 'orgo_is_recycle', 'orgo_collection_price', 'orgo_goo_inventory', 'orgo_state', 'orgo_waon_class', 'orgo_goo_type', 'orgo_recycle_price', 'orgo_recycle_quantity', 'orgo_goo_ampere_hour', 'orgo_tem_goo_name as tem_goo_name', 'orgo_assign_price', 'goo_brse_id', 'goo_bra_name', 'goo_class', 'orgo_wafr_id', 'orgo_wafg_id')
                ->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_brse_id);
                unset($order_goods[$key]->goo_class);
            }

            return response()->json(['code'=>200, 'msg'=>'success', 'order_data'=>$order_data, 'order_client_data'=>$order_client_data, 'order_client_info'=>$order_client_info, 'order_goods'=>$order_goods]);
        }

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

        $goods_data = json_decode($request['goods_data'], true);
        $request_wago_id = [];
        $goo_all_quantity = 0;
        $neaten_wagl_data = []; //锁定库存数据
        $neaten_goods_data = []; //仓库商品数据
        // 判断提交的商品参数
        if (empty($goods_data)) {
            // 救援单的可以不选商品
            if ($request['ord_service_type'] != 7) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'请选择商品']);
            }
            // 查询仓库id是否为移动仓库，移动仓库没有锁定库存
            // ware_type 类型：1固定仓2技师库3移动仓
            $ware_type = DB::table('warehouse')
                ->where('ware_id', $order_data->ord_ware_id)
                ->value('ware_type');
            // 查询订单商品信息
            $find_orgo_data = DB::table('order_goods')
                ->where('orgo_ord_id', $request['ord_id'])
                ->whereNotIn('orgo_state', [2, 3, 4])
                ->select('orgo_ware_id', 'orgo_waon_class', 'orgo_wago_id', 'orgo_goo_id', 'orgo_goo_quantity', 'orgo_goo_inventory', 'orgo_wafr_id', 'orgo_wafg_id')
                ->get()->toArray();
            // 取消锁定库存
            $lock_turn_normal = Order::cancelOrderChangeWafgstock(
                $user_info,
                $ware_type,
                $request,
                $find_orgo_data,
                $order_data
            );
            // 仓库商品锁定表中没有商品数据默认删除
            $wagl_id = 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', $order_data->ord_order_number)
                ->value('wagl_id');
            if ($wagl_id) {
                $wagl_del = 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', $order_data->ord_order_number)
                    ->delete();
            } else {
                $wagl_del = true;
            }
            if ($lock_turn_normal['code'] == 500) {
                DB::rollBack();
                return ['code'=>500, 'msg'=>'error', 'data'=>'编辑订单失败5'];
            }
        } else {
            foreach ($goods_data as $key => $value) {
                if (!isset($value['wago_id'])) {
                    $value['wago_id'] = 0;
                    $goods_data[$key]['wago_id'] = 0;
                }

                if (!isset($value['wafg_id'])) {
                    $value['wafg_id'] = 0;
                    $goods_data[$key]['wafg_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']]['goo_quantity'] = $value['goo_quantity'];
                    }
                    // [仓库商品id]，用于锁定库存处理
                    if (isset($neaten_wagl_data[$value['wago_id']])) {
                        $neaten_wagl_data[$value['wago_id']]['goo_quantity'] += $value['goo_quantity'];
                    } else {
                        $neaten_wagl_data[$value['wago_id']]['goo_quantity'] = $value['goo_quantity'];
                    }
                    $request_wago_id[] = $value['wago_id'];
                    $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;
                }
            }
        }

        DB::beginTransaction();

        $find_orcl_data = DB::table('order_client')
            ->where('orcl_ord_id', $request['ord_id'])
            ->select('orcl_order_type', 'orcl_shipment_party')
            ->first();
        $order_type = $find_orcl_data->orcl_order_type;
        $order_data->orcl_shipment_party = $find_orcl_data->orcl_shipment_party;
        if ($order_data->orcl_shipment_party != 4 && $order_data->orcl_shipment_party != 5) { //不是虚拟加盟店发货
            // 编辑订单锁定商品库存
            $lock_edit_return['return_data'] = [];
            if (!empty($neaten_goods_data)) { //仓库
                $lock_edit_return = $this->editOrderLockGoodsStock($user_info, $request->all(), $order_data, $neaten_goods_data, $request_wago_id, $goo_all_quantity);
                if ($lock_edit_return['code'] == 500) {
                    DB::rollBack();
                    return response()->json($lock_edit_return);
                }
            }
        } else {
            // 虚拟加盟店订单只能选择服务单、救援单
            // ord_service_type 订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单 7救援单
            if (!in_array($request['ord_service_type'], [1, 7])) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'虚拟加盟店订单只能选择服务单、救援单！']);
            }
            $lock_edit_return['return_data'] = [];
        }
        // 编辑订单相关数据
        $ord_edit_return = $this->editOrderData($user_info, $request->all(), $order_data, $goods_data, $lock_edit_return['return_data']);
        $goods_data = $ord_edit_return['return_datas'];
        if ($ord_edit_return['code'] == 500) {
            DB::rollBack();
            return response()->json($ord_edit_return);
        }
        // 不是退货单
        if ($request['ord_service_type'] != 4 && $order_data->orcl_shipment_party != 4 && $order_data->orcl_shipment_party != 5) {
            if (!empty($goods_data)) {
                // 查询仓位商品锁定表
                $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', $request['ord_id'])
                    ->where('wfgl_original_number', $order_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'] = $request['ord_id']; //订单id
                                    $orgf_data[$orgf_wfgl_key]['orgf_order_number'] = $order_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'] = $request['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']);
                    }
                }
            }
            $n = 0;
            if (!empty($neaten_wagl_data)) {
                foreach ($neaten_wagl_data as $wago_id => $value) {
                    // 仓库商品锁定表
                    $wagl_data[$n]['wagl_shop_id'] = $user_info->adm_shop_id;
                    $wagl_data[$n]['wagl_ware_id'] = $request['ware_id'] ? $request['ware_id'] : 0;
                    $wagl_data[$n]['wagl_wafr_id'] = 0;
                    $wagl_data[$n]['wagl_wago_id'] = $wago_id;
                    $wagl_data[$n]['wagl_wafg_id'] = 0;
                    $wagl_data[$n]['wagl_original_id'] = $request['ord_id'];
                    $wagl_data[$n]['wagl_original_number'] = $order_data->ord_order_number;
                    $wagl_data[$n]['wagl_original_correlation_id'] = $request['ord_id']; //关联id：订单id/发货单id/调拨单id
                    $wagl_data[$n]['wagl_correlation_type'] = 1; //关联类型：1订单2发货单3调拨单
                    $wagl_data[$n]['wagl_type'] = 1; //  原始单类型：1订单2调拨单
                    $wagl_data[$n]['wagl_state'] = 1; //锁定状态：1下单锁定2出库解锁
                    $wagl_data[$n]['wagl_lock_quantity'] = $value['goo_quantity'];
                    $n++;
                }
            }
        }
        // 如果订单类型为发货单
        if ($request['ord_service_type'] == 5) {
            // 修改发货单商品数量
            $dibi_edit_return = $this->editOrderDispatchBill($user_info, $request->all(), $order_data, $goods_data);
            if ($dibi_edit_return['code'] == 500) {
                DB::rollBack();
                return response()->json($dibi_edit_return);
            }

            // 查询出当前订单的发货单
            $find_dego_data = DB::table('dispatch_bill')
                ->where('dego_order_type', 1)
                // ->where('dego_type', 4)//类型：1未出库2已出库3作废4锁定
                ->where('dego_wor_id', $request['ord_id'])
                ->where('dego_original_number', $order_data->ord_order_number)
                ->orderBy('dego_id', 'desc')
                ->first(['dego_id', 'dego_type', 'dego_out_ware_id', 'dego_count', 'dego_number']);
            if (!empty($wagl_data)) {
                foreach ($wagl_data as $key => $value) {
                    $wagl_data[$key]['wagl_original_correlation_id'] = $find_dego_data->dego_id; //关联id：订单id/发货单id/调拨单id
                    $wagl_data[$key]['wagl_correlation_type'] = 2; //关联类型：1订单2发货单3调拨单
                }
            }
        }

        // 仓库商品锁定表
        if (!empty($wagl_data)) {
            // 仓库商品锁定表中没有商品数据默认删除
            $wagl_id = 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', $order_data->ord_order_number)
                ->value('wagl_id');
            if ($wagl_id) {
                $wagl_del = 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', $order_data->ord_order_number)
                    ->delete();
            } else {
                $wagl_del = true;
            }
            // 仓库商品锁定表新增锁定商品
            $wagl_res = DB::table('warehouse_goods_lock')->insert($wagl_data);
            if (!$wagl_del || !$wagl_res) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'编辑订单失败2']);
            }
        }

        // 如果订单类型为退货单
        if ($request['ord_service_type'] == 4 && $order_data->orcl_shipment_party != 4) {
            // 修改退货单商品数量
            $rede_edit_return = $this->editOrderRecede($user_info, $request->all(), $order_data, $goods_data);
            if ($rede_edit_return['code'] == 500) {
                DB::rollBack();
                return response()->json($rede_edit_return);
            }
        }

        $ord_data = DB::table('order')
            ->leftjoin('order_client as oc', 'oc.orcl_ord_id', '=', 'order.ord_id')
            ->where('ord_id', $request['ord_id'])
            ->first(['ord_actual_price', 'ord_payment_way']);
        $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', $request['ord_id'])
                    ->update(['ord_order_state' => 10, 'ord_wor_state' => 12]);
            }
        }

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

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

    /**
     * [editOrderData 编辑订单相关数据]
     * @param  [type] $user_info  [用户信息]
     * @param  [type] $request    [编辑提交数据]
     * @param  [type] $order_data [订单信息]
     * @param  [type] $goods_data [订单提交的商品数据]
     * @return [type]             [description]
     */
    private function editOrderData(
        $user_info,
        $request,
        $order_data,
        $goods_data,
        $return_data
    ) {
        // 2. 编辑订单商品表数据
        // 2.1 删除原来的订单商品数据
        $orgo_del_res = DB::table('order_goods')
            ->where('orgo_ord_id', $request['ord_id'])
            ->delete();
        $update['orgf_delete'] = 2;
        $update['orgf_update_time'] = date('Y-m-d H:i:s');
        $orgo_del_res = DB::table('order_goods_freight')
            ->where('orgf_ord_id', $request['ord_id'])
            ->where('orgf_order_number', $order_data->ord_order_number)
            ->update($update);
        // 订单类型不是发货单
        if ($request['ord_service_type'] != 5) {
            // 查询发货单数据
            $find_dego_data = DB::table('dispatch_bill')
                ->where('dego_order_type', 1)
                ->where('dego_wor_id', $request['ord_id'])
                ->where('dego_original_number', $order_data->ord_order_number)
                ->orderBy('dego_id', 'desc')
                ->first(['dego_id', 'dego_type', 'dego_out_ware_id', 'dego_count', 'dego_number']);
            if (!empty($find_dego_data)) {
                // 删除发货单的商品
                $find_digo_data = DB::table('dispatch_goods')
                    ->where('digo_dego_id', $find_dego_data->dego_id)
                    ->delete();
                // 删除发货单的数据
                $del_dibi_res = DB::table('dispatch_bill')
                    ->where('dego_id', $find_dego_data->dego_id)
                    ->where('dego_order_type', 1)
                    ->delete();
            }
        }
        // 订单类型不是退货单
        if ($request['ord_service_type'] != 4) {
            // 查询退货单数据
            $find_rec_id = DB::table('recede_recycle')
                ->where('rec_state', 1)
                ->where('rec_ord_id', $request['ord_id'])
                ->where('rec_ord_order_number', $order_data->ord_order_number)
                ->value('rec_id');
            if (!empty($find_rec_id)) {
                // 删除退换回收商品数据
                $del_rego_res = DB::table('recede_goods')
                    ->where('rego_rec_id', $find_rec_id)
                    ->delete();
                // 删除退换入库客户表数据
                $del_recl_data = DB::table('recede_client')
                    ->where('recl_rec_id', $find_rec_id)
                    ->delete();
                // 删除退换回收数据
                $del_rec_data = DB::table('recede_recycle')
                    ->where('rec_id', $find_rec_id)
                    ->delete();
            }
        }

        // 2.2 添加新的订单商品数据
        $goo_all_quantity = 0; //商品总数量
        $goo_all_price = 0; //商品总金额
        $goo_collection_price = 0; //商品代收总金额
        // 救援单的服务项目金额
        $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;
        $orcl_rescue_assign_price = isset($request['orcl_rescue_assign_price']) ? $request['orcl_rescue_assign_price'] : 0;
        $goo_assign_all_price = 0; //商品派单总金额

        if (!empty($goods_data)) {
            $neaten_goods_data = []; //整理后的商品数据
            $n = 0;
            foreach ($goods_data as $key => $value) {
                if (!isset($value['goo_assign_price'])) {
                    $value['goo_assign_price'] = 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_name', 'goo_goods_encode', 'goo_type', 'goo_ampere_hour', 'goo_price', 'goo_fid', '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;
                    }
                }
                // goo_state 商品状态1.正常 2.删除3.回收的商品4.换货商品5.赠品商品6.备用电池7.临时商品8.旧货商品
                // 换货商品金额处理
                if ($value['goo_state'] == 1 || $value['goo_state'] == 5) {
                    // 订单商品
                    $goo_all_price += $value['goo_price'] * $value['goo_quantity'];
                    $goo_assign_all_price += $value['goo_assign_price'] * $value['goo_quantity'];

                    $goo_all_quantity += $value['goo_quantity']; //商品总数量
                    $goo_collection_price += $value['goo_collection_price'];
                    if ($request['orcl_shipment_party'] != 4) {
                    } else {
                        $cost_price = 0;
                        $sell_res = true;
                    }
                } elseif ($value['goo_state'] == 4) { //换货商品
                    return ['code'=>500, 'msg'=>'success', 'data'=>'换货单生成订单失败'];
                } elseif ($value['goo_state'] == 6) { //备用电池
                    $goo_all_quantity += $value['goo_quantity']; //商品总数量
                    $goo_all_price += $value['goo_price'] * $value['goo_quantity'];
                    $goo_collection_price += $value['goo_collection_price'];
                } elseif ($value['goo_state'] == 7) { //临时商品
                    $goo_all_price += $value['goo_price'] * $value['goo_quantity'];
                    $goo_all_quantity += $value['goo_quantity']; //商品总数量
                } elseif ($value['goo_state'] == 8) { //旧货商品
                    $goo_all_price += $value['goo_price'] * $value['goo_quantity'];
                    $goo_assign_all_price += $value['goo_assign_price'] * $value['goo_quantity'];
                    $goo_all_quantity += $value['goo_quantity']; //商品总数量
                    $goo_collection_price += $value['goo_collection_price']; //商品代收总金额
                }

                // 订单商品表
                $orgo_data[$key]['orgo_ord_id'] = $request['ord_id'];
                $orgo_data[$key]['orgo_order_number'] = $order_data->ord_order_number;
                $orgo_data[$key]['orgo_ware_id'] = $request['ware_id'] ? $request['ware_id'] : 0;
                $orgo_data[$key]['orgo_wago_id'] = $value['wago_id'];
                $orgo_data[$key]['orgo_wafr_id'] = isset($value['wafr_id']) ? $value['wafr_id'] : 0;
                $orgo_data[$key]['orgo_wafg_id'] = isset($value['wafg_id']) ? $value['wafg_id'] : 0;
                $orgo_data[$key]['orgo_waon_class'] = $value['goo_waon_class'];
                $orgo_data[$key]['orgo_actual_goo_id'] = $value['goo_id'];
                $orgo_data[$key]['orgo_goo_id'] = $value['goo_id'];

                $orgo_data[$key]['orgo_goo_price'] = $value['goo_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'] = $value['goo_inventory'];
                $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_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'] = $value['goo_state'];
                if ($request['orcl_shipment_party'] == 4 || $request['orcl_shipment_party'] == 5) {
                    $orgo_data[$key]['orgo_assign_price'] = $value['goo_assign_price'] * 100;
                }
                // 出库方为仓库
                if ($request['orcl_shipment_party'] == 1) {
                    // 获取订单商品成本价
                    $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_goo_cost = $orgo_goo_cost ?: 0;
                    $orgo_data[$key]['orgo_goo_cost'] = $orgo_goo_cost * 100; //商品成本
                }
            }
            foreach ($orgo_data as $key => $value) {
                $orgo_res = DB::table('order_goods')->insertGetId($orgo_data[$key]);
                $goods_data[$key]['orgo_id'] = $orgo_res;
            }
        } else {
            $orgo_res = true;
        }

        // 3. 编辑订单客户表数据
        if ($request['ord_type'] == '2') {
            $chun_adm_id = DB::table('channel_unit')
                ->where('chun_id', $request['ord_client_id'])
                ->value('chun_adm_id');
        } else {
            $chun_adm_id = 0;
        }
        // 判断是否更改客户信息
        if ($request['ord_client_id'] > 0) {
            $orcl_info = DB::table('order_client')
                ->where('orcl_id', $order_data->ord_orcl_id)
                ->select('orcl_order_type', 'orcl_join_wor_id', 'orcl_before_wor_state')
                ->first();
            $orcl_data['orcl_client_id'] = isset($request['ord_client_id']) ? $request['ord_client_id'] : '';
            $orcl_data['orcl_adm_id'] = $chun_adm_id;
            $orcl_data['orcl_channel_unit'] = isset($request['orcl_channel_unit']) ? $request['orcl_channel_unit'] : '';
            $orcl_data['orcl_name'] = $request['orcl_name'];
            $orcl_data['orcl_phone'] = $request['orcl_phone'];
            $orcl_data['orcl_car_num'] = isset($request['orcl_car_num']) ? $request['orcl_car_num'] : ''; //车牌号
            $orcl_data['orcl_car_vehicle_type'] = isset($request['orcl_car_vehicle_type']) ? $request['orcl_car_vehicle_type'] : ''; //车型
            $orcl_data['orcl_province'] = $request['orcl_province'];
            $orcl_data['orcl_city'] = $request['orcl_city'];
            $orcl_data['orcl_county'] = $request['orcl_county'];
            $orcl_data['orcl_address'] = $request['orcl_address'];
            // 铺货类型：1是铺货 2不是铺货
            $orcl_data['orcl_chin_type'] = isset($request['orcl_chin_type']) ? $request['orcl_chin_type'] : 2;
            $orcl_data['orcl_collect_state'] = $request['orcl_collect_state']; //技师收钱：0未选择1是2否
            $orcl_data['orcl_rescue_service_price'] = $orcl_rescue_service_price * 100;
            $orcl_data['orcl_rescue_collection_price'] = $orcl_rescue_collection_price * 100;
            $orcl_data['orcl_rescue_assign_price'] = $orcl_rescue_assign_price * 100;
            $orcl_data['orcl_update_time'] = date('Y-m-d H:i:s');
            $orcl_data['orcl_order_type'] = $orcl_info->orcl_order_type;
            $orcl_data['orcl_join_wor_id'] = $orcl_info->orcl_join_wor_id;
            $orcl_data['orcl_before_wor_state'] = $orcl_info->orcl_before_wor_state;
            $orcl_data['orcl_shipment_party'] = isset($request['orcl_shipment_party']) ? $request['orcl_shipment_party'] : 2;
            $orcl_data['orcl_junk_type'] = isset($request['orcl_junk_type']) ? $request['orcl_junk_type'] : 2; //是否为旧货1是2否
            $orcl_data['orcl_whether_app'] = isset($request['orcl_whether_app']) ? $request['orcl_whether_app'] : 1; //是否走技师流程1是2否
            $orcl_data['orcl_precise_lock'] = isset($request['precise_lock']) ? $request['precise_lock'] : 2; //精确打卡1是 2否
            if (isset($request['orcl_appoint_time'])) {
                $orcl_data['orcl_appoint_time'] = $request['orcl_appoint_time']; //预约时间
            }

            if ($request['ord_client_id'] == $order_data->ord_client_id) {
                // 原来已经添加了订单客户信息，更改客户信息
                $orcl_id = DB::table('order_client')
                    ->where('orcl_id', $order_data->ord_orcl_id)
                    ->update($orcl_data);
            } else {
                // 原来没有添加客户信息，添加客户信息
                DB::table('order_client')
                    ->where('orcl_ord_id', $request['ord_id'])
                    ->delete();
                $orcl_data['orcl_ord_id'] = $request['ord_id'];
                $orcl_id = DB::table('order_client')->insertGetId($orcl_data);

                $ord_edit_data['ord_orcl_id'] = $orcl_id;
            }
        } else {
            $orcl_info = DB::table('order_client')
                ->where('orcl_ord_id', $request['ord_id'])
                ->select('orcl_order_type', 'orcl_join_wor_id', 'orcl_before_wor_state')
                ->first();
            $orcl_data['orcl_client_id'] = isset($request['ord_client_id']) ? $request['ord_client_id'] : '';
            $orcl_data['orcl_adm_id'] = $chun_adm_id;
            $orcl_data['orcl_channel_unit'] = isset($request['orcl_channel_unit']) ? $request['orcl_channel_unit'] : '';
            $orcl_data['orcl_name'] = $request['orcl_name'];
            $orcl_data['orcl_phone'] = $request['orcl_phone'];
            $orcl_data['orcl_car_num'] = isset($request['orcl_car_num']) ? $request['orcl_car_num'] : '';
            $orcl_data['orcl_province'] = $request['orcl_province'];
            $orcl_data['orcl_city'] = $request['orcl_city'];
            $orcl_data['orcl_county'] = $request['orcl_county'];
            $orcl_data['orcl_address'] = $request['orcl_address'];
            // 铺货类型：1是铺货 2不是铺货
            $orcl_data['orcl_chin_type'] = isset($request['orcl_chin_type']) ? $request['orcl_chin_type'] : 2;
            $orcl_data['orcl_collect_state'] = $request['orcl_collect_state']; //技师收钱：0未选择1是2否
            $orcl_data['orcl_rescue_service_price'] = $orcl_rescue_service_price * 100;
            $orcl_data['orcl_rescue_collection_price'] = $orcl_rescue_collection_price * 100;
            $orcl_data['orcl_rescue_assign_price'] = $orcl_rescue_assign_price * 100;
            $orcl_data['orcl_update_time'] = date('Y-m-d H:i:s');
            $orcl_data['orcl_standby_battery_type'] = isset($request['orcl_standby_battery_type']) ? $request['orcl_standby_battery_type'] : 2;
            $orcl_data['orcl_order_type'] = $orcl_info->orcl_order_type;
            $orcl_data['orcl_join_wor_id'] = $orcl_info->orcl_join_wor_id;
            $orcl_data['orcl_before_wor_state'] = $orcl_info->orcl_before_wor_state;
            $orcl_data['orcl_shipment_party'] = $request['orcl_shipment_party']; //出库方1仓库2直营店3加盟店4虚拟加盟店
            $orcl_data['orcl_junk_type'] = isset($request['orcl_junk_type']) ? $request['orcl_junk_type'] : 2; //是否为旧货1是2否
            $orcl_data['orcl_whether_app'] = isset($request['orcl_whether_app']) ? $request['orcl_whether_app'] : 1; //是否走技师流程1是2否
            $orcl_data['orcl_precise_lock'] = isset($request['precise_lock']) ? $request['precise_lock'] : 2; //精确打卡1是 2否
            if (isset($request['orcl_appoint_time'])) {
                $orcl_data['orcl_appoint_time'] = $request['orcl_appoint_time']; //预约时间
            }
            if ($request['ord_client_id'] == $order_data->ord_client_id) {
                // 原来已经添加了订单客户信息，更改客户信息
                $orcl_id = DB::table('order_client')
                    ->where('orcl_id', $order_data->ord_orcl_id)
                    ->update($orcl_data);
            } else {
                // 原来没有添加客户信息，添加客户信息
                DB::table('order_client')
                    ->where('orcl_ord_id', $request['ord_id'])
                    ->delete();
                $orcl_data['orcl_ord_id'] = $request['ord_id'];
                $orcl_id = DB::table('order_client')->insertGetId($orcl_data);

                $ord_edit_data['ord_orcl_id'] = $orcl_id;
            }
        }

        // 4. 更改订单表客户id、订单金额
        $ord_edit_data['ord_ware_id'] = isset($request['ware_id']) ? $request['ware_id'] : 0; //仓库id
        $ord_edit_data['ord_client_id'] = $request['ord_client_id']; //选择客户id
        $ord_edit_data['ord_service_type'] = $request['ord_service_type']; //订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单
        if ($request['ord_service_type'] == 5 || $request['ord_service_type'] == 4) {
            $ord_edit_data['ord_wor_state'] = 5; //订单的工单状态1未派工单2服务中3售后中4已完成5无工单
        } else {
            $ord_edit_data['ord_wor_state'] = 1; //订单的工单状态1未派工单2服务中3售后中4已完成5无工单
        }
        // 如果是外派订单还是无工单状态
        if ($orcl_info->orcl_order_type == 2) {
            $ord_edit_data['ord_wor_state'] = 5;
        }

        $goo_all_price = $goo_all_price + ($orcl_rescue_service_price); //合计金额=商品总金额+服务项目的订单金额
        $goo_order_price = $goo_all_price; //订单总金额
        if ($request['ord_service_type'] == 4) {
            $goo_all_price = '-' . $goo_all_price;
            $goo_order_price = '-' . $goo_order_price;
        }

        // 4. 更改订单表客户id、订单金额
        $ord_edit_data['ord_payment_way'] = $request['ord_payment_way']; // 结算方式1.账期 2.现结 3微信 4支付宝
        $ord_edit_data['ord_order_price'] = $goo_order_price * 100; // 订单金额（单位：分）
        $ord_edit_data['ord_actual_price'] = $goo_all_price * 100; // 结算金额（单位：分）
        $ord_edit_data['ord_goods_quantity'] = $goo_all_quantity; // 商品总数量
        $ord_edit_data['orcl_assign_price'] = $goo_assign_all_price * 100; // 结算金额（单位：分）
        $ord_edit_data['ord_type'] = $request['ord_type']; // 订单类型：1门店零售2渠道单位
        $ord_edit_data['ord_remark'] = isset($request['ord_remark']) ? $request['ord_remark'] : ''; //订单备注
        $ord_edit_data['ord_service_adm_id'] = isset($request['service_adm_id']) ? $request['service_adm_id'] : ''; //服务技师id
        $ord_edit_data['ord_service_sepr_id'] = $request['service_sepr_id']; //服务项目id
        // 服务门店为0的话 是当前门店id
        if ($request['service_shop_id'] == 0) {
            $ord_edit_data['ord_service_shop_id'] = $user_info->adm_shop_id; //服务门店id
        } else {
            $ord_edit_data['ord_service_shop_id'] = $request['service_shop_id']; //服务门店id
        }
        $ord_edit_data['ord_update_time'] = date('Y-m-d H:i:s');

        // 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']);
            $ord_edit_data['orcl_shit_id'] = $find_shit_id; //图片模板id
        } else {
            $ord_edit_data['orcl_shit_id'] = 0; //图片模板id
        }
        $ord_eidt_res = DB::table('order as ord')
            ->leftjoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
            ->where('ord_id', $request['ord_id'])
            ->update($ord_edit_data);
        // 查询出当前订单的发货单
        $find_dego_data = DB::table('dispatch_bill')
            ->where('dego_order_type', 1)
            // ->where('dego_type', 4)//类型：1未出库2已出库3作废4锁定
            ->where('dego_wor_id', $request['ord_id'])
            ->where('dego_original_number', $order_data->ord_order_number)
            ->orderBy('dego_id', 'desc')
            ->first(['dego_id', 'dego_type', 'dego_out_ware_id', 'dego_count', 'dego_number']);
        // 6. 订单类型为 发货单 生成发货单  虚拟加盟店不生成发货单
        if ($request['ord_service_type'] == 5 && $request['orcl_shipment_party'] != 4 && empty($find_dego_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;
            // 根据订单id查询订单单号
            $ord_number = DB::table('order')
                ->where('ord_id', $request['ord_id'])
                ->value('ord_order_number');
            $dibi_data = DispatchBill::create(
                $user_info,   //用户信息
                $request,  //订单提交数据
                $goods_data,  //提交的商品数据
                1,  //类型：1.订单发货 2.工单发货
                $request['ware_id'],  //出库仓库id
                $ord_number,  //原始单号，订单号/工单号
                $request['ord_id'],  //发货单关联的工单/订单id
                $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($order_data);
            }
        }
        // 查询出当前订单的退货单
        $find_rede_data = DB::table('recede_recycle')
            ->where('rec_state', 1)
            ->where('rec_ord_id', $request['ord_id'])
            ->where('rec_ord_order_number', $order_data->ord_order_number)
            ->orderBy('rec_id', 'desc')
            ->select('rec_id', 'rec_ord_id', 'rec_ord_order_number')
            ->first();
        // 订单类型为退货单,生成退货单
        if ($request['ord_service_type'] == 4 && $request['orcl_shipment_party'] != 4 && empty($find_rede_data)) {
            $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'] = $request['ord_id']; //订单id
            $add_recycle['rec_ord_order_number'] = $order_data->ord_order_number; //订单号
            $add_recycle['rec_source_type'] = 8; //类型 4 (工单号)退货单 5技师退回 6技师拒单 7技师终止 8(订单号)退货单
            $add_recycle['rec_price'] = abs($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'] = isset($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_orgo_id'] = $value['orgo_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['wago_id']; //仓库商品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)
                    ->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 (!$add_client || !$mem_res || !$add_goods || !$recycle_id) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'生成订单失败']);
            }
        }

        // 添加订单备注
        if (!empty($request['ord_remark'])) {
            $wor_remark = orderRemark($user_info, $request['ord_id'], 0, $request['ord_remark'], '订单编辑');
        } else {
            $wor_remark = true;
        }

        if ($ord_eidt_res && $orcl_id && $orgo_res && $wor_remark) {
            return ['code'=>200, 'msg'=>'success', 'data'=>'编辑订单成功', 'return_datas'=>$goods_data];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'编辑订单失败3'];
        }
    }

    /**
     * [editOrderLockStockGoods 编辑订单锁定商品库存]
     * @param  [type] $user_info  [用户信息]
     * @param  [type] $request    [编辑提交数据]
     * @param  [type] $order_data [订单信息]
     * @param  [type] $goods_data [订单提交的商品数据]
     * @return [type]             [description]
     */
    private function editOrderLockGoodsStock(
        $user_info,
        $request,
        $order_data,
        $goods_data,
        $request_wago_id,
        $goo_all_quantity
    ) {
        // 判断编辑的订单类型是不是退货单
        if ($request['ord_service_type'] == 4) { //订单类型：4退货单
            // 判断原来的订单类型是否为退货单
            if ($order_data->ord_service_type == 4) {
                return ['code'=>200, 'msg'=>'success', 'return_data'=>[]];
            } else {
                // 如果原来的订单不是退货单，要把之前的商品锁定库存数量还回去
                // 如果是发货单，要把发货单相关数据删除
                if ($order_data->ord_service_type == 5) { //订单类型: 5发货单
                    // 原来的发货单数据删除
                    $find_dego_data = DB::table('dispatch_bill')
                        ->where('dego_order_type', 1)
                        ->where('dego_wor_id', $request['ord_id'])
                        ->where('dego_original_number', $order_data->ord_order_number)
                        ->orderBy('dego_id', 'desc')
                        ->first(['dego_id', 'dego_type', 'dego_out_ware_id', 'dego_count', 'dego_number']);
                    if (!empty($find_dego_data)) {
                        // 删除发货单的商品
                        $del_dego_res = DB::table('dispatch_goods')
                            ->where('digo_dego_id', $find_dego_data->dego_id)
                            ->delete();
                        // 删除发货单的数据
                        $del_dibi_res = DB::table('dispatch_bill')
                            ->where('dego_id', $find_dego_data->dego_id)
                            ->delete();
                        if (!$del_dego_res || !$del_dibi_res) {
                            return ['code'=>500, 'msg'=>'error', 'data'=>'编辑订单失败1'];
                        }
                    }
                }
                // 查询原来订单商品表数据
                $find_order_goods = DB::table('order_goods')
                    ->where('orgo_ord_id', $request['ord_id'])
                    ->select('orgo_ware_id', 'orgo_waon_class', 'orgo_actual_goo_id', 'orgo_wago_id', 'orgo_goo_id', 'orgo_state', 'orgo_goo_quantity', 'orgo_goo_inventory', 'orgo_wafr_id', 'orgo_wafg_id')
                    ->get()->toArray();
                // 查询仓库id是否为移动仓库，移动仓库没有锁定库存
                // ware_type 类型：1固定仓2技师库3移动仓
                $ware_type = DB::table('warehouse')
                    ->where('ware_id', $order_data->ord_ware_id)
                    ->value('ware_type');
                // 取消锁定库存
                $lock_turn_normal = Order::cancelOrderChangeWafgstock(
                    $user_info,
                    $ware_type,
                    $request,
                    $find_order_goods,
                    $order_data
                );
                // 仓库商品锁定表中没有商品数据默认删除
                $wagl_id = 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', $order_data->ord_order_number)
                    ->value('wagl_id');
                if ($wagl_id) {
                    $wagl_del = 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', $order_data->ord_order_number)
                        ->delete();
                } else {
                    $wagl_del = true;
                }
                if ($lock_turn_normal['code'] == 500) {
                    DB::rollBack();
                    return ['code'=>500, 'msg'=>'error', 'data'=>'编辑订单失败4'];
                }
                return ['code'=>200, 'msg'=>'success', 'return_data'=>[]];
            }
        }
        // 订单类型不是退货单或发货单,锁定库存数量还回仓库
        // 查询原来订单商品表数据
        $find_order_goods = DB::table('order_goods')
            ->where('orgo_ord_id', $request['ord_id'])
            ->select('orgo_ware_id', 'orgo_waon_class', 'orgo_state', 'orgo_wago_id as wago_id', 'orgo_goo_id', 'orgo_goo_quantity as goo_quantity', 'orgo_goo_inventory')
            ->get()->toArray();
        $find_order_goods = json_decode(json_encode($find_order_goods, true), true);
        $find_orgo_data = [];
        $find_goo_quantity = 0;
        $find_orgo_wago_id = [];

        foreach ($find_order_goods as $key => $value) {
            // [仓库商品id][出库类型：良品/优先]，用于判断仓库是否有库存
            if (isset($find_orgo_data[$value['wago_id']][$value['orgo_goo_inventory']])) {
                $find_orgo_data[$value['wago_id']][$value['orgo_goo_inventory']]['goo_quantity'] += $value['goo_quantity'];
            } else {
                $find_orgo_data[$value['wago_id']][$value['orgo_goo_inventory']]['goo_quantity'] = $value['goo_quantity'];
            }
            $find_orgo_wago_id[] = $value['wago_id'];
            $find_goo_quantity += $value['goo_quantity'];
        }
        // 判断编辑提交的仓库商品id与原来订单商品表中的仓库商品id是否一样,并且仓库id也相同的,并且商品数量也相同的
        // array_diff() 函数用于比较两个（或更多个）数组的值，并返回差集
        // 比较两个商品id数组是否有差集，没有差集的就是没有更改商品
        if (!array_diff($request_wago_id, $find_orgo_wago_id) && $request['ware_id'] == $order_data->ord_ware_id && $find_goo_quantity == $goo_all_quantity && $order_data->ord_service_type != 4 && ($find_orgo_data == $goods_data)) {
            // 两个数组互相不存在差集，那这两个数组的值是相同的
            // 商品id一样并且仓库id也一样，不用更改锁定库存
            return ['code'=>200, 'msg'=>'success', 'return_data'=>[]];
        }
        // 商品id不一样，更改锁定库存
        // 判断选择的仓库是否为技师库，技师库不需要更改商品库存数量
        $find_ware_id[] = $request['ware_id'];
        $find_ware_id[] = $order_data->ord_ware_id;
        $find_ware_id = array_unique($find_ware_id);
        // ware_type 类型：1固定仓2技师库3移动仓
        $find_ware_data = DB::table('warehouse')
            ->whereIn('ware_id', $find_ware_id)
            ->pluck('ware_type', 'ware_id')->toArray();
        $return_data = [];
        // 原来订单有商品，原来的不是技师库，原来订单商品表中的锁定库存减少，正常库存增加
        if ($find_goo_quantity && $find_ware_data[$order_data->ord_ware_id] != 2 && $order_data->ord_service_type != 4  && $order_data->orcl_shipment_party != 4) {
            // 查询订单商品信息
            $find_orgo_data = DB::table('order_goods')
                ->where('orgo_ord_id', $request['ord_id'])
                ->whereNotIn('orgo_state', [2, 3, 4])
                ->select('orgo_ware_id', 'orgo_waon_class', 'orgo_wago_id', 'orgo_goo_id', 'orgo_goo_quantity', 'orgo_goo_inventory', 'orgo_wafr_id', 'orgo_wafg_id')
                ->get()->toArray();
            $lock_turn_normal = Order::cancelOrderChangeWafgstock(
                $user_info,
                $find_ware_data[$order_data->ord_ware_id],
                $request,
                $find_orgo_data,
                $order_data
            );
            if ($lock_turn_normal['code'] == 500) {
                DB::rollBack();
                return ['code'=>500, 'msg'=>'error', 'data'=>'编辑订单失败5'];
            }
        }

        // 编辑订单有商品，选择的固定仓库，编辑提交的商品id的正常库存减少，锁定库存增加
        if ($goo_all_quantity && $find_ware_data[$request['ware_id']] != 2 && $request['ord_service_type'] != 4  && $request['orcl_shipment_party'] != 4 && $request['orcl_shipment_party'] != 5) {
            // 查询固定仓库库存商品信息
            $find_warehouse_goods = DB::table('warehouse_goods')
                ->where('wago_ware_id', $request['ware_id'])
                ->whereIn('wago_id', $request_wago_id)
                ->select('wago_id', 'wago_class', 'wago_goo_id', 'wago_stock_number', 'wago_priority_stock_number', 'wago_lock_quantity', 'wago_priority_lock_quantity')
                ->get()->toArray();
            $warehouse_goods = array_column($find_warehouse_goods, null, 'wago_id');

            $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;
                        }
                    }
                }
            }
        }

        /*
            锁定仓库商品库存处理
            虚拟加盟店订单商品没有库存，不需要锁定库存；
            退货单商品不需要锁定商品库存；
            运营中心派单商品不需要锁定商品库存；
            其他有商品的情况需要锁定商品库存
        */
        $wagl_data = [];
        foreach ($order_data as $key => $value) {
            $order_datas['data'][$key] = $value;
        }
        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,
                    $order_datas,
                    $neaten_goods_data
                );
                if ($ware_lock_return['code'] == 500) {
                    return $ware_lock_return;
                }
                $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_datas['data']['ord_id'];
                    $wagl_data[$wagl_key]['wagl_original_number'] = $order_datas['data']['ord_order_number'];
                    $wagl_data[$wagl_key]['wagl_original_correlation_id'] = $order_datas['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) {
            $update_dis_data['dego_type'] = 3; //作废
            $update_dis_data['dego_update_time'] = date('Y-m-d H:i:s'); //更新时间
            $update_dis_res = DB::table('dispatch_bill')
                ->where('dego_wor_id', $order_datas['data']['ord_id'])
                ->update($update_dis_data);
            $dibi_data = DispatchBill::create(
                $user_info,   //用户信息
                $request,  //订单提交数据
                $goods_data,  //提交的商品数据
                1,  //类型：1.订单发货 2.工单发货
                $request['ware_id'],  //出库仓库id
                $order_datas['data']['ord_order_number'],  //原始单号，订单号/工单号
                $order_datas['data']['ord_id'],  //发货单关联的工单/订单id
                $order_datas['data']['shop_id'],  //所属总店id
                $order_datas['data']['ord_type'],  //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
                $order_datas['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) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'编辑订单失败'];
            }
        }
        return ['code'=>200, 'msg'=>'success', 'return_data'=>$return_data];
    }

    /**
     * [editOrderDispatchBill 编辑订单的发货单数据]
     * @param  [type] $user_info  [用户信息]
     * @param  [type] $request    [编辑提交数据]
     * @param  [type] $order_data [订单信息]
     * @param  [type] $goods_data [订单提交的商品数据]
     * @return [type]             [description]
     */
    private function editOrderDispatchBill(
        $user_info,
        $request,
        $order_data,
        $goods_data
    ) {
        // 查询出当前订单的发货单
        $find_dego_data = DB::table('dispatch_bill')
            ->where('dego_order_type', 1)
            // ->where('dego_type', 4)//类型：1未出库2已出库3作废4锁定
            ->where('dego_wor_id', $request['ord_id'])
            ->where('dego_original_number', $order_data->ord_order_number)
            ->orderBy('dego_id', 'desc')
            ->first(['dego_id', 'dego_type', 'dego_out_ware_id', 'dego_count', 'dego_number']);
        $goo_all_quantity = 0;
        foreach ($goods_data as $key => $value) {
            // 商品状态：1.正常3回收的商品4换货商品5赠品
            if ($value['goo_state'] == 4) {
                continue;
            }
            // 搜索商品id对应的商品名称、商品编号
            $find_goods_data = DB::table('goods')
                ->where('goo_id', $value['goo_id'])
                ->first(['goo_name', 'goo_goods_encode', 'goo_type', '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;
                }
            }
            // 发货商品表数据
            $dego_add_goo_data[$key]['digo_dego_id'] = $find_dego_data->dego_id;
            $dego_add_goo_data[$key]['digo_orgo_id'] = $value['orgo_id'];
            $dego_add_goo_data[$key]['digo_wago_id'] = $value['wago_id'];
            $dego_add_goo_data[$key]['digo_wago_class'] = $value['goo_waon_class'];
            $dego_add_goo_data[$key]['digo_goo_id'] = $value['goo_id'];
            $dego_add_goo_data[$key]['digo_goo_price'] = $value['goo_price'] * 100;
            $dego_add_goo_data[$key]['digo_goo_quantity'] = $value['goo_quantity'];
            $dego_add_goo_data[$key]['digo_state'] = $value['goo_state'];
            $dego_add_goo_data[$key]['digo_goo_inventory'] = $value['goo_inventory'];
            $dego_add_goo_data[$key]['digo_goo_name'] = $find_goods_data->goo_name;
            $dego_add_goo_data[$key]['digo_goo_goods_encode'] = $find_goods_data->goo_goods_encode;
            $dego_add_goo_data[$key]['digo_goo_type'] = isset($value['goo_type']) ? $value['goo_type'] : $find_goods_data->goo_type;
            $dego_add_goo_data[$key]['digo_tem_goo_name'] = empty($value['tem_goo_name']) ? '' : $value['tem_goo_name'];
            $goo_all_quantity += $value['goo_quantity'];
        }

        // 删除原来的发货单的商品
        $digo_del_res = DB::table('dispatch_goods')
            ->where('digo_dego_id', $find_dego_data->dego_id)
            ->delete();

        // 添加新的发货单商品数据
        $digo_add_res = DB::table('dispatch_goods')->insert($dego_add_goo_data); // 发货单商品表添加数据

        // 2.更新发货单数据
        $bill_data['dego_count'] = $goo_all_quantity; //发货总数量
        $bill_data['dego_out_ware_id'] = $request['ware_id']; //出库仓库id
        $bill_data['dego_remark'] = isset($request['ord_remark']) ? $request['ord_remark'] : ''; //备注
        $bill_data['dego_create_adm_id'] = $user_info->adm_id;
        $bill_data['dego_update_time'] = date('Y-m-d H:i:s');
        $dibi_res = DB::table('dispatch_bill')->where('dego_id', $find_dego_data->dego_id)->update($bill_data);
        if ($digo_del_res && $digo_add_res && $dibi_res) {
            return ['code'=>200, 'msg'=>'success', 'data'=>'编辑订单成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'编辑订单失败11'];
        }
    }

    /**
     * [editOrderRecede 编辑订单的退货单数据]
     * @param  [type] $user_info  [用户信息]
     * @param  [type] $request    [编辑提交数据]
     * @param  [type] $order_data [订单信息]
     * @param  [type] $goods_data [订单提交的商品数据]
     * @return [type]             [description]
     */
    private function editOrderRecede(
        $user_info,
        $request,
        $order_data,
        $goods_data
    ) {
        // 查询当前订单的退货单
        $find_rec_data = DB::table('recede_recycle as rr')
            ->leftjoin('recede_client as rc', 'rr.rec_id', '=', 'rc.recl_rec_id')
            ->where('rec_state', 1)
            ->where('rec_ord_id', $request['ord_id'])
            ->where('rec_ord_order_number', $order_data->ord_order_number)
            ->orderBy('rec_id', 'desc')
            ->select('rec_id', 'rec_type', 'rec_state', 'rec_ware_id', 'rec_amount', 'rec_number', 'recl_id', 'recl_client_id')
            ->first();
        // 查询出原来退货单的商品
        $find_rego_data = DB::table('recede_goods')
            ->where('rego_rec_id', $find_rec_data->rec_id)
            ->get()->toArray();
        $all_price = 0; //回收商品总金额
        $goo_all_quantity = 0;
        foreach ($goods_data as $key => $value) {
            // 根据商品id查询对应的商品名称、检索编码
            $find_good_data = DB::table('goods')
                ->where('goo_id', $value['goo_id'])
                ->first(['goo_name', 'goo_goods_encode', 'goo_type', 'goo_class']);
            if ($find_good_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_good_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_good_data->goo_name = $gosa_another_name;
                }
            }
            $rego_data[$key]['rego_rec_id'] = $find_rec_data->rec_id; //退换回收单id
            $rego_data[$key]['rego_orgo_id'] = $value['orgo_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_goo_id'] = $value['goo_id']; //商品id
            $rego_data[$key]['rego_goo_name'] = $find_good_data->goo_name; //商品名称
            $rego_data[$key]['rego_goo_goods_encode'] = $find_good_data->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']; //回收数量
            if ($value['goo_inventory'] == 1) {
                $rego_data[$key]['rego_goo_inventory'] = 1;
                $rego_data[$key]['rego_fine_quantity'] = $value['goo_quantity'];
            } elseif ($value['goo_inventory'] == 2) {
                $rego_data[$key]['rego_goo_inventory'] = 2;
                $rego_data[$key]['rego_priority_quantity'] = $value['goo_quantity'];
            }
            $all_price += $value['goo_price'] * $value['goo_quantity'];
            $goo_all_quantity += $value['goo_quantity'];
        }

        // 删除原来的退货单的商品
        $rec_del_res = DB::table('recede_goods')
            ->where('rego_rec_id', $find_rec_data->rec_id)
            ->delete();
        // 添加新的退回单商品数据
        $rego_add_res = DB::table('recede_goods')->insert($rego_data); // 退货商品表添加数据

        // 2.更新退换入库数据
        $rec_data['rec_price'] = $all_price * 100; //回收总金额（单位：分）
        $rec_data['rec_amount'] = $goo_all_quantity; //回收总数量
        $rec_data['rec_ware_id'] = $request['ware_id']; //仓库id
        $rec_data['rec_remark'] = isset($request['ord_remark']) ? $request['ord_remark'] : ''; //备注
        $rec_data['rec_create_adm_id'] = $user_info->adm_id;
        $rec_data['rec_update_time'] = date('Y-m-d H:i:s');
        $rec_res = DB::table('recede_recycle')
            ->where('rec_id', $find_rec_data->rec_id)
            ->update($rec_data);

        // 判断退货单的客户单位是否更改
        if ($find_rec_data->rec_type == $request['ord_type'] && $find_rec_data->recl_client_id == $request['ord_client_id']) {
            // 客户单位没有更改
            $recl_res = true;
        } else {
            // 更改客户单位信息
            $recl_data['recl_client_id'] = $request['ord_client_id'];
            $recl_data['recl_channel_unit'] = $request['orcl_channel_unit'];
            $recl_data['recl_name'] = $request['orcl_name'];
            $recl_data['recl_phone'] = $request['orcl_phone'];
            $recl_data['recl_update_time'] = date('Y-m-d H:i:s');
            $recl_res = DB::table('recede_client')
                ->where('recl_id', $find_rec_data->recl_id)
                ->update($recl_data);
        }
        if ($rec_del_res && $rego_add_res && $rec_res && $recl_res) {
            return ['code'=>200, 'msg'=>'success', 'data'=>'编辑订单成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'编辑订单失败12'];
        }
    }

    /* 订单转售后
     * 1.订单中没有工单的可以转售后
     * 2.订单中有工单的,订单中所有的工单必须服务完成,才可以转售后
     * 3.订单中已经有售后订单的,必须把售后订单处理完成,才可以生成新的售后订单
     * 4.已生成的售后订单,是未处理状态的可以撤销售后,订单改为原来的状态
     */
    public function afterSale(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderController;
        $error_message = $verify_data->afterSaleValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 查询订单信息
        $find_order = DB::table('order as ord')
            ->leftjoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
            ->where('ord_id', $request['ord_id'])
            ->select('ord_order_number', 'ord_orcl_id', 'ord_client_id', 'ord_type', 'ord_service_type', 'ord_service_sepr_id', 'ord_service_shop_id', 'ord_service_adm_id', 'ord_orla_id', 'ord_ware_id', 'ord_order_price', 'ord_actual_price', 'ord_plus_minus', 'ord_wor_state', 'orcl_client_id', 'orcl_channel_unit', 'orcl_name', 'orcl_phone', 'orcl_car_num', 'orcl_province', 'orcl_city', 'orcl_county', 'orcl_address', 'orcl_chin_type', 'orcl_standby_battery_type', 'orcl_shipment_party', 'orcl_order_type')
            ->first();
        if ($find_order->ord_wor_state == 1) {
            // 未派工单的可以直接转售后
        } elseif ($find_order->ord_wor_state == 2) {
            // 工单服务中的，查看已派工单是否全部服务完成
            $find_work = DB::table('work_order')
                ->where('wor_order_id', $request['ord_id'])
                ->where('wor_service_state', '<>', 6)
                ->value('wor_id');
            if ($find_work) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单存在正在服务中的工单，工单服务完成后才可以转售后']);
            }
        } elseif ($find_order->ord_wor_state == 3) {
            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;

        DB::beginTransaction();
        // 外派订单转售后单
        if ($find_order->orcl_shipment_party == '3') {
            // 生成售后
            $oraf_number = 'S' . rand(100, 999) . date('mdHis') . rand(100000, 999999);
            $oraf_data['oraf_cid'] = $user_info->adm_cid;
            $oraf_data['oraf_shop_id'] = $user_info->adm_shop_id;
            $oraf_data['oraf_superior_shop_id'] = $shop_id;
            $oraf_data['oraf_create_id'] = $user_info->adm_id;
            $oraf_data['oraf_number'] = $oraf_number; //售后单号
            $oraf_data['oraf_ord_id'] = $request['ord_id']; //订单id
            $oraf_data['oraf_order_number'] = $find_order->ord_order_number; //订单号
            $oraf_data['oraf_type'] = $find_order->ord_type; //买家类型：1门店零售2渠道单位3速电派单4第三方派单
            $oraf_data['oraf_client_id'] = $find_order->ord_client_id; //选择的客户id,会员id/单位id
            $oraf_data['oraf_service_type'] = $find_order->ord_service_type; //订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单 7救援单
            $oraf_data['oraf_service_shop_id'] = $find_order->ord_service_shop_id; //服务门店id
            $oraf_data['oraf_orla_id'] = $request['oraf_orla_id']; //售后标签id
            $oraf_id = DB::table('order_after')->insertGetId($oraf_data);

            // 新增订单售后客户信息
            $orac_data['orac_oraf_id'] = $oraf_id; //售后id
            $orac_data['orac_client_id'] = $find_order->orcl_client_id; //选择的客户id,会员id/单位id
            $orac_data['orac_channel_unit'] = $find_order->orcl_channel_unit; //客户单位
            $orac_data['orac_name'] = $find_order->orcl_name; //姓名
            $orac_data['orac_phone'] = $find_order->orcl_phone; //联系电话
            $orac_data['orac_car_num'] = $find_order->orcl_car_num; //车牌号
            $orac_data['orac_province'] = $find_order->orcl_province; //省
            $orac_data['orac_city'] = $find_order->orcl_city; //市
            $orac_data['orac_county'] = $find_order->orcl_county; //区县
            $orac_data['orac_address'] = $find_order->orcl_address; //地址
            $orac_data['orac_chin_type'] = $find_order->orcl_chin_type; //铺货类型：1是铺货 2不是铺货
            $orac_data['orac_order_type'] = 2; //1系统订单售后2外派订单售后
            $orac_id = DB::table('order_after_client')->insertGetId($orac_data);

            // 更改售后客户id
            $oraf_edit_data['oraf_orcl_id'] = $orac_id; //售后客户id
            $oraf_edit_res = DB::table('order_after')
                ->where('oraf_id', $oraf_id)
                ->update($oraf_edit_data);

            // 新增售后备注
            $oran_data['oran_oraf_id'] = $oraf_id; //售后id
            $oran_data['oran_afla_id'] = $request['oraf_orla_id']; //售后标签id
            $oran_data['oran_adm_id'] = $user_info->adm_id; //备注人id
            $oran_data['oran_adm_name'] = $user_info->adm_name; //备注人姓名
            $oran_data['oran_content'] = $request['oran_content']; //备注内容
            $oran_data['oran_update_time'] = date('Y-m-d H:i:s');
            $oran_id = DB::table('order_after_note')->insert($oran_data);

            // 更改订单状态为售后状态
            $ord_data['ord_wor_state'] = 3;
            $ord_data['ord_update_time'] = date('Y-m-d H:i:s');
            $ord_res = DB::table('order')
                ->where('ord_id', $request['ord_id'])
                ->update($ord_data);

            // 生成外派售后单
            if (isset($request['assignment']) && $request['assignment'] == 1) {
                // 生成售后
                $oraf_number = 'S' . rand(100, 999) . date('mdHis') . rand(100000, 999999);
                $oraf_data['oraf_cid'] = $user_info->adm_cid;
                $oraf_data['oraf_shop_id'] = $find_order->ord_service_shop_id;
                $oraf_data['oraf_superior_shop_id'] = $find_order->ord_service_shop_id;
                $oraf_data['oraf_create_id'] = $user_info->adm_id;
                $oraf_data['oraf_number'] = $oraf_number; //售后单号
                $oraf_data['oraf_ord_id'] = $request['ord_id']; //订单id
                $oraf_data['oraf_order_number'] = $find_order->ord_order_number; //订单号
                $oraf_data['oraf_client_id'] = $find_order->ord_client_id; //选择的客户id,会员id/单位id
                $oraf_data['oraf_service_type'] = $find_order->ord_service_type; //订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单 7救援单
                $oraf_data['oraf_service_shop_id'] = $find_order->ord_service_shop_id; //服务门店id
                $oraf_data['oraf_orla_id'] = $request['oraf_orla_id']; //售后标签id
                $oraf_data['oraf_wor_state'] = 2; //待接单状态
                $oraf_data['oraf_after_state'] = 1; //待接单状态
                $assign_oraf_id = DB::table('order_after')->insertGetId($oraf_data);

                // 新增订单售后客户信息
                $orac_data['orac_oraf_id'] = $assign_oraf_id; //售后id
                $orac_data['orac_client_id'] = $find_order->orcl_client_id; //选择的客户id,会员id/单位id
                $orac_data['orac_channel_unit'] = $find_order->orcl_channel_unit; //客户单位
                $orac_data['orac_name'] = $find_order->orcl_name; //姓名
                $orac_data['orac_phone'] = $find_order->orcl_phone; //联系电话
                $orac_data['orac_car_num'] = $find_order->orcl_car_num; //车牌号
                $orac_data['orac_province'] = $find_order->orcl_province; //省
                $orac_data['orac_city'] = $find_order->orcl_city; //市
                $orac_data['orac_county'] = $find_order->orcl_county; //区县
                $orac_data['orac_address'] = $find_order->orcl_address; //地址
                $orac_data['orac_chin_type'] = $find_order->orcl_chin_type; //铺货类型：1是铺货 2不是铺货
                $orac_data['orac_order_type'] = 2; //1系统订单售后2外派订单售后
                $orac_data['orac_join_oraf_id'] = $oraf_id; //加盟店售后单id
                $assign_orac_id = DB::table('order_after_client')->insertGetId($orac_data);

                // 更改售后客户id
                $oraf_edit_data['oraf_orcl_id'] = $assign_orac_id; //售后客户id
                $assign_oraf_res = DB::table('order_after')
                    ->where('oraf_id', $assign_oraf_id)
                    ->update($oraf_edit_data);

                // 新增售后备注
                $oran_data['oran_oraf_id'] = $oraf_id; //售后id
                $oran_data['oran_afla_id'] = $request['oraf_orla_id']; //售后标签id
                $oran_data['oran_adm_id'] = $user_info->adm_id; //备注人id
                $oran_data['oran_adm_name'] = $user_info->adm_name; //备注人姓名
                $oran_data['oran_content'] = $request['oran_content']; //备注内容
                $oran_data['oran_update_time'] = date('Y-m-d H:i:s');
                $assign_oran_id = DB::table('order_after_note')->insert($oran_data);
            } else {
                $assign_oraf_id = true;
                $assign_orac_id = true;
                $assign_oraf_res = true;
                $assign_oran_id = true;
            }
            $orac_edit_data['orac_join_wor_id'] = $assign_oraf_id;
            $orac_data = DB::table('order_after_client')
                ->where('orac_id', $orac_id)
                ->update($orac_edit_data);
            // 生成操作记录
            $sale_record = orderLog($user_info, $request['ord_id'], 0, '转售后');

            if ($assign_oraf_id && $assign_orac_id && $assign_oraf_res && $assign_oran_id && $sale_record) {
                DB::commit();
                Common::addLog($user_info, getRealIp($request), '订单列表', '转售后', $find_order->ord_order_number . '转售后成功');
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'转售后成功']);
            } else {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'转售后失败']);
            }
        }
        // 生成售后
        $oraf_number = 'S' . rand(100, 999) . date('mdHis') . rand(100000, 999999);
        $oraf_data['oraf_cid'] = $user_info->adm_cid;
        $oraf_data['oraf_shop_id'] = $user_info->adm_shop_id;
        $oraf_data['oraf_superior_shop_id'] = $shop_id;
        $oraf_data['oraf_create_id'] = $user_info->adm_id;
        $oraf_data['oraf_number'] = $oraf_number; //售后单号
        $oraf_data['oraf_ord_id'] = $request['ord_id']; //订单id
        $oraf_data['oraf_order_number'] = $find_order->ord_order_number; //订单号
        $oraf_data['oraf_type'] = $find_order->ord_type; //买家类型：1门店零售2渠道单位3速电派单4第三方派单
        $oraf_data['oraf_client_id'] = $find_order->ord_client_id; //选择的客户id,会员id/单位id
        $oraf_data['oraf_service_type'] = $find_order->ord_service_type; //订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单 7救援单
        $oraf_data['oraf_service_shop_id'] = $find_order->ord_service_shop_id; //服务门店id
        $oraf_data['oraf_orla_id'] = $request['oraf_orla_id']; //售后标签id
        $oraf_id = DB::table('order_after')->insertGetId($oraf_data);

        // 新增订单售后客户信息
        $orac_data['orac_oraf_id'] = $oraf_id; //售后id
        $orac_data['orac_client_id'] = $find_order->orcl_client_id; //选择的客户id,会员id/单位id
        $orac_data['orac_channel_unit'] = $find_order->orcl_channel_unit; //客户单位
        $orac_data['orac_name'] = $find_order->orcl_name; //姓名
        $orac_data['orac_phone'] = $find_order->orcl_phone; //联系电话
        $orac_data['orac_car_num'] = $find_order->orcl_car_num; //车牌号
        $orac_data['orac_province'] = $find_order->orcl_province; //省
        $orac_data['orac_city'] = $find_order->orcl_city; //市
        $orac_data['orac_county'] = $find_order->orcl_county; //区县
        $orac_data['orac_address'] = $find_order->orcl_address; //地址
        $orac_data['orac_chin_type'] = $find_order->orcl_chin_type; //铺货类型：1是铺货 2不是铺货
        $orac_data['orac_order_type'] = 1; //1系统订单售后2外派订单售后
        $orac_id = DB::table('order_after_client')->insertGetId($orac_data);

        // 更改售后客户id
        $oraf_edit_data['oraf_orcl_id'] = $orac_id; //售后客户id
        $oraf_edit_res = DB::table('order_after')
            ->where('oraf_id', $oraf_id)
            ->update($oraf_edit_data);

        // 新增售后备注
        $oran_data['oran_oraf_id'] = $oraf_id; //售后id
        $oran_data['oran_afla_id'] = $request['oraf_orla_id']; //售后标签id
        $oran_data['oran_adm_id'] = $user_info->adm_id; //备注人id
        $oran_data['oran_adm_name'] = $user_info->adm_name; //备注人姓名
        $oran_data['oran_content'] = $request['oran_content'] ? $request['oran_content'] : ''; //备注内容
        $oran_data['oran_update_time'] = date('Y-m-d H:i:s');
        $oran_id = DB::table('order_after_note')->insert($oran_data);

        // 更改订单状态为售后状态
        $ord_data['ord_wor_state'] = 3;
        $ord_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_res = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->update($ord_data);

        // 生成操作记录
        $sale_record = orderLog($user_info, $request['ord_id'], 0, '转售后');

        $after_record = orderAfterLog($user_info, $oraf_id, '3', '生成售后单');

        if ($oraf_id && $orac_id && $oraf_edit_res && $oran_id && $ord_res && $sale_record && $after_record) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '订单列表', '转售后', $find_order->ord_order_number . '转售后成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'转售后成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'转售后失败']);
        }
    }

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

        $search_data = $request->all();

        // 如果选择了单位类型 查询出该单位类型下有多少个单位
        if (!empty($search_data['unit_type'])) {
            $chun_id = DB::table('channel_unit')
                ->where('chun_chty_id', $search_data['unit_type'])
                ->get(['chun_id'])->toArray();
            $search_data['chty_id'] = array_column($chun_id, 'chun_id');
        }
        if($search_data['unit_type'] == 2 && isset($search_data['ord_client_id']) && $search_data['ord_client_id'] > 0){
            $client_list = DB::table('business_account')
                ->where('buac_bucl_id', $search_data['ord_client_id'])
                ->where('buac_cid', $user_info->adm_cid)
                ->where('buac_shop_id', $shop_id)
                ->where('buac_del', 1)
                ->get()->toArray();
            $client_account_ids = array_column($client_list,'buac_id');
            $search_data['client_account_ids'] = $client_account_ids;
        }
        $data = DB::table('order as o')
            ->leftJoin('admin as c', 'c.adm_id', '=', 'o.ord_create_id')
            ->leftJoin('shop as s', 's.shop_id', '=', 'o.ord_service_shop_id')
            ->where('ord_cid', $user_info->adm_cid)
            ->where('ord_shop_id', $shop_id)
            ->where('ord_delete', 1)
            ->where('ord_collection_bill', 1) //是否代收账单：1正常订单2代收账单
            ->where('ord_state', 1) //未结算
            ->whereIn('ord_wor_state', [4,18,19,20]) //无工单 已完成
            ->where(function ($query) use ($search_data) { //判断是编辑还是新增
                if (!empty($search_data['orbi_id'])) {
                    // 编辑
                    $query->where('ord_orbi_id', 0)
                        ->Orwhere('ord_orbi_id', $search_data['orbi_id']);
                } else {
                    // 新增
                    $query->where('ord_orbi_id', 0);
                }
            })
            ->where(function ($query) use ($search_data) { //起止日期
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                    $query->whereBetween('ord_create_time', [$search_data['start_time'], $search_data['end_time'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['start_time'])) {
                        $query->where('ord_create_time', '>=', $search_data['start_time']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['end_time'])) {
                            $query->where('ord_create_time', '<=', $search_data['end_time'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) { //会员零售
                if ($search_data['unit_type'] == 1 && !empty($search_data['ord_client_id'])) {
                    $query->where('ord_type', 1)
                        ->where('ord_client_id', $search_data['ord_client_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //客户单位
                if($search_data['unit_type'] == 2 && !empty($search_data['client_account_ids'])){
                    $query->where('ord_type', 2)
                        ->whereIn('ord_client_id', $search_data['client_account_ids']);
                }else if ($search_data['unit_type'] == 2 && !empty($search_data['ord_client_id'])) {
                    $query->where('ord_type', 2)
                        ->where('ord_client_id', $search_data['ord_client_id']);
                }
            })
            ->orderBy('ord_id', 'desc')
            ->select('ord_id', 'ord_order_number', 'ord_create_id', 'ord_state', 'ord_service_type', 'ord_order_price', 'ord_actual_price', 'ord_create_time', 'c.adm_name','ord_collection_price', 'ord_mem_price')
            ->get();
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }

    // 生成账单
    public function createBill(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderController;
        $error_message = $verify_data->createBillValidator($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;

        $number = 'DZ' . time() . rand(10000000, 99999999);
        // 1.订单账单表新增一条数据
        $add_data['orbi_cid'] = $user_info->adm_cid;
        $add_data['orbi_shop_id'] = $user_info->adm_shop_id;
        $add_data['orbi_superior_shop_id'] = $shop_id;
        $add_data['orbi_create_adm_id'] = $user_info->adm_id;
        $add_data['orbi_number'] = $number;
        $add_data['orbi_order_amount'] = count($request['ord_id']);
        $add_data['orbi_start_time'] = $request['start_time'];
        $add_data['orbi_end_time'] = $request['end_time'];
        $add_data['orbi_remark'] = $request['orbi_remark'] ?? '';
        $add_data['orbi_state'] = 3; //待审核
        $add_data['orbi_type'] = $request['orbi_type']; //类型：1门店零售2渠道单位
        // 获取客户单位信息
        if ($request['orbi_type'] == 1) {
            // 会员
            $channel = DB::table('member')
                ->where('mem_id', $request['orbi_client_id'])
                ->value('mem_name');
        } elseif ($request['orbi_type'] == 2) {
            // 客户单位
            /*$channel = DB::table('channel_unit')
                ->where('chun_id', $request['orbi_client_id'])
                ->value('chun_unit_name');*/
            $channel = DB::table('business_client')
                ->where('bucl_id', $request['orbi_client_id'])
                ->value('bucl_name');
        } else {
            $channel = '';
        }
        $add_data['orbi_channel_unit'] = $channel; //客户单位名称
        $add_data['orbi_client_id'] = $request['orbi_client_id']; //会员/客户单位id
        // 获取到代收金额/商品总量/合计金额/结算金额
        $order_info = DB::table('order')
            ->whereIn('ord_id', $request['ord_id'])
            ->select('ord_goods_quantity', 'ord_actual_price', 'ord_order_price', 'ord_state', 'ord_service_type', 'ord_plus_minus', 'ord_id', 'ord_order_number', 'ord_orbi_id', 'ord_mem_price')
            ->get()->toArray();
        $add_data['orbi_collection_price'] = 0; //代收金额
        $add_data['orbi_goods_sum'] = 0; // 商品总量
        $goods_price = 0; //计算账单金额使用结算金额计算(合计金额/结算金额是一个)
        $original_id = []; //原始id，更改应收账款数据使用
        foreach ($order_info as $key => $value) {
            if ($value->ord_state != 1) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$value->ord_order_number . '订单已结算,无法生成账单']);
            }
            if (!empty($value->ord_orbi_id)) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$value->ord_order_number . '订单已经生成账单,无法生成账单']);
            }
            $add_data['orbi_goods_sum'] += $value->ord_goods_quantity;
            if ($value->ord_state == 1) { //只相加未结算的订单结算金额
                // ord_service_type 订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单
                if ($request['choose_collect'] == 1) {
                    $original_id[] = $value->ord_order_number;
                }
                $goods_price += $value->ord_order_price;
            }
        }
        $choose_collect = $request['choose_collect']; //是否合并代收：1是2否
        if ($choose_collect == 2) {
            // 没有选择合并代收金额，实收金额就是结算金额,代收金额就是0
            $orbi_actual_price = $goods_price; //实收金额
            $add_data['orbi_collection_price'] = 0;
        } else {
            // 选择合并代收金额，实收金额=结算金额-代收金额
            $orbi_actual_price = $goods_price - $add_data['orbi_collection_price']; //实收金额
        }
        if ($orbi_actual_price < 0) {
            $add_data['orbi_plus_minus'] = 2; //负数
        } else {
            $add_data['orbi_plus_minus'] = 1; //正数
        }
        $add_data['orbi_merge_state'] = $choose_collect; //是否合并代收：1是2否
        $add_data['orbi_total_price'] = abs($goods_price); //合计金额（单位：分）订单的结算
        $add_data['orbi_bill_price'] = abs($goods_price);  //结算金额（单位：分）订单结算金额：商品总金额-回收总金额
        $add_data['orbi_actual_price'] = abs($orbi_actual_price);  //实收金额（单位：分）订单结算金额-代收金额，实际应收金额
        DB::beginTransaction();
        $orbi_id = DB::table('order_bill')->insertGetId($add_data);
        // if ($choose_collect == 1) {
        //     // 选择合并代收金额，有代收金额的在订单表里新增代收金额的数据
        //     foreach ($request['ord_id'] as $key => $value) {
        //         $order = DB::table('order')->where('ord_id', $value)->first(); //订单表
        //         // 代收金额不为0时 就是有代收的订单 有代收金额的订单id 所对应的订单数据 新增一条一模一样的数据
        //         if ($order->ord_collection_price != 0) {
        //             //订单客户表
        //             $order_client = DB::table('order_client')->where('orcl_ord_id', $value)->first();
        //             //订单商品表
        //             $order_goods = DB::table('order_goods')
        //                     ->where('orgo_ord_id', $value)
        //                     ->get(['orgo_ord_id','orgo_order_number','orgo_goo_id','orgo_goo_name',
        //                            'orgo_goo_goods_encode','orgo_state','orgo_goo_price','orgo_collection_price',
        //                            'orgo_goo_quantity','orgo_goo_inventory','orgo_goo_exchange','orgo_is_recycle',
        //                            'orgo_recycle_quantity','orgo_can_assign_quantity']);
        //             $order_goods = json_decode(json_encode($order_goods), true);

        //             // 订单表
        //             $ord_order_number = Common::orderRule($user_info);
        //             $ord_data['ord_cid'] = $order->ord_cid; //所属企业id
        //             $ord_data['ord_superior_shop_id'] = $order->ord_superior_shop_id; //所属总店id
        //             $ord_data['ord_shop_id'] = $order->ord_shop_id; //所属门店id
        //             $ord_data['ord_order_number'] = $ord_order_number; //订单号
        //             $ord_data['ord_create_id'] = $order->ord_create_id; //创建人id
        //             $ord_data['ord_orcl_id'] = $order->ord_orcl_id; //订单客户id
        //             $ord_data['ord_client_id'] = $order->ord_client_id; //选择的客户id，会员id/单位id
        //             $ord_data['ord_type'] = $order->ord_type; //订单类型：1门店零售2渠道单位
        //             $ord_data['ord_service_type'] = $order->ord_service_type; //订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单
        //             $ord_data['ord_service_sepr_id'] = $order->ord_service_sepr_id; //服务项目id
        //             $ord_data['ord_service_shop_id'] = $order->ord_service_shop_id; //服务门店id
        //             $ord_data['ord_service_adm_id'] = $order->ord_service_adm_id; //服务技师id
        //             $ord_data['ord_orla_id'] = $order->ord_orla_id; //订单标签id
        //             $ord_data['ord_ware_id'] = $order->ord_ware_id; //仓库id
        //             $ord_data['ord_payment_way'] = $order->ord_payment_way; //结算方式1.账期 2.现结 3微信 4支付宝
        //             $ord_data['ord_state'] = $order->ord_state; //结算状态1未结算2已结算3已核销
        //             $ord_data['ord_order_price'] = $order->ord_order_price; //订单金额（单位：分）
        //             $ord_data['ord_actual_price'] = $order->ord_actual_price; //结算金额（单位：分）
        //             $ord_data['ord_collection_price'] = $order->ord_collection_price; //代收金额（单位：分）
        //             $ord_data['ord_plus_minus'] = $order->ord_plus_minus; //金额正负：1正值2负值
        //             $ord_data['ord_goods_quantity'] = $order->ord_goods_quantity; //商品总数量
        //             $ord_data['ord_wor_state'] = $order->ord_wor_state; //订单的工单状态1未派工单2服务中3售后中4已完成5无工单
        //             $ord_data['ord_wor_quantity'] = $order->ord_wor_quantity; //工单数量
        //             $ord_data['ord_delete'] = $order->ord_delete; //是否删除：1正常订单2取消订单
        //             $ord_data['ord_remark'] = $order->ord_remark; //订单备注
        //             $ord_data['ord_collection_bill'] = 2; //是否代收账单：1正常订单2代收账单
        //             $ord_data['ord_orbi_id'] = 0;  //账单id
        //             $ord_id = DB::table('order')->insertGetId($ord_data); //订单表

        //             // 订单商品表
        //             foreach ($order_goods as $key => $value) {
        //                 $order_goods[$key]['orgo_ord_id'] = $ord_id; //订单id
        //             }
        //             $add_goods = DB::table('order_goods')->insert($order_goods);

        //             // 订单客户表
        //             $cli_data['orcl_ord_id'] = $ord_id; //订单id
        //             $cli_data['orcl_channel_unit'] = $order_client->orcl_channel_unit; //渠道单位
        //             $cli_data['orcl_name'] = $order_client->orcl_name; //姓名
        //             $cli_data['orcl_phone'] = $order_client->orcl_phone; //联系电话
        //             $cli_data['orcl_car_num'] = $order_client->orcl_car_num; //车牌号
        //             $cli_data['orcl_address'] = $order_client->orcl_address; //地址
        //             $cli_data['orcl_acc_subject_id'] = $order_client->orcl_acc_subject_id; //会计科目id
        //             $cli_data['orcl_img'] = $order_client->orcl_img; //结算凭证
        //             $cli_data['orcl_chin_type'] = $order_client->orcl_chin_type; //铺货类型：1是铺货 2不是铺货
        //             $cli_data['orcl_standby_battery_type'] = $order_client->orcl_standby_battery_type; //是否为备用电池1是2否
        //             $add_client = DB::table('order_client')->insert($cli_data);

        //             if (!$ord_id || !$add_goods || !$add_client) {
        //                 DB::rollBack();
        //                 return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'生成账单失败']);
        //             }
        //         }
        //     }
        // }

        // 2.修改订单表 账单id
        $sql = 'UPDATE `faster_order` SET ';
        $ord_orbi_id = ''; //账单id
        $ord_state = ''; //更改结算状态
        $update_time = ''; //调货时间
        $ord_id = "";

        foreach ($request['ord_id'] as $key => $value) {
            // 更改账单id
            $ord_orbi_id = $ord_orbi_id . ' WHEN ' . $value;
            $ord_orbi_id = $ord_orbi_id . ' THEN ' . $orbi_id;
            // 更改结算状态
            $ord_state = $ord_state . ' WHEN ' . $value;
            $ord_state = $ord_state . ' THEN 2';
            // 更改时间
            $update_time = $update_time . ' WHEN ' . $value;
            $update_time = $update_time . ' THEN "' . date('Y-m-d H:i:s') . '"';
            // 要更改的订单id
            $ord_id = $ord_id . $value . ',';
        }
        $sql = $sql . ' `ord_orbi_id`= CASE `ord_id` ' . $ord_orbi_id . ' END,';
        $sql = $sql . ' `ord_state`= CASE `ord_id` ' . $ord_state . ' END,';
        $sql = $sql . ' `ord_update_time`= CASE `ord_id` ' . $update_time . ' END';
        $sql = $sql . ' WHERE `ord_id` IN (' . trim($ord_id, ',') . ')';
        $save_order = DB::update($sql);

        // 3. 订单退款类型的生成账单之后，应收账款列表不再显示申请还款的按钮
        // 将应收账款的订单退款类型的收款状态改为 3还款待核对状态
        if (empty($original_id)) {
            $update_recr = true;
        } else {
            //$recr_edit_data['recr_leisurely_type'] = 3;
            $recr_edit_data['recpay_belongs_id'] = $orbi_id;
            $recr_edit_data['recpay_update_time'] = date('Y-m-d H:i:s');
            $original_id_ret = DB::table('receivable_pay')
                ->where('recpay_cid', $user_info->adm_cid)
                ->where('recpay_shop_superior_id', $shop_id)
                ->where('recpay_type', 1)
                // ->where('recr_account_type', 2)
                ->whereIn('recpay_original_number', $original_id)
                ->select('recpay_original_number')->get()->toArray();
            $original_id_arr = array_unique(array_column($original_id_ret, 'recpay_original_number'));
            if($original_id_arr){
                $update_recr = DB::table('receivable_pay')
                    ->where('recpay_cid', $user_info->adm_cid)
                    ->where('recpay_shop_superior_id', $shop_id)
                    ->where('recpay_type', 1)
                    // ->where('recr_account_type', 2)
                    ->whereIn('recpay_original_number', $original_id)
                    ->update($recr_edit_data);
            }
        }
        if ($orbi_id && $save_order && $update_recr) {
            Common::addLog($user_info, getRealIp($request), '订单列表', '生成账单', '生成账单：' . $number . '成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'生成账单成功', 'data'=>'success']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'生成账单失败', 'data'=>'error']);
        }
    }

    // 打印
    public function print(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderController;
        $error_message = $verify_data->infoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::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;

        $info = DB::table('order as ord')
            ->leftJoin('warehouse as ware', 'ord.ord_ware_id', '=', 'ware.ware_id')
            ->leftJoin('order_client as orcl', 'ord.ord_orcl_id', '=', 'orcl.orcl_id')
            ->leftJoin('print_number as prnu', 'prnu.prnu_original_id', 'ord.ord_id')
            ->where('ord_id', $request['ord_id'])
            ->where('ord_cid', $user_info->adm_cid)
            ->where('ord_shop_id', $shop_id)
            ->select('ord_order_number', 'ord_create_time', 'ord_order_price', 'ord_wor_state', 'ord_wor_quantity', 'ord_actual_price', 'ord_payment_way', 'ord_goods_quantity', 'ord_type', 'ord_state', 'ord_orcl_id', 'ord_remark', 'ord_create_id', 'ord_service_type', 'ware_name', 'ware_leader_id', 'orcl_name', 'orcl_phone', 'orcl_address', 'orcl_channel_unit', 'orcl_car_num', 'ord_client_id', 'ware_freight_space', 'prnu_print_num', 'ord_service_sepr_id', 'orcl_province', 'orcl_city', 'orcl_county', 'ord_service_shop_id', 'orcl_rescue_service_price', 'orcl_rescue_collection_price', 'orcl_assign_price', 'orcl_plus_minus', 'ord_plus_minus', 'ord_service_adm_id', 'orcl_car_vehicle_type', 'ord_order_plus_minus', 'orcl_shipment_party', 'orcl_adm_id', 'orcl_client_id', 'orcl_order_type')
            ->first();
        if ($info->ord_type == 1) {
            $total_client_price = 0;
        } else {
            $total_client_price = ReceivableCredit::queryClientPrice(
                $user_info,
                1, //打印类型：1订单打印2工单打印
                $info->ord_type, //客户类型
                $info->ord_client_id, //客户id
                $info->orcl_order_type, //单据类型：1系统工单2外派工单3速电派单4虚拟加盟店
                $info->ord_service_shop_id //服务门店id，实体加盟店id/虚拟加盟店id
            );
        }
        $data['ord_actual_price'] = num_to_rmb($info->ord_actual_price / 100);
        // 查询服务门店名称
        $info->ord_service_shop_name = DB::table('shop')->where('shop_id', $info->ord_service_shop_id)->value('shop_store_name');
        $info->prnu_print_num = empty($info->prnu_print_num) ? 0 : $info->prnu_print_num;

        // 订单类型如果是和客户单位的话 追加客户等级
        if ($info->ord_type == 2) {
            $info->chin_level = DB::table('channel_info')
                ->where('chin_chun_id', $info->ord_client_id)
                ->value('chin_level');

            $chun_data = DB::table('channel_unit')
                ->where('chun_id', $info->ord_client_id)
                ->select('chun_adm_id', 'chun_province', 'chun_city', 'chun_county', 'chun_address', 'chun_name', 'chun_phone')
                ->first();
            // $info->chun_adm_name = $chun_data->chun_adm_id;
            $info->chun_adm_name = $info->orcl_adm_id;
            $info->orcl_channel_unit = DB::table('channel_unit')
                ->where('chun_id', $info->ord_client_id)
                ->value('chun_unit_name');
        } elseif ($info->ord_type == 3) {
            $info->orcl_channel_unit = '速电快保';
            $info->chun_adm_name = "";
            $info->chin_level = "";
            $chun_data = [];
        } else {
            $info->chin_level = "";
            $info->chun_adm_name = "";
            $chun_data = [];
        }
        // 查询服务项目名称
        if ($info->ord_service_sepr_id != '0') {
            $sepr_data = DB::table('service_project')
                ->where('sepr_id', $info->ord_service_sepr_id)
                ->select('sepr_name', 'sepr_order_money')
                ->first();
            $info->ord_service_sepr_name = $sepr_data->sepr_name;
            $info->sepr_order_money = $info->orcl_rescue_service_price;
        }

        // 获取采购商(仓库负责人)/创建人
        $adm_id = [
            $info->ord_create_id,
            $info->ware_leader_id,
            $info->chun_adm_name,
            $info->ord_service_adm_id,
        ];
        $adm_id = array_filter($adm_id);
        $find_admin = DB::table('admin')
            ->whereIn('adm_id', $adm_id)
            ->select('adm_id', 'adm_name', 'adm_phone')
            ->get()->toArray();
        $adm_name = array_column($find_admin, null, 'adm_id');

        if ($info->ord_create_id != '0') {
            $info->create_name = $adm_name[$info->ord_create_id]->adm_name; //创建人
        }
        if ($info->ord_service_adm_id != '0') {
            $info->ord_service_adm_name = $adm_name[$info->ord_service_adm_id]->adm_name; //服务技师
        } else {
            $info->ord_service_adm_name = ''; //服务技师
        }

        $adm_ids = DB::table('admin')
            ->where('adm_id', $info->chun_adm_name)
            ->value('adm_id');
        if (empty($adm_ids)) {
            $info->ware_leader_name = ''; //仓库负责人
            $info->chun_adm_phone = ''; //业务员联系电话
            $info->chun_adm_name = ''; //业务员
        } else {
            $info->ware_leader_name = $info->ware_leader_id ? $adm_name[$info->ware_leader_id]->adm_name : ''; //仓库负责人
            $info->chun_adm_phone = $info->chun_adm_name ? $adm_name[$info->chun_adm_name]->adm_phone : ''; //业务员联系电话
            $info->chun_adm_name = $info->chun_adm_name ? $adm_name[$info->chun_adm_name]->adm_name : ''; //业务员
            // $info->ord_service_adm_name = $adm_name[$info->ord_service_adm_id]->adm_name;//技师
        }

        // 速电派单,门店没有接单时,客户信息隐藏
        if ($info->ord_wor_state == '7') {
            $info->orcl_name = substituteCharacter($info->orcl_name);
            $info->orcl_phone = substr_replace($info->orcl_phone, '****', 3, 8);
            $info->orcl_city = '***';
            $info->orcl_county = '***';
            $info->orcl_address = '***';
        }

        // 获取该订单下的商品信息
        $goods_data = DB::table('order_goods as orgo')
            ->leftjoin('goods as goo', 'goo.goo_id', '=', 'orgo.orgo_goo_id')
            ->where('orgo_ord_id', $request['ord_id'])
            ->where('orgo_state', '!=', 2)
            ->select('orgo_goo_name', 'orgo_goo_goods_encode', 'orgo_goo_quantity', 'orgo_goo_price', 'orgo_is_recycle', 'orgo_can_assign_quantity', 'orgo_collection_price', 'orgo_state', 'orgo_recycle_price', 'orgo_recycle_quantity', 'orgo_tem_goo_name as tem_goo_name', 'orgo_assign_price', 'orgo_ware_id', 'goo_unit', 'goo_class', 'goo_bra_name', 'goo_brse_id', 'orgo_wafr_id', 'orgo_id', 'goo_id')
            ->get()->toArray();
        $goods_data = json_decode(json_encode($goods_data), true);
        $goods_datas = array_column($goods_data, null, 'orgo_id');
        // 查询系列数据
        $goo_brse_id = array_column($goods_data, 'goo_brse_id');
        $brse_data = DB::table('brand_serie')
            ->whereIn('brse_id', $goo_brse_id)
            ->pluck('brse_name', 'brse_id')
            ->toArray();
        // 查询仓位数据
        $orgo_wafr_id = array_column($goods_data, 'orgo_wafr_id');
        $wafr_data = DB::table('warehouse_freight')
            ->whereIn('wafr_id', $orgo_wafr_id)
            ->pluck('wafr_name', 'wafr_id')
            ->toArray();
        // 查询订单商品仓位数据
        $orgo_id = array_column($goods_data, 'orgo_id');
        $find_orgf_data = DB::table('order_goods_freight as orgf')
            ->leftjoin('warehouse_freight as wafr', 'wafr.wafr_id', 'orgf.orgf_wafr_id')
            ->where('orgf_shop_id', $user_info->adm_shop_id)
            ->where('orgf_ord_id', $request['ord_id'])
            ->whereIn('orgf_orgo_id', $orgo_id)
            ->where('orgf_order_number', $info->ord_order_number)
            ->where('orgf_delete', 1)
            ->select('orgf_id', 'orgf_ord_id', 'orgf_order_number', 'orgf_orgo_id', 'orgf_wago_id', 'orgf_ware_id', 'orgf_wafr_id', 'orgf_goo_id', 'orgf_goo_quantity', 'orgf_goo_inventory', 'wafr_name')
            ->get()->toArray();
        $wor_id = DB::table('work_order')
            ->where('wor_order_id', $request['ord_id'])
            ->where('wor_delete', 1)
            ->where('wor_state', '!=', 11)
            ->select('wor_id', 'wor_number')
            ->orderBy('wor_id', 'desc')
            ->first();
        $find_rego_data = DB::table('recede_recycle')
            ->where(function ($query) use ($wor_id, $info) {
                if ($wor_id) {
                    $query->where('rec_ord_order_number', $info->ord_order_number)
                        ->orwhere('rec_ord_order_number', $wor_id->wor_number);
                } else {
                    $query->where('rec_ord_order_number', $info->ord_order_number);
                }
            })
            ->where(function ($query) use ($wor_id, $request) {
                if ($wor_id) {
                    $query->where('rec_ord_id', $request['ord_id'])
                        ->orwhere('rec_ord_id', $wor_id->wor_id);
                } else {
                    $query->where('rec_ord_id', $request['ord_id']);
                }
            })
            ->select('rec_id', 'rec_amount', 'rec_source_type')
            ->orderBy('rec_id', 'desc')
            ->first();
        if (!empty($find_rego_data)) {
            $find_rego_data_res = false;
        } else {
            $find_rego_data_res = true;
        }
        $new_new_goo_datas = [];
        if ($find_orgf_data && $find_rego_data_res && $user_info->shop_versions == 2) {
            $new_find_orgf_data = [];
            foreach ($find_orgf_data as $key => $value) {
                $orgf_goods_data = $goods_datas[$value->orgf_orgo_id];
                if (isset($orgf_goods_data)) {
                    // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                        if (!empty($orgf_goods_data['goo_brse_id'])) {
                            if ($orgf_goods_data['goo_class'] == 2) {
                                $orgf_goods_data['orgo_goo_name'] = $brse_data[$orgf_goods_data['goo_brse_id']] . ' ' . $orgf_goods_data['orgo_goo_name'];
                            } else {
                                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                    $orgf_goods_data['orgo_goo_name'] = $brse_data[$orgf_goods_data['goo_brse_id']] . ' ' . $orgf_goods_data['orgo_goo_name'];
                                }
                            }
                        }
                    }
                    // 显示品牌名称
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                        if ($orgf_goods_data['goo_class'] == 2) {
                            $orgf_goods_data['orgo_goo_name'] = $orgf_goods_data['goo_bra_name'] . ' ' .  $orgf_goods_data['orgo_goo_name'];
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $orgf_goods_data['orgo_goo_name'] = $orgf_goods_data['goo_bra_name'] . ' ' .  $orgf_goods_data['orgo_goo_name'];
                            }
                        }
                    }
                    $new_find_orgf_data[] = $orgf_goods_data['goo_id'];
                    $new_goo_data['orgo_goo_name'] = $orgf_goods_data['orgo_goo_name']; //商品名称
                    $new_goo_data['orgo_goo_goods_encode'] = $orgf_goods_data['orgo_goo_goods_encode']; //检索编码
                    $new_goo_data['orgo_goo_quantity'] = $value->orgf_goo_quantity; //商品数量
                    $new_goo_data['orgo_goo_price'] = $orgf_goods_data['orgo_goo_price']; //商品售价（单位：分）
                    $new_goo_data['orgo_is_recycle'] = $orgf_goods_data['orgo_is_recycle']; //回收状态：1回收2不回收
                    $new_goo_data['orgo_can_assign_quantity'] = $orgf_goods_data['orgo_can_assign_quantity']; //剩余可以派工单的商品数量
                    $new_goo_data['orgo_collection_price'] = $orgf_goods_data['orgo_collection_price']; //代收金额（单位：分）
                    $new_goo_data['orgo_state'] = $orgf_goods_data['orgo_state']; //商品状态1.正常 2.删除3回收的商品4换货商品5赠品商品6备用电池7临时商品8旧货商品
                    $new_goo_data['orgo_recycle_price'] = $orgf_goods_data['orgo_recycle_price']; //回收金额（单位：分）
                    $new_goo_data['orgo_recycle_quantity'] = $orgf_goods_data['orgo_recycle_quantity']; //商品回收数量
                    $new_goo_data['tem_goo_name'] = $orgf_goods_data['tem_goo_name']; //临时商品名称
                    $new_goo_data['orgo_assign_price'] = $orgf_goods_data['orgo_assign_price']; //派单金额
                    $new_goo_data['unit'] = $orgf_goods_data['goo_unit']; //单位
                    $new_goo_data['orgo_wafr_name'] = $value->wafr_name; //仓位
                    $new_goo_data['orgo_freight_space'] = DB::table('warehouse')
                        ->where('ware_id', $orgf_goods_data['orgo_ware_id'])
                        ->value('ware_freight_space'); //仓库编码
                    $new_new_goo_datas[] = $new_goo_data;
                    unset($new_goo_data);
                }
            }
        } else {
            foreach ($goods_data as $key => $value) {
                // 查询仓库简称
                $goods_data[$key]['orgo_freight_space'] = DB::table('warehouse')
                    ->where('ware_id', $value['orgo_ware_id'])
                    ->value('ware_freight_space');
                $goods_data[$key]['unit'] = $value['goo_unit'];
                // 判断系列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) {
                            $goods_data[$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'))) {
                                $goods_data[$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) {
                        $goods_data[$key]['orgo_goo_name'] = $value['goo_bra_name'] . ' ' .  $goods_data[$key]['orgo_goo_name'];
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $goods_data[$key]['orgo_goo_name'] = $value['goo_bra_name'] . ' ' .  $goods_data[$key]['orgo_goo_name'];
                        }
                    }
                }
                // 判断商品是否是从仓位出库
                if (!empty($value['orgo_wafr_id'])) {
                    // 仓位出库显示商品所在仓位
                    $goods_data[$key]['orgo_wafr_name'] = $wafr_data[$value['orgo_wafr_id']];
                } else {
                    $goods_data[$key]['orgo_wafr_name'] = '';
                }
                unset($goods_data[$key]['orgo_ware_id']);
                unset($goods_data[$key]['goo_class']);
                unset($goods_data[$key]['goo_brse_id']);
                unset($goods_data[$key]['orgo_wafr_id']);
            }
            $new_new_goo_datas = $goods_data;
        }

        // 获取打印缓存数据
        $cache_data = DB::table('print_cache')
            ->where('prca_create_adm_id', $user_info->adm_id) //创建人id
            ->where('prca_type', 1) //类型1.订单 2.工单
            ->select('prca_com_name', 'prca_serve_provider', 'prca_serve_order')
            ->first();
        if (empty($cache_data)) {
            $cache_data['prca_com_name'] = '';
            $cache_data['prca_serve_provider'] = '';
            $cache_data['prca_serve_order'] = '';
        }
        $data['order_data'] = $info;
        $data['goods_data'] = $new_new_goo_datas;
        $data['cache_data'] = $cache_data;
        $data['chun_data'] = $chun_data;
        $data['total_client_price'] = $total_client_price;

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

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

        $search_data = $request->all();

        // 实际金额最小钱数
        if (!empty($search_data['min_price'])) {
            $search_data['min_price'] = $search_data['min_price'] * 100;
        }
        // 实际金额最大钱数
        if (!empty($search_data['max_price'])) {
            $search_data['max_price'] = $search_data['max_price'] * 100;
        }

        $orderby_type = 'desc'; //排序类型，默认倒序查询
        // 当查询待接单状态订单时，按正序查询
        if (!empty($request['ord_wor_state']) && $request['ord_wor_state'] == 7) {
            $orderby_type = 'asc'; //默认排序类型
        }
        $data = DB::table('order as ord')
            ->leftJoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
            ->leftJoin('order_goods as orgo', 'orgo.orgo_ord_id', '=', 'ord.ord_id')
            ->leftJoin('shop as shop', 'shop.shop_id', '=', 'ord.ord_shop_id')
            ->where('ord_cid', $user_info->adm_cid)
            ->where('ord_superior_shop_id', $shop_id)
            ->where('ord_collection_bill', 1) //是否代收账单：1正常订单2代收账单
            ->where(function ($query) use ($search_data) { //仓库名称
                if (!empty($search_data['ware_id'])) {
                    $query->where('ord_ware_id', $search_data['ware_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //业务员搜索
                if (!empty($search_data['chun_adm_id'])) {
                    $query->where('chun_adm_id', $search_data['chun_adm_id'])
                        ->where('ord_type', 2);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['adm_name'])) {
                    $query->where('c.adm_name', 'like', '%' . $search_data['adm_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ord_order_number'])) {
                    $query->where('ord_order_number', 'like', '%' . $search_data['ord_order_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orcl_channel_unit'])) {
                    $query->where('orcl_channel_unit', 'like', '%' . $search_data['orcl_channel_unit'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orcl_name'])) {
                    $query->where('orcl_name', 'like', '%' . $search_data['orcl_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orcl_phone'])) {
                    $query->where('orcl_phone', 'like', '%' . $search_data['orcl_phone'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orcl_car_num'])) {
                    $query->where('orcl_car_num', 'like', '%' . $search_data['orcl_car_num'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //车型
                if (!empty($search_data['orcl_car_vehicle_type'])) {
                    $query->where('orcl_car_vehicle_type', 'like', '%' . $search_data['orcl_car_vehicle_type'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ord_type'])) {
                    $query->where('ord_type', $search_data['ord_type']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ord_service_type'])) {
                    $query->where('ord_service_type', $search_data['ord_service_type']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ord_create_id'])) {
                    $query->where('ord_create_id', $search_data['ord_create_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ord_state'])) {
                    $query->where('ord_state', $search_data['ord_state']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ord_wor_state'])) {
                    $query->where('ord_wor_state', $search_data['ord_wor_state']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ord_payment_way'])) {
                    $query->where('ord_payment_way', $search_data['ord_payment_way']);
                }
            })
            ->where(function ($query) use ($search_data) { //备注
                if (!empty($search_data['ord_remark'])) {
                    $query->where('ord_remark', 'like', '%' . $search_data['ord_remark'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //铺货类型：1是铺货2不是铺货
                if (!empty($search_data['orcl_chin_type'])) {
                    $query->where('orcl_chin_type', $search_data['orcl_chin_type']);
                }
            })
            ->where(function ($query) use ($search_data) { //创建时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                    $query->whereBetween('ord_create_time', [$search_data['create_time_start'], $search_data['create_time_end'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['create_time_start'])) {
                        $query->where('ord_create_time', '>=', $search_data['create_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['create_time_end'])) {
                            $query->where('ord_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ord_form_type'])) {
                    $query->where('ord_form_type', $search_data['ord_form_type']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orcl_shipment_party'])) {
                    $query->where('orcl_shipment_party', $search_data['orcl_shipment_party']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ord_service_shop_id'])) {
                    $query->where('ord_service_shop_id', $search_data['ord_service_shop_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orcl_order_type'])) {
                    $query->where('orcl_order_type', $search_data['orcl_order_type']);
                }
            })
            ->where(function ($query) use ($search_data) { //客户id
                if (!empty($search_data['ord_client_id'])) {
                    $query->where('ord_client_id', $search_data['ord_client_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //实际金额区间搜索
                // 如果选择最小钱数并且选择最大钱数
                if (!empty($search_data['min_price']) && !empty($search_data['max_price'])) {
                    $query->whereBetween('ord_actual_price', [$search_data['min_price'], $search_data['max_price']]);
                } else {
                    // 如果选择最小钱数
                    if (!empty($search_data['min_price'])) {
                        $query->where('ord_actual_price', '>=', $search_data['min_price']);
                    } else {
                        // 如果选择最大钱数
                        if (!empty($search_data['max_price'])) {
                            $query->where('ord_actual_price', '<=', $search_data['max_price']);
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) { //金额正负值1正值2负值
                if (!empty($search_data['ord_plus_minus'])) {
                    $query->where('ord_plus_minus', $search_data['ord_plus_minus']);
                }
            })
            ->where(function ($query) use ($search_data) { //商品检索编码
                if (!empty($search_data['goo_goods_encode'])) {
                    $query->where('orgo_goo_goods_encode', $search_data['goo_goods_encode']);
                }
            })
            ->where(function ($query) use ($search_data) { //速电单号（第三方单号）
                if (!empty($search_data['ord_other_system_number'])) {
                    $query->where('ord_other_system_number', 'like', '%' . $search_data['ord_other_system_number'] . '%');
                }
            })
            ->select('ord_order_number', 'ord_other_system_number', 'ord_create_id', 'ord_ware_id', 'ord_service_sepr_id', 'orcl_rescue_service_price', 'orgo_goo_name', 'orgo_goo_goods_encode', 'orgo_goo_price', 'orgo_goo_quantity', 'ord_goods_quantity', 'ord_actual_price', 'ord_order_price', 'ord_payment_way', 'ord_state', 'ord_wor_state', 'ord_wor_quantity', 'ord_type', 'ord_service_type', 'orcl_channel_unit', 'orcl_name', 'orcl_phone', 'orcl_car_num', 'orcl_address', 'ord_remark', 'ord_create_time', 'ord_plus_minus', 'orgo_state', 'ord_order_plus_minus', 'ord_client_id','shop_store_name')
            ->orderBy('ord_id', $orderby_type)
            ->get()->toArray();
        if (!empty($data)) {
            // 将对象转化为数组
            $data = json_decode(json_encode($data), true);
            $ord_create_id = array_unique(array_column($data, 'ord_create_id')); //创建人id
            $ord_ware_id = array_unique(array_column($data, 'ord_ware_id')); //仓库id
            $ord_client_id = array_unique(array_column($data, 'ord_client_id')); //选择的客户id，会员id/单位id
            // 查询创建人信息
            $find_adm_data = DB::table('admin')
                ->leftJoin('admin_shop_role as asr', 'asr.adm_id', '=', 'admin.adm_id')
                ->whereIn('admin.adm_id', $ord_create_id)
                ->where('asr.shop_id', $shop_id)
                ->pluck('admin.adm_name', 'admin.adm_id')
                ->toArray();
            // 查询客户单位
            $channel = DB::table('channel_unit')
                ->whereIn('chun_id', $ord_client_id)
                ->where('chun_shop_id', $shop_id)
                ->where('chun_state', '1')
                ->pluck('chun_unit_name', 'chun_id')
                ->toArray();
            // 查找仓库id对应的仓库名称
            $find_ware_data = DB::table('warehouse')
                ->whereIn('ware_id', $ord_ware_id)
                ->where('ware_shop_id', $user_info->adm_shop_id)
                ->pluck('ware_name', 'ware_id')
                ->toArray();
            $sepr_id = array_unique(array_column($data, 'ord_service_sepr_id'));
            // 查找服务项目id对应的名称
            $service_project = DB::table('service_project')
                ->whereIn('sepr_id', $sepr_id)
                ->pluck('sepr_name', 'sepr_id');
            foreach ($data as $key => $value) {
                if (isset($service_project[$value['ord_service_sepr_id']])) {
                    $data[$key]['ord_service_sepr_id'] = $service_project[$value['ord_service_sepr_id']];
                } else {
                    $data[$key]['ord_service_sepr_id'] = '';
                }
                $data[$key]['orcl_rescue_service_price'] = $value['orcl_rescue_service_price'] / 100; //服务项目金额
                // ord_service_type订单类型为退货单或orgo_state商品状态3回收的商品4换货商品
                if ($value['ord_service_type'] == 4 || $value['orgo_state'] == 3 || $value['orgo_state'] == 4) {
                    $data[$key]['orgo_goo_price'] = '-' . $value['orgo_goo_price'] / 100;
                } else {
                    $data[$key]['orgo_goo_price'] = $value['orgo_goo_price'] / 100;
                }
                $data[$key]['ord_actual_price'] = $value['ord_actual_price'] / 100; //结算金额
                $data[$key]['ord_order_price'] = $value['ord_order_price'] / 100; //订单金额
                // 结算方式
                if ($value['ord_payment_way'] == 1) {
                    $data[$key]['ord_payment_way'] = '账期';
                } elseif ($value['ord_payment_way'] == 2) {
                    $data[$key]['ord_payment_way'] = '现结';
                } elseif ($value['ord_payment_way'] == 3) {
                    $data[$key]['ord_payment_way'] = '微信';
                } elseif ($value['ord_payment_way'] == 4) {
                    $data[$key]['ord_payment_way'] = '支付宝';
                }
                // 结算状态
                if ($value['ord_state'] == '1') {
                    $data[$key]['ord_state'] = '未结算';
                } elseif ($value['ord_state'] == '2') {
                    $data[$key]['ord_state'] = '结算中';
                } elseif ($value['ord_state'] == '3') {
                    $data[$key]['ord_state'] = '已结算';
                } elseif ($value['ord_state'] == '4') {
                    $data[$key]['ord_state'] = '已代收';
                }
                // 订单的工单状态
                if ($value['ord_wor_state'] == '1') {
                    $data[$key]['ord_wor_state'] = '未派工单';
                } elseif ($value['ord_wor_state'] == '2') {
                    $data[$key]['ord_wor_state'] = '服务中';
                } elseif ($value['ord_wor_state'] == '3') {
                    $data[$key]['ord_wor_state'] = '售后中';
                } elseif ($value['ord_wor_state'] == '4') {
                    $data[$key]['ord_wor_state'] = '已完成';
                } elseif ($value['ord_wor_state'] == '5') {
                    $data[$key]['ord_wor_state'] = '无工单';
                } elseif ($value['ord_wor_state'] == '6') {
                    $data[$key]['ord_wor_state'] = '审核活动';
                } elseif ($value['ord_wor_state'] == '7') {
                    $data[$key]['ord_wor_state'] = '待接单';
                } elseif ($value['ord_wor_state'] == '8') {
                    $data[$key]['ord_wor_state'] = '锁定';
                } elseif ($value['ord_wor_state'] == '9') {
                    $data[$key]['ord_wor_state'] = '撤销';
                } elseif ($value['ord_wor_state'] == '10') {
                    $data[$key]['ord_wor_state'] = '终止';
                } elseif ($value['ord_wor_state'] == '11') {
                    $data[$key]['ord_wor_state'] = '取消订单';
                } elseif ($value['ord_wor_state'] == '12') {
                    $data[$key]['ord_wor_state'] = '待审核';
                }
                // 订单类型
                if ($value['ord_type'] == '1') {
                    $data[$key]['ord_type'] = '会员零售';
                } elseif ($value['ord_type'] == '2') {
                    $data[$key]['ord_type'] = '客户单位';
                } elseif ($value['ord_type'] == '3') {
                    $data[$key]['ord_type'] = '速电派单';
                } elseif ($value['ord_type'] == '4') {
                    $data[$key]['ord_type'] = '第三方派单';
                } elseif ($value['ord_type'] == '5') {
                    $data[$key]['ord_type'] = '运营中心给门店派单';
                }
                // 服务类型
                if ($value['ord_service_type'] == '1') {
                    $data[$key]['ord_service_type'] = '服务单';
                } elseif ($value['ord_service_type'] == '2') {
                    $data[$key]['ord_service_type'] = '销售单';
                } elseif ($value['ord_service_type'] == '3') {
                    $data[$key]['ord_service_type'] = '换货单';
                } elseif ($value['ord_service_type'] == '4') {
                    $data[$key]['ord_service_type'] = '退货单';
                } elseif ($value['ord_service_type'] == '5') {
                    $data[$key]['ord_service_type'] = '发货单';
                } elseif ($value['ord_service_type'] == '6') {
                    $data[$key]['ord_service_type'] = '结清单';
                } elseif ($value['ord_service_type'] == '7') {
                    $data[$key]['ord_service_type'] = '救援单';
                }
                // 客户单位名称
                if (isset($channel[$value['ord_client_id']])) {
                    $data[$key]['orcl_channel_unit'] = $channel[$value['ord_client_id']];
                } else {
                    $data[$key]['orcl_channel_unit'] = '';
                }
                // 仓库
                if ($value['ord_ware_id'] == '0') {
                    $data[$key]['ord_ware_id'] = '';
                } else {
                    $data[$key]['ord_ware_id'] = $find_ware_data[$value['ord_ware_id']];
                }
                // 创建人
                if (isset($find_adm_data[$value['ord_create_id']])) {
                    $data[$key]['ord_create_id'] = $find_adm_data[$value['ord_create_id']];
                } else {
                    $data[$key]['ord_create_id'] = '';
                }
                // 商品编号
                $data[$key]['orgo_goo_goods_encode'] = empty("\t" . $value['orgo_goo_goods_encode']) ? '' : "\t" . $value['orgo_goo_goods_encode'];
                $data[$key]['orgo_goo_name'] = empty($value['orgo_goo_name']) ? '' : $value['orgo_goo_name'];
                $data[$key]['orgo_goo_price'] = empty($data[$key]['orgo_goo_price']) ? 0 : $data[$key]['orgo_goo_price'];
                unset($data[$key]['ord_plus_minus']);
                unset($data[$key]['orgo_state']);
                unset($data[$key]['ord_order_plus_minus']);
                unset($data[$key]['ord_client_id']);
            }
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'没有符合条件的数据']);
        }
        $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
        // 创建文件夹
        if (!file_exists($pathName)) {
            mkdir($pathName, 0775, true);
            chmod($pathName, 0775);
        }

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

        $where['action_name'] = '订单列表';
        $where['field_name'] = ['订单号', '速电单号', '录单员', '仓库名称', '服务项目', '服务金额', '商品名称', '商品编号', '单价', '商品数量', '商品总数量', '结算金额', '订单金额', '结算方式', '结算状态', '订单的工单状态', '工单数量', '订单类型', '服务类型', '客户单位', '客户姓名', '客户电话', '车牌号', '地址', '订单备注', '添加时间'];
        // 调用导出的公共方法
        export::publicExport(
            $streamFilename, //路径
            $where,    //sheet名及其每一行的标题
            $data      //导出数据
        );

        // 判断文件是否存在 存在则成功  不存在则失败
        if (file_exists($streamFilename)) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'storage/excel/' . $streamFileRand]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'导出失败']);
        }
    }

    // 打印次数提交,更新备注
    public function printNumber(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderController;
        $error_message = $verify_data->printNumberValidator($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;

        // 判断是否有打印数据
        $prnu_id = DB::table('print_number')
            ->where('prnu_adm_cid', $user_info->adm_cid)
            ->where('prnu_superior_shop_id', $shop_id)
            ->where('prnu_type', 1)
            ->where('prnu_original_id', $request['ord_id'])
            ->select('prnu_id', 'prnu_print_num')
            ->first();

        $prnu_data['prnu_adm_cid'] = $user_info->adm_cid;   //公司id
        $prnu_data['prnu_shop_id'] = $user_info->adm_shop_id;   //所属门店id
        $prnu_data['prnu_superior_shop_id'] = $shop_id;   //所属总店id
        $prnu_data['prnu_type'] = 1;   //所属类型
        $prnu_data['prnu_original_id'] = $request['ord_id'];   //订单id
        $prnu_data['prnu_update_time'] = date('Y-m-d H:i:s');
        DB::beginTransaction();
        if ($prnu_id) {
            $prnu_data['prnu_print_num'] = $prnu_id->prnu_print_num + 1;   //打印次数
            $prnu_res = DB::table('print_number')
                ->where('prnu_original_id', $request['ord_id'])
                ->update($prnu_data);
        } else {
            $prnu_data['prnu_print_num'] = 1;   //打印次数
            $prnu_res = DB::table('print_number')->insert($prnu_data);
        }

        // 添加订单备注
        if (!empty($request['ord_remark'])) {
            $wor_id = DB::table('work_order')
                ->where('wor_order_id', $request['ord_id'])
                ->value('wor_id');
            $wor_remark = orderRemark($user_info, $request['ord_id'], $wor_id, $request['ord_remark'], '订单列表-打印');
        } else {
            $wor_remark = true;
        }

        // 判断是否存储了缓存：存储了更新,没有存储新增
        $prca_id = DB::table('print_cache')
            ->where('prca_create_adm_id', $user_info->adm_id) //创建人id
            ->where('prca_type', 1) //类型1.订单 2.工单
            ->value('prca_id');
        $prca_data['prca_com_name'] = $request['prca_com_name'] ? $request['prca_com_name'] : ''; //公司名称
        $prca_data['prca_serve_provider'] = $request['prca_serve_provider'] ? $request['prca_serve_provider'] : ''; //服务提供商
        $prca_data['prca_serve_order'] = $request['prca_serve_order'] ? $request['prca_serve_order'] : ''; //打印单的类型
        $prca_data['prca_type'] = 1; //类型1.订单 2.工单
        $prca_data['prca_update_time'] = date('Y-m-d H:i:s'); //更新时间

        if (empty($prca_id)) {
            // 新增
            $prca_data['prca_cid'] = $user_info->adm_cid; //公司id
            $prca_data['prca_shop_id'] = $user_info->adm_shop_id; //门店id
            $prca_data['prca_superior_shop_id'] = $shop_id; //所属总店id
            $prca_data['prca_create_adm_id'] = $user_info->adm_id; //创建人id
            $prca_data['prca_type'] = 1; //类型1.订单 2.工单
            $prca_res = DB::table('print_cache')->insert($prca_data);
        } else {
            // 更新
            $prca_res = DB::table('print_cache')
                ->where('prca_id', $prca_id)
                ->update($prca_data);
        }

        if ($prnu_res && $prca_res && $wor_remark) {
            DB::commit();
            $ord_order_number = DB::table('order')->where('ord_id', $request['ord_id'])->value('ord_order_number');
            Common::addLog($user_info, getRealIp($request), '订单列表', '打印', $ord_order_number . '打印成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'打印成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'打印失败']);
        }
    }

    // 冲单操作【暂时用不到】
    public function againstOrder(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderController;
        $error_message = $verify_data->againstOrderValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 订单状态
        $ord_data = DB::table('order as o')
            ->leftJoin('order_client as oc', 'oc.orcl_ord_id', '=', 'o.ord_id')
            ->where('ord_id', $request['ord_id'])
            ->first(['ord_state', 'ord_order_number', 'ord_type', 'ord_client_id', 'orcl_channel_unit', 'ord_create_time']);
        if ($ord_data->ord_state != 3) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'此订单不是已核销状态']);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $request['actual_price'] = $request['actual_price'] * 100; //换算成分
        DB::beginTransaction();
        $recr_id = ReceivableBill::create(
            $user_info, //用户信息
            10, //类型：10订单冲单
            0, //应收账款id
            $request['ord_id'], //原始id(订单id)
            $ord_data->ord_order_number, //应收账款单号/原始号(订单编号)
            $ord_data->ord_type, //客户类型：1.门店零售 2.来往单位 3.加盟店 4会员零售(工单代收）
            $ord_data->ord_client_id, //会员id/来往单位id
            $ord_data->orcl_channel_unit, //会员/来往单位名称
            $request['actual_price'], //结算金额
            $request['remit_time'], //汇款时间
            $request['acti_id'], //会计科目id
            $request['actual_price'], //实际金额
            0, //抹零金额
            1,  //状态：1.未核销 2.已核销
            1,  //应收账单id是否是自己 1.不是 2.是
            $request['remark'] ? $request['remark'] : '',  //备注
            0,  //已收金额
            '', //截止时间
            $request['plus_minus'], //金额正负:1正2负值
            15, //显示类型
            2, //是否合并代收：1是2否
            $order_data->ord_create_time,
            0 //技师是否收钱：0未选择1是2否
        );

        // 生成结款明细
        $acset_id = AccountingSettlement::add(
            $user_info, // [用户信息]
            15, // [单据类型1订单2订单账单3工单账单4采购账单5销售账单6预收款]
            $request['ord_id'], // [与单据类型对应的id]
            $ord_data->ord_order_number, // [与单据类型对应的单号]
            $ord_data->ord_type, // [买家类型1门店零售2来往单位]
            $ord_data->ord_client_id, // [会员/客户id]
            $ord_data->orcl_channel_unit, // [来往单位名称]
            $request['acti_id'], // [会计科目id]
            $request['plus_minus'], // [类型1收入2支出]
            $request['actual_price'], // [实际金额](此次的实收金额)
            $request['actual_price'], // [合计金额](此次的应收金额)
            0, // [欠收金额](此次结款后还应收金额)
            0, // [抹零金额]
            $request['remark'] ? $request['remark'] : '' //[备注]
        );
        if ($recr_id && $acset_id) {
            Common::addLog($user_info, getRealIp($request), '订单列表', '冲单', '订单：' . $ord_data->ord_order_number . '冲单成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'订单冲单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'订单冲单失败']);
        }
    }

    // 审核【暂时用不到】
    public function activityAudit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderController;
        $error_message = $verify_data->auditShowValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        if ($request['search_type'] == '1') {
            // 获取当前操作账号信息
            $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;

            $info = DB::table('order as o')
                ->leftJoin('warehouse as w', 'o.ord_ware_id', '=', 'w.ware_id')
                ->leftJoin('order_client as c', 'o.ord_orcl_id', '=', 'c.orcl_id')
                ->where('o.ord_cid', $user_info->adm_cid)
                ->where('o.ord_superior_shop_id', $shop_id)
                ->where('o.ord_id', $request['ord_id'])
                ->select('o.ord_order_number', 'o.ord_create_time', 'o.ord_order_price', 'o.ord_wor_state', 'o.ord_wor_quantity', 'o.ord_actual_price', 'o.ord_payment_way', 'o.ord_goods_quantity', 'o.ord_type', 'o.ord_state', 'o.ord_remark', 'o.ord_create_id', 'o.ord_service_type', 'w.ware_name', 'w.ware_leader_id', 'orcl_name', 'orcl_phone', 'orcl_address', 'orcl_channel_unit', 'orcl_car_num', 'ord_client_id', 'w.ware_freight_space', 'ord_service_sepr_id', 'ord_orla_id', 'orcl_province', 'orcl_city', 'orcl_county', 'ord_service_shop_id', 'ord_acti_id', 'ord_acti_row')
                ->first();
            // 查询服务门店名称
            $info->ord_service_shop_name = DB::table('shop')->where('shop_id', $info->ord_service_shop_id)->value('shop_store_name');

            // 订单类型如果是和客户单位的话 追加客户等级
            if ($info->ord_type == 2) {
                $info->chun_adm_name = DB::table('channel_unit')
                    ->where('chun_id', $info->ord_client_id)
                    ->value('chun_adm_id');
            } else {
                $info->chun_adm_name = "";
            }
            if ($info->ord_service_sepr_id != '0') {
                // 查询服务项目名称
                $sepr_data = DB::table('service_project')
                    ->where('sepr_id', $info->ord_service_sepr_id)
                    ->select('sepr_name', 'sepr_order_money')
                    ->first();
                $info->ord_service_sepr_name = $sepr_data->sepr_name;
                $info->sepr_order_money = $sepr_data->sepr_order_money;
            }

            // 追加订单标签
            $info->ord_orla_name = DB::table('order_label')
                ->where('orla_id', $info->ord_orla_id)
                ->value('orla_name');

            // 获取采购商(仓库负责人)/创建人
            $adm_id = [
                $info->ord_create_id,
                $info->ware_leader_id,
                $info->chun_adm_name,
            ];
            $adm_id = array_filter($adm_id);
            $find_admin = DB::table('admin')
                ->whereIn('adm_id', $adm_id)
                ->select('adm_id', 'adm_name', 'adm_phone')
                ->get()
                ->toArray();
            $adm_name = array_column($find_admin, null, 'adm_id');

            $info->create_name = $adm_name[$info->ord_create_id]->adm_name; //创建人
            $info->ware_leader_name = $info->ware_leader_id ? $adm_name[$info->ware_leader_id]->adm_name : ''; //仓库负责人
            $info->chun_adm_phone = $info->chun_adm_name ? $adm_name[$info->chun_adm_name]->adm_phone : ''; //业务员联系电话
            $info->chun_adm_name = $info->chun_adm_name ? $adm_name[$info->chun_adm_name]->adm_name : ''; //业务员

            // 获取该订单下的商品信息
            $goods_data = DB::table('order_goods')
                ->where('orgo_ord_id', $request['ord_id'])
                ->select('orgo_goo_name', 'orgo_goo_goods_encode', 'orgo_goo_quantity', 'orgo_goo_price', 'orgo_is_recycle', 'orgo_can_assign_quantity', 'orgo_collection_price', 'orgo_state', 'orgo_tem_goo_name as tem_goo_name')
                ->get();

            // 获取该订单下的活动
            $find_acti = DB::table('activity')
                ->where('acti_id', $info->ord_acti_id)
                ->select('acti_number', 'acti_name', 'acti_activity_type', 'acti_start_time', 'acti_end_time', 'acti_activity_nature', 'acti_state', 'acti_activity_days', 'acti_cycle_number')
                ->first();
            // 活动类型
            if ($find_acti->acti_activity_type == '1') { //折扣
                $find_acdi = DB::table('activity_discount as acdi')
                    ->where('acdi_acti_id', $info->ord_acti_id)
                    ->where('acdi_row', $info->ord_acti_row)
                    ->select('acdi_id', 'acdi_goo_id', 'acdi_discount', 'acdi_row')
                    ->first();
                $data['find_acdi'] = $find_acdi;
            } elseif ($find_acti->acti_activity_type == '2') { //买送
                // 买送
                $find_acdo = DB::table('activity_donate as acdo')
                    ->where('acdo_acti_id', $info->ord_acti_id)
                    ->where('acdo_row', $info->ord_acti_row)
                    ->select('acdo_acti_id', 'acdo_goo_id', 'acdo_gift_id', 'acdo_purchase_quantity', 'acdo_attached_quantity', 'acdo_row')
                    ->first();
                $data['find_acdo'] = $find_acdo;
            } elseif ($find_acti->acti_activity_type == '3') { //买赠
                // 买赠
                $find_acdos = DB::table('activity_donate as acdo')
                    ->where('acdo_acti_id', $info->ord_acti_id)
                    ->where('acdo_row', $info->ord_acti_row)
                    ->select('acdo_acti_id', 'acdo_goo_id', 'acdo_gift_id', 'acdo_purchase_quantity', 'acdo_attached_quantity', 'acdo_row')
                    ->first();
                $find_acdos->gift_name = DB::table('goods')
                    ->where('goo_id', $find_acdos->acdo_gift_id)
                    ->value('goo_name');
                $data['find_acdos'] = $find_acdos;
            } elseif ($find_acti->acti_activity_type == '4') { //满减
                // 满减
                $find_acdr = DB::table('activity_discount_reduction')
                    ->where('acdr_acti_id', $info->ord_acti_id)
                    ->where('acdr_row', $info->ord_acti_row)
                    ->select('acdr_acti_id', 'acdr_reduction_price', 'acdr_credit_price', 'acdr_row')
                    ->first();
                $data['find_acdr'] = $find_acdr;
            } elseif ($find_acti->acti_activity_type == '5') { //现结折扣
                // 现结折扣
                $find_acdrs = DB::table('activity_discount_reduction')
                    ->where('acdr_acti_id', $info->ord_acti_id)
                    ->where('acdr_row', $info->ord_acti_row)
                    ->select('acdr_acti_id', 'acdr_reduction_price', 'acdr_discount', 'acdr_row')
                    ->first();
                $data['find_acdrs'] = $find_acdrs;
            } elseif ($find_acti->acti_activity_type == '6') { //累计返点
                // 累计返点
                $find_accp = DB::table('activity_cash_points')
                    ->where('accp_acti_id', $info->ord_acti_id)
                    ->select('accp_acti_id', 'accp_transaction_price', 'accp_integral')
                    ->first();
                $find_accr = DB::table('activity_cumulative_rebates')
                    ->where('accr_acti_id', $info->ord_acti_id)
                    ->select('accr_acti_id', 'accr_transaction_price', 'accr_integral', 'accr_row')
                    ->first();
                // $data['find_accp'] = $find_accp;
                // $data['find_accr'] = $find_accr;
            } elseif ($find_acti->acti_activity_type == '7') { //高价回收
                // 高价回收
                $find_achr = DB::table('activity_high_recycling as achr')
                    ->where('achr_acti_id', $info->ord_acti_id)
                    ->select('achr_acti_id', 'achr_goo_id', 'achr_recycle_quantity', 'achr_recycle_price')
                    ->first();
                $data['find_achr'] = $find_achr;
            } elseif ($find_acti->acti_activity_type == '8') { //大批量采购
                // 大批量采购
                $find_acpr = DB::table('activity_procurement as acpr')
                    ->where('acpr_acti_id', $info->ord_acti_id)
                    ->where('acpr_row', $info->ord_acti_row)
                    ->select('acpr_acti_id', 'acpr_goo_id', 'acpr_goods_quantity', 'acpr_recycle_quantity', 'acpr_row')
                    ->first();
                $data['find_acpr'] = $find_acpr;
            }

            $data['order_data'] = $info;
            $data['goods_data'] = $goods_data;
            $data['find_acti'] = $find_acti;

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

        // 验证数据
        $verify_data = new VerifyOrderController;
        $error_message = $verify_data->auditValidator($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 ($request['type'] == '1') {
            $res = $this->activityPass($user_info, $request->all());
        } else {
            $res = $this->activityReject($user_info, $request->all());
        }

        if ($res['code'] == 200) {
            // 查询信息
            $ord_order_number = DB::table('order')
                ->where('ord_id', $request['ord_id'])
                ->value('ord_order_number');
            Common::addLog($user_info, getRealIp($request), '订单列表', '审核', $ord_order_number . '审核成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'审核成功']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'审核失败']);
        }
    }

    // 订单审核通过(活动)【暂时用不到】
    private function activityPass($user_info, $request)
    {
        DB::beginTransaction();
        $ord_data['ord_wor_state'] = 1;
        $ord_data['ord_update_time'] = date('Y-m-d H:i:s');

        $ord_res = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->update($ord_data);
        // 生成操作记录
        $order_record = orderLog($user_info, $request['ord_id'], 0, '活动审核');
        if ($ord_res && $order_record) {
            DB::commit();
            return ['code'=>200, 'msg'=>'success', 'data'=>'通过成功'];
        } else {
            DB::rollBack();
            return ['code'=>500, 'msg'=>'error', 'data'=>'通过失败'];
        }
    }

    // 订单审核驳回(活动)【暂时用不到】
    private function activityReject($user_info, $request)
    {
        DB::beginTransaction();
        // 删除订单客户表数据
        $orcl_id = DB::table('order_client')
            ->where('orcl_ord_id', $request['ord_id'])
            ->delete();

        // 查询订单商品数据
        $find_orgo_id = DB::table('order_goods')
            ->where('orgo_ord_id', $request['ord_id'])
            ->select('orgo_id', 'orgo_ware_id', 'orgo_waon_class', 'orgo_goo_id', 'orgo_goo_inventory', 'orgo_goo_quantity')
            ->get()->toArray();

        $orgo_goo_id = array_column($find_orgo_id, 'orgo_goo_id'); //商品id
        $orgo_ware_id = array_column($find_orgo_id, 'orgo_ware_id', 'orgo_goo_id'); //仓库id
        $orgo_waon_class = array_column($find_orgo_id, 'orgo_waon_class', 'orgo_goo_id'); //仓库类别
        $orgo_goo_quantity = array_column($find_orgo_id, 'orgo_goo_quantity', 'orgo_goo_id'); //商品数量
        $orgo_goo_inventory = array_column($find_orgo_id, 'orgo_goo_inventory', 'orgo_goo_id'); //库存扣除方式

        // 将原来发货单的商品，锁定库存转正常库存
        $lock_turn_normal = Warehouse::lockTurnNormal(
            $user_info, //用户信息
            $orgo_ware_id, //商品id=>仓库id
            $orgo_goo_id, //商品id
            $orgo_goo_quantity, //商品id=>商品数量
            $orgo_goo_inventory, //商品id=>出库类型
            $orgo_waon_class //商品id=>仓库类别
        );

        // 查询订单单号
        $ord_number = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->value('ord_order_number');

        // 删除订单商品表数据
        $orgo_id = DB::table('order_goods')
            ->where('orgo_ord_id', $request['ord_id'])
            ->delete();

        // 删除订单表数据
        $ord_id = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->delete();

        if ($orcl_id && $lock_turn_normal && $orgo_id && $ord_id) {
            DB::commit();
            return ['code'=>200, 'msg'=>'success', 'data'=>'驳回成功'];
        } else {
            DB::rollBack();
            return ['code'=>500, 'msg'=>'error', 'data'=>'驳回失败'];
        }
    }

    // 订单列表生成工单+给下级门店派单
    public function createWorkAssign(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderController;
        $error_message = $verify_data->assignmentOrderValidator($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;

        // 获取订单数据
        $order = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->first();
        $order = json_decode(json_encode($order), true);
        // 查询客户信息
        $order_client = DB::table('order_client')
            ->where('orcl_id', $order['ord_orcl_id'])
            ->first();
        $order_client = json_decode(json_encode($order_client), true);
        $find_order_goods = DB::table('order_goods')
            ->where('orgo_ord_id', $request['ord_id'])
            ->select('orgo_can_assign_quantity', '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);

        DB::beginTransaction();

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

        // 救援单的服务项目金额
        $orcl_rescue_service_price = $order_client['orcl_rescue_service_price'] / 100;
        // 救援单的代收金额
        $orcl_rescue_collection_price = $order_client['orcl_rescue_collection_price'] / 100;
        // 救援单派单金额
        $orcl_rescue_assign_price = $order_client['orcl_rescue_assign_price'] / 100;

        if (empty($find_order_goods)) {
            $goo_all_price = $orcl_rescue_service_price * 100;
            $goo_assign_all_price = $orcl_rescue_assign_price * 100;
        } else {
            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 ($order_client['orcl_shipment_party'] == 5 || $order_client['orcl_shipment_party'] == 4 || $order_client['orcl_shipment_party'] == 3) {
                    $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 ($order_client['orcl_shipment_party'] == 4 || $order_client['orcl_shipment_party'] == 3 || $order_client['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;
        }
        // 添加工单表数据
        $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'] = $order['ord_order_number']; //订单号
        $wor_data['wor_service_shop_id'] = $order['ord_service_shop_id']; //服务门店id
        $wor_data['wor_service_sepr_id'] = $order['ord_service_sepr_id']; //服务项目id
        $wor_data['wor_service_adm_id'] = $order['ord_service_adm_id']; //服务技师id
        // 订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单
        $wor_data['wor_service_type'] = $order['ord_service_type'];
        // 是否走技师流程  1是  2否
        if (!empty($order_client['orcl_whether_app']) && ($order_client['orcl_whether_app'] == 2) && ($order_client['orcl_shipment_party'] == 4)) {
            // 虚拟加盟店，不走技师流程
            $wor_data['wor_service_state'] = 6;
            $wor_data['wor_state'] = 8;
        } else {
            $wor_data['wor_service_state'] = 1;
            $wor_data['wor_state'] = 3;
        }
        // 审核：1.待审核 2.合格 3.不合格
        $wor_data['wor_pass'] = 1;
        $wor_data['wor_type'] = $order['ord_type'];
        $wor_data['wor_remark'] = $order['ord_remark']; //工单备注
        $wor_data['wor_ware_id'] = 0; //仓库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; //总的商品数量
        $wor_data['wor_appoint_time'] = $order_client['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($order['ord_remark'])) {
            $wor_remark = orderRemark($user_info, $request['ord_id'], $wor_id, $order['ord_remark'], '工作总台');
        } else {
            $wor_remark = true;
        }
        if (!empty($find_order_goods)) {
            // 7. 添加工单商品表数据
            foreach ($wogo_data as $key => $value) {
                $wogo_data[$key]['wogo_wor_id'] = $wor_id;
                $wogo_res = DB::table('work_good')->insert($wogo_data[$key]);
            }
        } else {
            $wogo_res = true;
        }

        // 8. 添加工单客户表数据
        if ($order['ord_type'] == '2') {
            $chun_adm_id = DB::table('channel_unit')
                ->where('chun_id', $order['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' => $order['ord_client_id'], //渠道单位或者客户单位id
            'wocl_adm_id' => $chun_adm_id, //业务员id
            'wocl_channel_unit' => $order_client['orcl_channel_unit'],
            'wocl_name' => $order_client['orcl_name'],
            'wocl_phone' => $order_client['orcl_phone'],
            'wocl_car_num' => $order_client['orcl_car_num'], //车牌号
            'wocl_car_vehicle_type' => $order_client['orcl_car_vehicle_type'], //车型
            'wocl_province' => $order_client['orcl_province'],
            'wocl_city' => $order_client['orcl_city'],
            'wocl_county' => $order_client['orcl_county'],
            'wocl_address' => $order_client['orcl_address'],
            'wocl_chin_type' => $order_client['orcl_chin_type'], //铺货类型：1是铺货 2不是铺货
            'wocl_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' => $order_client['orcl_standby_battery_type'],
            'wocl_junk_type' => $order_client['orcl_junk_type'], //是否回收旧货1是2否
            'wocl_whether_app' => $order_client['orcl_whether_app'], //是否走技师流程1是2否
            'wocl_precise_lock' => $order_client['orcl_precise_lock'], //精确打卡1是 2否
        ];
        if ($order_client['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($order['ord_service_type'], [1, 7])) {
            // 订单类型为服务单、救援单的有图片上传模板，根据订单类型，获取当前门店的图片上传模板
            $image_manager = new ImageUpload();
            $find_shit_id = $image_manager->getOrderTypeImageTemplate($user_info->adm_shop_id, $order['ord_service_type']);
            $wocl_data['wocl_shit_id'] = $find_shit_id; //图片模板id
        }
        $wocl_id = DB::table('work_client')->insertGetId($wocl_data);

        $work_record_res = orderLog($user_info, 0, $wor_id, '生成工单');
        $assign_record_res = orderLog($user_info, 0, $wor_id, '派单');
        // 判断是否是外派门店
        if ($order_client['orcl_shipment_party'] == 5) {
            // 给门店创建订单
            $find_user_info = DB::table('admin')
                ->leftJoin('admin_shop_role as asr', 'asr.adm_id', '=', 'admin.adm_id')
                ->where('asr.shop_id', $order['ord_service_shop_id'])
                ->select('admin.adm_id', 'asr.shop_cid as adm_cid', 'asr.shop_id as adm_shop_id', 'asr.superior_shop_id as shop_superior_id', 'admin.adm_name', 'admin.adm_phone')
                ->first();

            $add_shop_order_res = $this->addShopOrder($wocl_data, $find_user_info, $order, $order_client, $find_order_goods, $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 {
            $add_shop_order_res = true;
        }
        if ($order['ord_wor_state'] == 1) {
            $ord_data['ord_wor_state'] = 2;
        }
        $ord_data['ord_wor_quantity'] = $order['ord_wor_quantity'] + 1;
        $ord_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_res =  DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->update($ord_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()->toArray();
        $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_id', $value['orgo_id'])
                ->where('orgo_ord_id', $request['ord_id'])
                ->update(['orgo_can_assign_quantity' => $assign_quantity, 'orgo_update_time' => date('Y-m-d H:i:s')]);
            if (!$orgo_res) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'派单失败！']);
            }
        }
        if ($ord_res && $add_shop_order_res && $wc_updres && $wor_id && $wogo_res && $wocl_id && $work_record_res && $assign_record_res && $wor_remark) {
            Common::addLog($user_info, getRealIp($request), '订单列表', '派单', $wor_order_number . '派单成功');
            if (!empty($order['ord_service_adm_id']) && $order_client['orcl_whether_app'] == 1) {
                $wechat_msg['pushtype'] = 1; //工单推送
                $wechat_msg['adm_id'] = $order['ord_service_adm_id']; //推送人
                $wechat_msg['wor_number'] = $wor_order_number; //工单号
                $wechat_msg['ord_number'] = $order['ord_order_number']; //订单号
                $wechat_msg['order_type'] = ordType($order['ord_service_type']); //订单类型
                $wechat_msg['user_name'] = $order_client['orcl_name']; //姓名
                $wechat_msg['user_phone'] = $order_client['orcl_phone']; //手机号
                $wechat_msg['user_dress'] = $order_client['orcl_province'] . $order_client['orcl_city'] . $order_client['orcl_county'] . $order_client['orcl_address']; //手机号
                $wechat_msg['tittle'] = '您有新工单请及时处理'; //手机
                $wechat_msg['remark'] = isset($order['ord_remark']) ? $order['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'=>'派单失败']);
        }
    }

    // 为门店生成订单
    private function addShopOrder($wocl_data, $user_info, $order, $order_client, $goods_data, $wocl_id)
    {
        // 判断是否为加盟店账号,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_data['ord_wor_state'] = 7;
        $ord_data['ord_client_id'] = $order['ord_client_id']; //选择客户id
        $ord_data['ord_order_number'] = $ord_order_number; //订单号
        // 订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单 7救援单
        $ord_data['ord_service_type'] = $order['ord_service_type'];
        $ord_data['ord_payment_way'] = $order['ord_payment_way']; // 结算方式1.账期 2.现结 3微信 4支付宝
        $ord_data['ord_type'] = 5; //买家类型：1门店零售2渠道单位3速电派单4第三方派单
        $ord_data['ord_remark'] = $order['ord_remark']; //订单备注
        $ord_data['ord_service_sepr_id'] = $order['ord_service_sepr_id']; //服务项目id
        $ord_data['ord_service_shop_id'] = $order['ord_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 = $order_client['orcl_rescue_service_price'];
        // 救援单的服务派单金额
        $orcl_rescue_assign_price = $order_client['orcl_rescue_assign_price'];
        // 救援单的代收金额

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

        if (in_array($order['ord_service_type'], [1, 7])) {
            // 运营中心给门店派单，订单类型为服务单、救援单的有图片上传模板，用运营中心的图片模板
            $find_shit_id = $wocl_data['wocl_shit_id'];
            $orcl_data['orcl_shit_id'] = $find_shit_id; //图片模板id
        }
        // 添加订单客户表数据
        $orcl_data = [
            'orcl_ord_id' => $ord_id,
            'orcl_channel_unit' => $order_client['orcl_channel_unit'],
            'orcl_adm_id' => $chun_adm_id, //业务员id
            'orcl_name' => $order_client['orcl_name'],
            'orcl_phone' => $order_client['orcl_phone'],
            'orcl_car_num' => $order_client['orcl_car_num'],
            'orcl_car_vehicle_type' => $order_client['orcl_car_vehicle_type'], //车型
            'orcl_province' => $order_client['orcl_province'],
            'orcl_city' => $order_client['orcl_city'],
            'orcl_county' => $order_client['orcl_county'],
            'orcl_address' => $order_client['orcl_address'],
            'orcl_chin_type' => $order_client['orcl_chin_type'], //铺货类型：1是铺货 2不是铺货
            'orcl_collect_state' => $order_client['orcl_collect_state'],
            // 救援单的服务项目金额
            'orcl_rescue_service_price' => $orcl_rescue_assign_price,
            // 救援单的代收金额
            'orcl_rescue_collection_price' => $orcl_rescue_collection_price,
            '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' => $order_client['orcl_junk_type'], //是否为旧货1是2否
            'orcl_shit_id' => $find_shit_id,
        ];
        $orcl_id = DB::table('order_client')->insertGetId($orcl_data);

        // $sepr_order_money = 0; //服务项目的订单金额
        $recycle_all_price = 0; //订单回收金额
        $goo_all_assign_price = 0; //接单金额
        // 订单类型：7救援单，查询服务项目的订单金额
        if ($order['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; // 订单金额（单位：分）
                $ord_edit_data['ord_actual_price'] = $orcl_rescue_assign_price; // 结算金额（单位：分）
                $ord_edit_data['ord_goods_quantity'] = 0; // 商品总数量
                $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'=>'门店生成订单失败'];
                }
            }
        }

        // 有商品数据
        if ($goods_data) {
            foreach ($goods_data as $key => $value) {
                // 搜索商品id对应的商品名称、商品编号
                $find_goods_data = DB::table('goods')
                    ->where('goo_id', $value['orgo_goo_id'])
                    ->select('goo_state', '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 gocs')
                        ->leftJoin('goods as goo', 'goo.goo_id', '=', 'gocs.goco_goo_id')
                        ->where('goco_shop_id', $shop_id)
                        ->where('goco_parent_goo_id', $value['orgo_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_goass_price = DB::table('goods_system_affiliate')
                        ->where('gosa_shop_id', $shop_id)
                        ->where('gosa_goo_id', $value['orgo_goo_id'])
                        ->value('gosa_assign_price');
                    // 查询系统商品属性表
                    $gosa_another_name = DB::table('goods_system_affiliate')
                        ->where('gosa_goo_id', $value['orgo_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;
                    }
                }

                $goo_all_assign_price += $value['orgo_assign_price'] * $value['orgo_goo_quantity'];

                // 订单商品表
                $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_wago_id'] = 0;
                $orgo_data[$key]['orgo_waon_class'] = 1;
                $orgo_data[$key]['orgo_actual_goo_id'] = $find_goods_data->goo_class == 1 ? $shop_goods->goo_id : $value['orgo_goo_id'];
                $orgo_data[$key]['orgo_goo_id'] = $find_goods_data->goo_class == 1 ? $shop_goods->goo_id : $value['orgo_goo_id'];
                $orgo_data[$key]['orgo_goo_price'] = $value['orgo_assign_price'];
                $orgo_data[$key]['orgo_goo_quantity'] = $value['orgo_goo_quantity'];
                $orgo_data[$key]['orgo_can_assign_quantity'] = $value['orgo_can_assign_quantity'];
                $orgo_data[$key]['orgo_collection_price'] = $value['orgo_collection_price'];
                $orgo_data[$key]['orgo_goo_inventory'] = 0;
                $orgo_data[$key]['orgo_update_time'] = date('Y-m-d H:i:s');
                if (!empty($value['orgo_tem_goo_name'])) {
                    $orgo_data[$key]['orgo_tem_goo_name'] = $value['orgo_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['orgo_state'];
                $orgo_data[$key]['orgo_assign_price'] = $value['orgo_assign_price'];
            }

            $orgo_res = DB::table('order_goods')->insert($orgo_data);
        }

        if ($order_client['orcl_assign_price'] < 0 || $order['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 || $order['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负值
        }
        // 4. 更改订单表客户id、订单金额
        $ord_edit_data['ord_orcl_id'] = $orcl_id;
        $ord_edit_data['ord_order_price'] = $goo_all_assign_price; // 订单金额（单位：分）
        $ord_edit_data['ord_actual_price'] = $goo_all_assign_price; // 结算金额（单位：分）
        $ord_edit_data['ord_goods_quantity'] = $order['ord_goods_quantity']; // 商品总数量
        $ord_edit_data['orcl_assign_price'] = abs($goo_all_assign_price); //派单金额（单位：分）
        $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 assignmentOrder(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderController;
        $error_message = $verify_data->assignmentOrderValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        DB::beginTransaction();
        $order_data = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->first();
        if ($order_data->ord_service_shop_id == $order_data->ord_shop_id) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'此订单不是外派订单']);
        }
        if (in_array($order_data->ord_wor_state, [2, 3, 4, 6, 7, 8])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'此订单状态不能派单']);
        }

        $user_info = Common::getUserInfo($request['api_token']);

        $order_goods = DB::table('order_goods')
            ->where('orgo_ord_id', $request['ord_id'])
            ->get();
        $order_goods = json_decode(json_encode($order_goods), true);
        // 订单客户表
        $order_client = DB::table('order_client')
            ->where('orcl_ord_id', $request['ord_id'])
            ->first();
        $order_client = json_decode(json_encode($order_client), true);
        $qecycle_quantity = 0; //工单计划总的旧货回收数量
        $wor_recycle_price = 0; //总的回收金额
        $wor_is_recycle = 2; //  1.回收2.不回收
        $assign_price = 0; //总价格
        foreach ($order_goods as $key => $value) {
            if ($value['orgo_is_recycle'] == 1) {
                $qecycle_quantity += $value['orgo_recycle_quantity'];
                $wor_recycle_price += $value['orgo_recycle_quantity'] * $value['orgo_recycle_price'];
                $wor_is_recycle = 1;
            }
            $assign_price += $value['orgo_assign_price']; //派单金额(单位:分)
        }
        $order_data = json_decode(json_encode($order_data), true);
        // 1. 添加工单表数据
        $wor_order_number = Common::workRule($user_info);
        $wor_data['wor_cid'] = $order_data['ord_cid'];
        $wor_data['wor_superior_shop_id'] = $order_data['ord_superior_shop_id'];
        $wor_data['wor_shop_id'] = $order_data['ord_shop_id'];
        $wor_data['wor_create_id'] = $order_data['ord_create_id'];
        $wor_data['wor_number'] = $wor_order_number;
        $wor_data['wor_order_id'] = $order_data['ord_id'];
        $wor_data['wor_order_number'] = $order_data['ord_order_number'];
        $wor_data['wor_service_shop_id'] = $order_data['ord_service_shop_id'];
        $wor_data['wor_service_sepr_id'] = $order_data['ord_service_sepr_id'];
        $wor_data['wor_service_adm_id'] = $order_data['ord_service_adm_id'];
        $wor_data['wor_service_type'] = $order_data['ord_service_type'];
        $wor_data['wor_service_state'] = 1;
        $wor_data['wor_orla_id'] = $order_data['ord_orla_id'];
        $wor_data['wor_state'] = 1; //1.新订单 2未派单 3待接单/已派单 4.未出发/已接单
        $wor_data['wor_pass'] = 1; //1.待审核 2.合格 3.不合格 4系统锁定 5速电锁定6第三方锁定7速电待审核
        $wor_data['wor_type'] = $order_data['ord_type'];
        $wor_data['wor_recycle_number'] = $qecycle_quantity;
        $wor_data['wor_actual_price'] = $order_data['ord_actual_price'];
        $wor_data['wor_is_recycle'] = $wor_is_recycle;
        $wor_data['wor_goo_amount'] = $order_data['ord_goods_quantity'];
        $wor_data['wor_plus_minus'] = $order_data['ord_plus_minus'];
        $wor_data['wor_recycle_price'] = $wor_recycle_price;
        $wor_id = DB::table('work_order')->insertGetId($wor_data);

        foreach ($order_goods as $key => $value) {
            $order_goods[$key]['orgo_goo_price'] = $value['orgo_assign_price']; //派单金额(单位:分)
            $wor_goo_data[$key]['wogo_goo_id'] = $value['orgo_goo_id']; //商品id
            $wor_goo_data[$key]['wogo_is_recycle'] = $value['orgo_is_recycle']; //回收状态：1回收2不回收
            $wor_goo_data[$key]['wogo_goo_name'] = $value['orgo_goo_name']; //商品名称
            $wor_goo_data[$key]['wogo_goo_goods_encode'] = $value['orgo_goo_goods_encode']; //检索编码
            $wor_goo_data[$key]['wogo_goo_type'] = $value['orgo_goo_type']; //商品类型 1正常商品2赠品商品3活动商品4旧货商品
            $wor_goo_data[$key]['wogo_state'] = $value['orgo_state']; //商品状态1.正常 2.删除3回收的商品4换货商品5赠品商品6备用电池
            $wor_goo_data[$key]['wogo_goo_price'] = $value['orgo_goo_price']; //商品售价（单位：分）
            $wor_goo_data[$key]['wogo_collection_price'] = $value['orgo_collection_price']; //代收金额（单位：分）
            $wor_goo_data[$key]['wogo_recycle_price'] = $value['orgo_recycle_price']; //回收金额（单位：分）
            $wor_goo_data[$key]['wogo_goo_amount'] = $value['orgo_goo_quantity']; //订单商品数量
            $wor_goo_data[$key]['wogo_goo_inventory'] = $value['orgo_goo_inventory']; //库存扣除方式1.良品 2.优先
            $wor_goo_data[$key]['wogo_recycle_quantity'] = $value['orgo_recycle_quantity']; //商品回收数量
            $wor_goo_data[$key]['wogo_wor_id'] = $wor_id; //工单id
            $wor_goo_data[$key]['wogo_waon_class'] = 0; //仓库类别
            $wor_goo_data[$key]['wogo_assign_price'] = $value['orgo_assign_price']; //派单金额(单位:分)
        }
        $wor_goods_res = DB::table('work_good')->insert($wor_goo_data);

        $wor_client['wocl_client_id'] = $order_client['orcl_client_id'];
        $wor_client['wocl_channel_unit'] = $order_client['orcl_channel_unit'];
        $wor_client['wocl_name'] = $order_client['orcl_name'];
        $wor_client['wocl_phone'] = $order_client['orcl_phone'];
        $wor_client['wocl_car_num'] = $order_client['orcl_car_num'];
        $wor_client['wocl_province'] = $order_client['orcl_province'];
        $wor_client['wocl_city'] = $order_client['orcl_city'];
        $wor_client['wocl_county'] = $order_client['orcl_county'];
        $wor_client['wocl_address'] = $order_client['orcl_address'];
        $wor_client['wocl_chin_type'] = $order_client['orcl_chin_type'];
        $wor_client['wocl_collect_state'] = $order_client['orcl_collect_state'];
        $wor_client['wocl_acti_id'] = $order_client['orcl_acc_subject_id'];
        $wor_client['wocl_rescue_service_price'] = $order_client['orcl_rescue_service_price'];
        $wor_client['wocl_rescue_collection_price'] = $order_client['orcl_rescue_collection_price'];
        $wor_client['wocl_wor_id'] = $wor_id;
        $wor_client['wocl_wor_type'] = 2; //1系统工单2外派工单
        $wor_client['wocl_assign_price'] = $order_client['orcl_assign_price']; //派单总金额
        $wor_client['wocl_plus_minus'] = $order_client['orcl_plus_minus']; //1系统工单2外派工单

        // 添加加盟店订单数据
        $order_number = Common::orderRule($user_info);
        $number = $order_data['ord_order_number'];
        $order_data['ord_superior_shop_id'] = $order_data['ord_service_shop_id'];
        $order_data['ord_order_number'] = $order_number;
        $order_data['ord_create_id'] = $user_info->adm_id;
        $order_data['ord_service_shop_id'] = $order_data['ord_superior_shop_id'];
        $order_data['ord_wor_state'] = 7;
        $order_data['ord_wor_quantity'] = 0;
        $order_data['ord_actual_price'] = $assign_price + $order_client['orcl_rescue_service_price'] - $wor_recycle_price;
        $order_data['ord_order_price'] = $assign_price + $order_client['orcl_rescue_service_price'] - $wor_recycle_price;
        unset($order_data['ord_id']);
        unset($order_data['ord_create_time']);
        $order_res = DB::table('order')->insertGetId($order_data);

        $wor_client['wocl_join_ord_id'] = $order_res;
        $wor_client_res = DB::table('work_client')->insertGetId($wor_client);
        // 添加加盟店订单商品数据
        foreach ($order_goods as $key => $value) {
            unset($order_goods[$key]['orgo_id']);
            $order_goods[$key]['orgo_ord_id'] = $order_res;
            $order_goods[$key]['orgo_order_number'] = $order_number;
        }
        $order_goods_res = DB::table('order_goods')->insert($order_goods);

        // 添加加盟店订单客户数据
        unset($order_client['orcl_id']);
        unset($order_client['orcl_assign_price']);
        unset($order_client['orcl_plus_minus']);
        $order_client['orcl_ord_id'] = $order_res;
        $order_client['orcl_join_wor_id'] = $wor_id;
        $order_client_res = DB::table('order_client')->insertGetId($order_client);
        $join_order['ord_orcl_id'] = $order_client_res;
        $join_res = DB::table('order')
            ->where('ord_id', $order_res)
            ->update($join_order);

        // 总店下的工单数量
        $ord_res = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->increment('ord_wor_quantity', 1, ['ord_wor_state' => 2]);

        // 添加操作记录
        $work_record = orderLog($user_info, $request['ord_id'], $wor_id, '生成外派工单');

        if ($order_res && $order_client_res && $order_goods_res && $join_res && $wor_id && $wor_goods_res && $wor_client_res && $ord_res) {
            Common::addLog($user_info, getRealIp($request), '订单列表', '外派工单', '订单:' . $number . ' 外派成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'外派成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'外派失败']);
        }
    }

    // 加盟店改单审核
    public function applyFor($user_info, $request)
    {
        foreach ($request['goo_id'] as $key => $value) {
            $orgo_data[$key]['wged_order_id'] = $request['ord_id'];
            $orgo_data[$key]['wged_ware_id'] = isset($request['ware_id']) ? $request['ware_id'] : 0;
            $orgo_data[$key]['wged_waon_class'] = isset($request['goo_waon_class'][$key]) ? $request['goo_waon_class'][$key] : 1;
            $orgo_data[$key]['wged_goo_id'] = $value;
            // 搜索商品id对应的商品名称、商品编号
            $find_goods_data = DB::table('goods')
                ->where('goo_id', $value)
                ->select('goo_name', 'goo_goods_encode', 'goo_type', 'goo_ampere_hour', 'goo_price', '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;
                }
            }
            $orgo_data[$key]['wged_goo_price'] = $request['goo_price'][$key] * 100;
            $orgo_data[$key]['wged_goo_amount'] = $request['goo_quantity'][$key];
            $orgo_data[$key]['wged_recycle_quantity'] = $request['goo_recycle_quantity'][$key];
            $orgo_data[$key]['wged_recycle_price'] = $request['goo_recycle_price'][$key] * 100;
            $orgo_data[$key]['wged_collection_price'] = $request['goo_collection_price'][$key] * 100;
            $orgo_data[$key]['wged_goo_inventory'] = isset($request['goo_inventory'][$key]) ? $request['goo_inventory'][$key] : 1;
            $orgo_data[$key]['wged_update_time'] = date('Y-m-d H:i:s');

            $orgo_data[$key]['wged_goo_name'] = $find_goods_data->goo_name;
            $orgo_data[$key]['wged_goo_goods_encode'] = $find_goods_data->goo_goods_encode;
            $orgo_data[$key]['wged_goo_type'] = isset($request['goo_type'][$key]) ? $request['goo_type'][$key] : $find_goods_data->goo_type;
            $orgo_data[$key]['wged_goo_ampere_hour'] = $find_goods_data->goo_ampere_hour;
            $orgo_data[$key]['wged_state'] = $request['goo_state'][$key];

            // 换货商品金额处理
            if ($request['goo_state'][$key] == 1 || $request['goo_state'][$key] == 5) {
                $orgo_data[$key]['wged_is_recycle'] = $request['goo_recycle'][$key];
            }
        }
        $work_good_res = DB::table('work_good_edit')->insert($orgo_data);
        if (empty($work_good_res)) {
            return false;
        }
        // 判断是否更改客户信息
        if ($request['ord_client_id'] > 0) {
            $orcl_data['orcl_channel_unit'] = isset($request['orcl_channel_unit']) ? $request['orcl_channel_unit'] : '';
            $orcl_data['wced_name'] = $request['orcl_name'];
            $orcl_data['wced_phone'] = $request['orcl_phone'];
            $orcl_data['wced_car_num'] = isset($request['orcl_car_num']) ? $request['orcl_car_num'] : '';
            $orcl_data['wced_province'] = $request['orcl_province'];
            $orcl_data['wced_city'] = $request['orcl_city'];
            $orcl_data['wced_county'] = $request['orcl_county'];
            $orcl_data['wced_address'] = $request['orcl_address'];
            $orcl_data['wced_order_id'] = $request['ord_id'];
            $orcl_data['wced_collect_state'] = $request['orcl_collect_state'];
            $orcl_id = DB::table('work_client_edit')->insert($orcl_data);
            if (empty($orcl_id)) {
                return false;
            }
        }
        return true;
    }

    // 添加备注
    public function remark(Request $request)
    {
        if (empty($request['remark']) && empty($request['ord_id'])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
        }
        $number = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->value('ord_order_number');
        $wor_id = DB::table('work_order')
            ->where('wor_order_id', $request['ord_id'])
            ->value('wor_id');
        $wor_id = $wor_id ?: 0;
        $user_info = Common::getUserInfo($request['api_token']);

        $wor_remark = orderRemark($user_info, $request['ord_id'], $wor_id, $request['remark'], '订单列表');
        if ($wor_remark) {
            Common::addLog($user_info, getRealIp($request), '订单列表', '备注', '订单:' . $number . ' 添加备注 :' . $request['remark']);
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'备注成功']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'备注失败']);
        }
    }

    // 生成凭证【暂时用不到】
    public function orderVoucher(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;

        ignore_user_abort();
        set_time_limit(0);

        // 查询类型为发货单,并且已经出库的数据
        $find_ord_data = DB::table('dispatch_bill')
            ->where('dego_cid', $user_info->adm_cid)
            ->where('dego_shop_id', $user_info->adm_shop_id)
            ->where('dego_order_type', 1)
            ->where('dego_type', 2)
            ->select('dego_wor_id', 'dego_cid', 'dego_superior_shop_id', 'dego_shop_id', 'dego_original_number', 'dego_client_type', 'dego_client_id', 'dego_create_adm_id', 'dego_update_time')
            ->get()->toArray();
        $cost_price = 0;
        foreach ($find_ord_data as $key => $value) {
            // 根据订单id和单号查询出结算金额,代收金额,旧货回收金额
            $find_order_data = DB::table('order as ord')
                ->leftjoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
                ->where('ord_id', $value->dego_wor_id)
                ->where('ord_cid', $value->dego_cid)
                ->where('ord_superior_shop_id', $value->dego_superior_shop_id)
                ->where('ord_shop_id', $value->dego_shop_id)
                ->where('ord_order_number', $value->dego_original_number)
                ->select('ord_order_price', 'ord_actual_price', 'ord_plus_minus', 'ord_order_plus_minus', 'orcl_channel_unit', 'orcl_name', 'ord_create_time', 'ord_ware_id')
                ->first();
            if ($find_order_data) {
                // 根据订单id和商品状态,查询出回收的商品
                $find_goods_data = DB::table('order_goods')
                    ->where('orgo_ord_id', $value->dego_wor_id)
                    ->where('orgo_state', 3)
                    ->select('orgo_id', 'orgo_ord_id', 'orgo_goo_id', 'orgo_goo_price', 'orgo_goo_quantity')
                    ->get()->toArray();
                $goo_recycle_price = [];
                foreach ($find_goods_data as $kk => $vv) {
                    if (!isset($goo_recycle_price[$vv->orgo_goo_id])) {
                        $goo_recycle_price[$vv->orgo_goo_id] = 0;
                    }
                    $goo_recycle_price[$vv->orgo_goo_id] += $vv->orgo_goo_price * $vv->orgo_goo_quantity; //商品数量
                }
                $recycle_amount = 0;
                foreach ($goo_recycle_price as $kkk => $vvv) {
                    $recycle_amount += $vvv;
                }
                // 根据订单id,查询商品
                $find_orgo_data = DB::table('order_goods')
                    ->where('orgo_ord_id', $value->dego_wor_id)
                    ->where('orgo_order_number', $value->dego_original_number)
                    ->where('orgo_state', '!=', 2)
                    ->select('orgo_id', 'orgo_ord_id', 'orgo_ware_id', 'orgo_waon_class', 'orgo_goo_id', 'orgo_goo_price', 'orgo_goo_quantity', 'orgo_state')
                    ->get()->toArray();
                if ($find_orgo_data) {
                    $cost_price = 0;
                    foreach ($find_orgo_data as $kkkk => $vvvv) {
                        // 获取当前月份商品成本价
                        if ($vvvv->orgo_ware_id == '0') {
                            $vvvv->orgo_ware_id = $value->ord_ware_id;
                        } else {
                            $vvvv->orgo_ware_id = $vvvv->orgo_ware_id;
                        }
                        if ($vvvv->orgo_state != 3 && $vvvv->orgo_state != 7 && $vvvv->orgo_state != 8) {
                            /* $newprice = DB::table('enters_sells_saves')
                                ->where('ense_goo_id', $vvvv->orgo_goo_id)
                                ->where('ense_goo_warehouse', $vvvv->orgo_ware_id)
                                ->where('ense_goo_waretype', $vvvv->orgo_waon_class)
                                ->where('ense_order_number', $value->dego_original_number)
                                ->select('ense_end_price')
                                ->first();
                            if ($newprice) {
                                $cost_price += $newprice->ense_end_price * $vvvv->orgo_goo_quantity;
                            } else {
                                $cost_price = 0;
                            } */
                            $list_items = DB::table('enters_sells_saves')
                                ->where('ense_shop_id', $shop_id)
                                ->where('ense_goo_id', $vvvv->orgo_goo_id)
                                ->where('ense_goo_warehouse', $vvvv->orgo_ware_id)
                                ->where('ense_goo_waretype', $vvvv->orgo_waon_class)
                                ->where('ense_order_number', $value->dego_original_number)
                                ->select('ense_goo_id')
                                ->groupBy('ense_goo_id')
                                ->get()->toArray();
                            $ids = array();
                            foreach ($list_items as $kone => $vone) {
                                foreach ($vone as $kkone => $vvone) {
                                    $ids[] = $vvone;
                                }
                            }
                            $list = DB::table('enters_sells_saves')
                                ->where('ense_shop_id', $shop_id)
                                ->where('ense_goo_warehouse', $vvvv->orgo_ware_id)
                                ->where('ense_goo_waretype', $vvvv->orgo_waon_class)
                                ->whereIn('ense_goo_id', $ids)
                                ->where('ense_order_number', $value->dego_original_number)
                                ->select('ense_id', 'ense_goo_id', 'ense_end_price')
                                ->orderBy('ense_id', 'asc')
                                ->get()
                                ->toArray();
                            $dataayyar = array();
                            if ($list) {
                                $listarray = array();
                                $list = json_decode(json_encode($list), true);
                                foreach ($list as $ktwo => $vtwo) {
                                    if (isset($listarray[$vtwo['ense_goo_id']])) {
                                        $listarray[$vtwo['ense_goo_id']]['ense_end_price'] = $vtwo['ense_end_price'];
                                    } else {
                                        $listarray[$vtwo['ense_goo_id']] = $vtwo;
                                    }
                                }
                                $i = "0";
                                foreach ($listarray as $kthree => $vthree) {
                                    $dataayyar[$i] = $vthree;
                                    $i = $i + 1;
                                }
                            }
                            if ($dataayyar) {
                                foreach ($dataayyar as $k3 => $v3) {
                                    $cost_price += $v3['ense_end_price'] * $vvvv->orgo_goo_quantity;
                                }
                            } else {
                                $cost_price = 0;
                            }
                        }
                    }
                    // 判断凭证单据是否存在
                    $vore_id = DB::table('voucher_receipts')
                        ->where('vore_cid', $user_info->adm_cid)
                        ->where('vore_shop_id', $user_info->adm_shop_id)
                        ->where('vore_ord_id', $value->dego_wor_id)
                        ->where('vore_ord_number', $value->dego_original_number)
                        ->where('vore_order_type', 1)
                        ->where('vore_state', 1)
                        ->select('vore_ord_id', 'vore_ord_number')
                        ->first();
                    if (empty($vore_id)) {
                        // 凭证单据报表
                        $vore_data['vore_cid'] = $value->dego_cid; //公司id
                        $vore_data['vore_superior_shop_id'] = $value->dego_superior_shop_id; //总店id
                        $vore_data['vore_shop_id'] = $value->dego_shop_id; //门店id
                        $vore_data['vore_create_id'] = $value->dego_create_adm_id; //创建人
                        $vore_data['vore_order_type'] = 1; //单号类型1.订单2.工单3.采购单4.销售单
                        $vore_data['vore_ord_id'] = $value->dego_wor_id; //订单id
                        $vore_data['vore_ord_number'] = $value->dego_original_number; //订单单号
                        $vore_data['vore_plus_minus'] = $find_order_data->ord_plus_minus; //金额正负1正值2负值
                        $vore_data['vore_actual_price'] = $find_order_data->ord_actual_price / 100; //结算金额
                        $vore_data['vore_recycle_price'] = $recycle_amount / 100; //回收金额
                        $vore_data['vore_early_costing'] = $cost_price; //成本
                        $vore_data['vore_type'] = $value->dego_client_type; //单位类型1会员零售2客户单位3速电派单
                        $vore_data['vore_client_id'] = $value->dego_client_id; //客户单位/客户id
                        if ($value->dego_client_type == 1) { //会员零售
                            $vore_data['vore_channel_unit'] = $find_order_data->orcl_name;
                        } elseif ($value->dego_client_type == 2) { //客户单位
                            $vore_data['vore_channel_unit'] = $find_order_data->orcl_channel_unit;
                        } elseif ($value->dego_client_type == 3) { //速电派单
                            $vore_data['vore_channel_unit'] = $find_order_data->orcl_channel_unit;
                        }
                        $vore_data['vore_create_time'] = $find_order_data->ord_create_time;
                        $vore_id = DB::table('voucher_receipts')->insertGetId($vore_data);
                        // 凭证借贷表(结算金额)
                        $volo_data[0]['volo_shop_id'] = $value->dego_shop_id;
                        $volo_data[0]['volo_vore_id'] = $vore_id;
                        $volo_data[0]['volo_type'] = 1; //类型1借方2贷方
                        $volo_data[0]['volo_borrow_subject'] = '1122'; //借方科目
                        $volo_data[0]['volo_borrow_subject_name'] = '应收账款'; //借方科目名称
                        $volo_data[0]['volo_loan_subject'] = '600101'; //贷方科目
                        $volo_data[0]['volo_loan_subject_name'] = '主营业务收入'; //贷方科目名称

                        $volo_data[0]['volo_borrow_costing_subject'] = '640101'; //借方成本科目
                        $volo_data[0]['volo_borrow_costing_name'] = '主营业务成本'; //借方成本名称
                        $volo_data[0]['volo_borrow_costing'] = $cost_price; //借方成本
                        $volo_data[0]['volo_loan_costing_subject'] = '140501'; //贷方成本科目
                        $volo_data[0]['volo_loan_costing_name'] = '库存商品'; //贷方成本名称
                        $volo_data[0]['volo_loan_costing'] = $cost_price; //贷方成本

                        $volo_data[0]['volo_update_time'] = $find_order_data->ord_create_time; //更新时间
                        // 凭证借贷表(回收金额)
                        $volo_data[1]['volo_shop_id'] = $value->dego_shop_id;
                        $volo_data[1]['volo_vore_id'] = $vore_id;
                        $volo_data[1]['volo_type'] = 1; //类型1借方2贷方
                        $volo_data[1]['volo_borrow_subject'] = '140501'; //借方科目
                        $volo_data[1]['volo_borrow_subject_name'] = '库存商品'; //借方科目名称
                        $volo_data[1]['volo_borrow_price'] = $recycle_amount / 100; //借方金额
                        $volo_data[1]['volo_loan_subject'] = ''; //贷方科目
                        $volo_data[1]['volo_loan_subject_name'] = ''; //贷方科目名称
                        $volo_data[1]['volo_loan_price'] = 0; //贷方金额

                        $volo_data[1]['volo_borrow_costing_subject'] = ''; //借方成本科目
                        $volo_data[1]['volo_borrow_costing_name'] = ''; //借方成本名称
                        $volo_data[1]['volo_borrow_costing'] = 0; //借方成本
                        $volo_data[1]['volo_loan_costing_subject'] = ''; //贷方成本科目
                        $volo_data[1]['volo_loan_costing_name'] = ''; //贷方成本名称
                        $volo_data[1]['volo_loan_costing'] = 0; //贷方成本

                        if ($find_order_data->ord_plus_minus == 2) {
                            $volo_data[0]['volo_loan_price'] =  (-1) * $find_order_data->ord_actual_price / 100 + $recycle_amount / 100; //贷方金额
                            $volo_data[0]['volo_borrow_price'] = (-1) * $find_order_data->ord_actual_price / 100; //借方金额
                        } else {
                            $volo_data[0]['volo_loan_price'] = $find_order_data->ord_actual_price / 100 + $recycle_amount / 100; //贷方金额
                            $volo_data[0]['volo_borrow_price'] = $find_order_data->ord_actual_price / 100; //借方金额
                        }

                        $volo_data[1]['volo_update_time'] = $find_order_data->ord_create_time; //更新时间
                        if (!empty($find_goods_data)) {
                            $volo_id = DB::table('voucher_loan')->insert($volo_data);
                        } else {
                            $volo_id = DB::table('voucher_loan')->insert($volo_data[0]);
                        }
                    } else {
                        $vore_id = true;
                        $volo_id = true;
                    }
                } else {
                    $vore_id = true;
                    $volo_id = true;
                }
            } else {
                $vore_id = true;
                $volo_id = true;
            }
        }
        if ($vore_id && $volo_id) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '订单列表', '生成凭证', '生成凭证成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'生成凭证成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'生成凭证失败']);
        }
    }

    // 修改客户单位
    public function editUnit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderController;
        $error_message = $verify_data->editUnitValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 查询订单数据
        $order_data = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->select('ord_order_number', 'ord_client_id', 'ord_orbi_id')
            ->first();
        if ($order_data->ord_orbi_id > 0) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已生成账单，无法修改客户单位！']);
        }
        if ($request['chun_id'] == $order_data->ord_client_id) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'修改前后单位一致，请重新选择！']);
        }

        // 查询订单对应的应收应付
        $receivable_result = DB::table('receivable_credit')
            ->where('recr_original_id', $request['ord_id'])
            ->where('recr_original_number', $order_data->ord_order_number)
            ->where('recr_state', 2)
            ->select('recr_id', 'recr_account_type', 'recr_state')
            ->get()->toArray();
        if ($receivable_result) {
            // 应收应付是否已确定
            foreach ($receivable_result as $k => $v) {
                if ($v->recr_account_type == '1' || $v->recr_account_type == '10') {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已结算，无法修改！']);
                }
            }
        }

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

        // 提交的新客户单位
        $new_channel_unit = DB::table('channel_unit')
            ->where('chun_id', $request['chun_id'])
            ->select('chun_id', 'chun_unit_name', 'chun_name', 'chun_phone', 'chun_chty_id', 'chun_province', 'chun_city', 'chun_county', 'chun_address')
            ->first();

        // 编辑前客户单位
        $order_client_res = DB::table('order_client')
            ->where('orcl_ord_id', $request['ord_id'])
            ->select('orcl_client_id', 'orcl_channel_unit', 'orcl_name', 'orcl_phone', 'orcl_order_type', 'orcl_province', 'orcl_city', 'orcl_county', 'orcl_address')
            ->first();
        if ($order_client_res->orcl_client_id == '0') {
            $oldname = $order_client_res->orcl_name;
        } else {
            $oldname = $order_client_res->orcl_channel_unit;
        }
        // 更改前的车主信息
        $before_change = $order_client_res->orcl_name . '，' . $order_client_res->orcl_phone . '，' . $order_client_res->orcl_province . $order_client_res->orcl_city . $order_client_res->orcl_county . $order_client_res->orcl_address;
        $edit_type_hint = '没有更改车主信息';

        DB::beginTransaction();
        // 应收应付客户单位更改
        $find_receivable_data = DB::table('receivable_credit')
            ->where('recr_shop_id', $user_info->adm_shop_id)
            ->where('recr_original_id', $request['ord_id'])
            ->where('recr_original_number', $order_data->ord_order_number)
            ->select('recr_id')
            ->first();
        if ($find_receivable_data) {
            $receivable_data['recr_client_type'] = 2; //客户类型：1.会员零售 2.来往单位
            $receivable_data['recr_client_id'] = $new_channel_unit->chun_id;
            $receivable_data['recr_client_name'] = $new_channel_unit->chun_unit_name;
            $receivable_res = DB::table('receivable_credit')
                ->where('recr_shop_id', $user_info->adm_shop_id)
                ->where('recr_original_id', $request['ord_id'])
                ->where('recr_original_number', $order_data->ord_order_number)
                ->update($receivable_data);
            unset($receivable_data);
            if (!$receivable_res) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'修改失败0']);
            }
        }

        // 查询订单相关的结款明细数据
        $find_acset_data = DB::table('accounting_settlement')
            ->where('acset_shop_id', $user_info->adm_shop_id)
            ->where('acset_original_id', $request['ord_id'])
            ->where('acset_original_number', $order_data->ord_order_number)
            ->value('acset_id');
        if ($find_acset_data) {
            $accounting_data['acset_client_type'] = 2; //买家类型：1会员零售2客户单位
            $accounting_data['acset_client_id'] = $new_channel_unit->chun_id;
            $accounting_data['acset_client_name'] = $new_channel_unit->chun_unit_name;
            $accounting_res = DB::table('accounting_settlement')
                ->where('acset_shop_id', $user_info->adm_shop_id)
                ->where('acset_original_id', $request['ord_id'])
                ->where('acset_original_number', $order_data->ord_order_number)
                ->update($accounting_data);
            unset($accounting_data);
            if (!$accounting_res) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'修改失败00']);
            }
        }

        // 修改订单表
        $ord_data['ord_type'] = 2; //买家类型:1门店零售2客户单位3速电派单4第三方派单
        $ord_data['ord_client_id'] = $request['chun_id'];
        $ord_res = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->where('ord_client_id', $order_data->ord_client_id)
            ->update($ord_data);
        // 修改订单客户表信息
        $client_data['orcl_client_id'] = $new_channel_unit->chun_id;
        $client_data['orcl_channel_unit'] = $new_channel_unit->chun_unit_name;
        // edit_type 更改车主信息：1是2否
        if (isset($request['edit_type']) && $request['edit_type'] == 1) {
            $client_data['orcl_name'] = $new_channel_unit->chun_name;
            $client_data['orcl_phone'] = $new_channel_unit->chun_phone;
            $client_data['orcl_province'] = $new_channel_unit->chun_province;
            $client_data['orcl_city'] = $new_channel_unit->chun_city;
            $client_data['orcl_county'] = $new_channel_unit->chun_county;
            $client_data['orcl_address'] = $new_channel_unit->chun_address;
            $edit_type_hint = '更改车主信息';
        }
        $orcl_client_res = DB::table('order_client')
            ->where('orcl_ord_id', $request['ord_id'])
            ->update($client_data);
        unset($client_data);

        // 修改工单客户信息
        // 查询工单数据
        $find_work_data = DB::table('work_order')
            ->where('wor_order_id', $request['ord_id'])
            ->where('wor_order_number', $order_data->ord_order_number)
            ->select('wor_id', 'wor_number')
            ->get()->toArray();

        // 修改发货单的客户单位
        $dispatch_data['dego_client_type'] = 2; //买家类型：1.会员零售2.客户单位
        $dispatch_data['dego_client_id'] = $new_channel_unit->chun_id;
        // 查询是否有订单对应的发货单
        $find_dego_id = DB::table('dispatch_bill')
            ->where('dego_wor_id', $request['ord_id'])
            ->where('dego_original_number', $order_data->ord_order_number)
            ->where('dego_order_type', 1)
            ->value('dego_id');
        if ($find_dego_id) {
            // 更改发货单对应的客户单位
            $dispatch_res = DB::table('dispatch_bill')
                ->where('dego_wor_id', $request['ord_id'])
                ->where('dego_original_number', $order_data->ord_order_number)
                ->where('dego_order_type', 1)
                ->update($dispatch_data);
            if (!$dispatch_res) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'修改失败01']);
            }
        }
        // 修改工单相关的客户单位数据
        if ($find_work_data) {
            foreach ($find_work_data as $key => $value) {
                // 更改工单客户单位表数据
                $wocl_data['wocl_client_id'] = $new_channel_unit->chun_id;
                $wocl_data['wocl_channel_unit'] = $new_channel_unit->chun_unit_name;
                // edit_type 更改车主信息：1是2否
                if (isset($request['edit_type']) && $request['edit_type'] == 1) {
                    $wocl_data['wocl_name'] = $new_channel_unit->chun_name;
                    $wocl_data['wocl_phone'] = $new_channel_unit->chun_phone;
                    $wocl_data['wocl_province'] = $new_channel_unit->chun_province;
                    $wocl_data['wocl_city'] = $new_channel_unit->chun_city;
                    $wocl_data['wocl_county'] = $new_channel_unit->chun_county;
                    $wocl_data['wocl_address'] = $new_channel_unit->chun_address;
                }
                $wocl_res = DB::table('work_client')
                    ->where('wocl_wor_id', $value->wor_id)
                    ->update($wocl_data);
                unset($wocl_data);

                // 更改工单表数据
                $work_order_data['wor_type'] = 2;
                $work_order_data['wor_update_time'] = date('Y-m-d H:i:s');
                $work_order_res = DB::table('work_order')
                    ->where('wor_id', $value->wor_id)
                    ->update($work_order_data);
                unset($work_order_data);

                // 查询工单对应的发货单
                $find_dego_id = DB::table('dispatch_bill')
                    ->where('dego_wor_id', $value->wor_id)
                    ->where('dego_original_number', $value->wor_number)
                    ->where('dego_order_type', 2)
                    ->value('dego_id');
                if ($find_dego_id) {
                    $dispatch_res = DB::table('dispatch_bill')
                        ->where('dego_wor_id', $value->wor_id)
                        ->where('dego_original_number', $value->wor_number)
                        ->where('dego_order_type', 2)
                        ->update($dispatch_data);
                    if (!$dispatch_res) {
                        DB::rollBack();
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'修改失败02']);
                    }
                }

                // 修改退换入库相关表
                $find_recycle_data = DB::table('recede_recycle')
                    ->where('rec_shop_id', $user_info->adm_shop_id)
                    ->where('rec_ord_id', $value->wor_id)
                    ->where('rec_ord_order_number', $value->wor_number)
                    ->select('rec_id')
                    ->get()->toArray();
                if ($find_recycle_data) {
                    foreach ($find_recycle_data as $rec_key => $rec_value) {
                        $recl_data['rec_type'] = 2;
                        $recl_data['recl_client_id'] = $new_channel_unit->chun_id;
                        $recl_data['recl_channel_unit'] = $new_channel_unit->chun_unit_name;
                        // edit_type 更改车主信息：1是2否
                        if (isset($request['edit_type']) && $request['edit_type'] == 1) {
                            $recl_data['recl_name'] = $new_channel_unit->chun_name;
                            $recl_data['recl_phone'] = $new_channel_unit->chun_phone;
                        }
                        $recl_res = DB::table('recede_client as rc')
                            ->leftJoin('recede_recycle as rr', 'rc.recl_rec_id', '=', 'rr.rec_id')
                            ->where('recl_rec_id', $rec_value->rec_id)
                            ->update($recl_data);
                        unset($recl_data);
                        if (!$recl_res) {
                            DB::rollBack();
                            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'修改失败03']);
                        }
                    }
                    unset($find_recycle_data);
                }

                // 修改结款明细订单工单账单
                $accounting_data['acset_client_type'] = 2;
                $accounting_data['acset_client_id'] = $new_channel_unit->chun_id;
                $accounting_data['acset_client_name'] = $new_channel_unit->chun_unit_name;
                $find_accounting_data = DB::table('accounting_settlement')
                    ->where('acset_shop_id', $user_info->adm_shop_id)
                    ->where('acset_original_id', $value->wor_id)
                    ->where('acset_original_number', $value->wor_number)
                    ->value('acset_id');
                if ($find_accounting_data) {
                    $wor_acset_res = DB::table('accounting_settlement')
                        ->where('acset_shop_id', $user_info->adm_shop_id)
                        ->where('acset_original_id', $value->wor_id)
                        ->where('acset_original_number', $value->wor_number)
                        ->update($accounting_data);
                    unset($accounting_data);
                } else {
                    $wor_acset_res = true;
                }

                // 修改应收应付的客户单位
                $receivable_data['recr_client_type'] = 2;
                $receivable_data['recr_client_id'] = $new_channel_unit->chun_id;
                $receivable_data['recr_client_name'] = $new_channel_unit->chun_unit_name;
                $find_receivable_data = DB::table('receivable_credit')
                    ->where('recr_shop_id', $user_info->adm_shop_id)
                    ->where('recr_original_id', $value->wor_id)
                    ->where('recr_original_number', $value->wor_number)
                    ->value('recr_id');
                if ($find_receivable_data) {
                    $recr_res = DB::table('receivable_credit')
                        ->where('recr_shop_id', $user_info->adm_shop_id)
                        ->where('recr_original_id', $value->wor_id)
                        ->where('recr_original_number', $value->wor_number)
                        ->update($receivable_data);
                    unset($receivable_data);
                } else {
                    $recr_res = true;
                }
                if (!$wocl_res || !$work_order_res || !$wor_acset_res || !$recr_res) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'修改失败04']);
                }
            }
            unset($find_work_data);
        }

        // 查询订单所属的旧货回收单数据
        $find_junk_data = DB::table('junk_recycle')
            ->where('jur_shop_id', $user_info->adm_shop_id)
            ->where('jur_ord_id', $request['ord_id'])
            ->where('jur_ord_order_number', $order_data->ord_order_number)
            ->select('jur_id')
            ->get()->toArray();
        if ($find_junk_data) {
            // 修改旧货回收单客户单位数据
            foreach ($find_junk_data as $key => $value) {
                $junk_data['jur_type'] = 2;
                $junk_data['jucl_client_id'] = $new_channel_unit->chun_id;
                $junk_data['jucl_channel_unit'] = $new_channel_unit->chun_unit_name;
                // edit_type 更改车主信息：1是2否
                if (isset($request['edit_type']) && $request['edit_type'] == 1) {
                    $junk_data['jucl_name'] = $new_channel_unit->chun_name;
                    $junk_data['jucl_phone'] = $new_channel_unit->chun_phone;
                }
                $junk_res = DB::table('junk_client as jc')
                    ->leftJoin('junk_recycle as jr', 'jc.jucl_jur_id', '=', 'jr.jur_id')
                    ->where('jur_id', $value->jur_id)
                    ->update($junk_data);
                unset($junk_data);
                if (!$junk_res) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'修改失败05']);
                }
            }
            unset($find_junk_data);
        }

        // 查询订单相关的退换入库数据
        $find_rec_data = DB::table('recede_recycle')
            ->where('rec_shop_id', $user_info->adm_shop_id)
            ->where('rec_ord_id', $request['ord_id'])
            ->where('rec_ord_order_number', $order_data->ord_order_number)
            ->select('rec_id')
            ->get()->toArray();
        if ($find_rec_data) {
            foreach ($find_rec_data as $key => $value) {
                $recl_data['rec_type'] = 2;
                $recl_data['recl_client_id'] = $new_channel_unit->chun_id;
                $recl_data['recl_channel_unit'] = $new_channel_unit->chun_unit_name;
                // edit_type 更改车主信息：1是2否
                if (isset($request['edit_type']) && $request['edit_type'] == 1) {
                    $recl_data['recl_name'] = $new_channel_unit->chun_name;
                    $recl_data['recl_phone'] = $new_channel_unit->chun_phone;
                }
                $recl_res = DB::table('recede_client as rc')
                    ->leftJoin('recede_recycle as rr', 'rc.recl_rec_id', '=', 'rr.rec_id')
                    ->where('recl_rec_id', $value->rec_id)
                    ->update($recl_data);
                unset($recl_data);
                if (!$recl_res) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'修改失败06']);
                }
            }
            unset($find_rec_data);
        }

        // 查询订单相关的销售统计数据
        $find_data_statistical = DB::table('data_statistical')
            ->where('dast_shop_id', $user_info->adm_shop_id)
            ->where('dast_ord_id', $request['ord_id'])
            ->where('dast_order_number', $order_data->ord_order_number)
            ->value('dast_id');
        if ($find_data_statistical) {
            // 更改销售统计表相关的客户单位数据
            $dast_data['dast_type'] = 2; //单位类型1会员零售2客户单位3速电派单
            $dast_data['dast_chty_id'] = $new_channel_unit->chun_chty_id;
            $dast_data['dast_client_id'] = $new_channel_unit->chun_id;
            $dast_res = DB::table('data_statistical')
                ->where('dast_shop_id', $user_info->adm_shop_id)
                ->where('dast_ord_id', $request['ord_id'])
                ->where('dast_order_number', $order_data->ord_order_number)
                ->update($dast_data);
            unset($dast_data);
            if (!$dast_res) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'修改失败07']);
            }
        }

        // 查询订单相关的凭证表数据
        $find_vore_data = DB::table('voucher_receipts')
            ->where('vore_shop_id', $user_info->adm_shop_id)
            ->where('vore_ord_id', $request['ord_id'])
            ->where('vore_ord_number', $order_data->ord_order_number)
            ->select('vore_id', 'vore_state')
            ->get()->toArray();
        if ($find_vore_data) {
            foreach ($find_vore_data as $key => $value) {
                if ($value->vore_state == 2) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'相关凭证已同步U8，无法修改！']);
                }
            }
            // 更改凭证表相关的客户单位数据
            $voucher_data['vore_type'] = 2; //单位类型1会员零售2客户单位3速电派单
            $voucher_data['vore_client_id'] = $new_channel_unit->chun_id;
            $voucher_data['vore_channel_unit'] = $new_channel_unit->chun_unit_name;
            $vore_res = DB::table('voucher_receipts')
                ->where('vore_shop_id', $user_info->adm_shop_id)
                ->where('vore_ord_id', $request['ord_id'])
                ->where('vore_ord_number', $order_data->ord_order_number)
                ->update($voucher_data);
            unset($voucher_data);
        } else {
            $vore_res = true;
        }

        // 查询商品流水记录相关数据
        $find_oure_data = DB::table('outin_record')
            ->where('oure_shop_id', $user_info->adm_shop_id)
            ->where('oure_original_correlation_id', $request['ord_id'])
            ->where('oure_original_correlation_number', $order_data->ord_order_number)
            ->value('oure_id');
        if ($find_oure_data) {
            // 有对应的流水记录，更改对应的客户单位数据
            $outin_recore_data['oure_client_type'] = 2;
            $outin_recore_data['oure_client_id'] = $new_channel_unit->chun_id;
            $oure_res = DB::table('outin_record')
                ->where('oure_shop_id', $user_info->adm_shop_id)
                ->where('oure_original_correlation_id', $request['ord_id'])
                ->where('oure_original_correlation_number', $order_data->ord_order_number)
                ->update($outin_recore_data);
            unset($outin_recore_data);
        } else {
            $oure_res = true;
        }

        $ord_record = orderLog($user_info, $request['ord_id'], 0, '修改客户');

        if ($ord_res && $orcl_client_res && $vore_res && $oure_res && $ord_record) {
            Common::addLog($user_info, getRealIp($request), '订单列表', '修改客户', "【" . $order_data->ord_order_number . "】" . $oldname . "->" . $new_channel_unit->chun_unit_name . '；修改前信息：' . $before_change . '；' . $edit_type_hint);
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'修改成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'修改失败']);
        }
    }

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

        // 查询订单数据
        $find_order = DB::table('order as ord')
            ->leftjoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
            ->leftjoin('order_label as orla', 'orla.orla_id', '=', 'ord.ord_orla_id')
            ->where('ord_id', $request['ord_id'])
            ->select('ord_orcl_id', 'ord_service_type', 'ord_state', 'ord_wor_quantity', 'ord_payment_way', 'ord_actual_price', 'ord_type', 'ord_remark', 'ord_ware_id', 'ord_client_id', 'ord_service_sepr_id', 'ord_service_adm_id', 'ord_orla_id', 'orla_name', 'orla_recycle_state', 'ord_service_shop_id', 'ord_order_number', 'ord_acti_id', 'ord_acti_row', 'ord_plus_minus', 'ord_order_plus_minus', 'orcl_shipment_party', 'orcl_rescue_assign_price', 'orcl_junk_type', 'ord_wor_state', 'orcl_rescue_collection_price', 'orcl_rescue_service_price')
            ->first();

        $error_message = $verify_data->editValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $find_goods_data = DB::table('goods')
            ->whereIn('goo_id', $request['goo_id'])
            ->select('goo_id', 'goo_name', 'goo_type', 'goo_goods_encode')
            ->get()->toArray();
        $goods_data = array_column($find_goods_data, null, 'goo_id');

        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_quantity > 0) {
            // 工单数量大于0，已经派工单
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已经派工单，无法派单']);
        }
        // 出库方1仓库2直营店3加盟店4虚拟加盟店，如果不是虚拟加盟店
        if ($find_order->orcl_shipment_party != 4) {
            if (empty($request['ware_id'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'请选择仓库']);
            }
            $ware_return = Warehouse::existMoveWarehouse($request['service_adm_id']);
            if (empty($ware_return)) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前技师暂未绑定移动仓，无法派单']);
            }
        } else {
            $request->offsetSet('ware_id', 0);
        }

        $goo_all_quantity = 0; //商品总数量
        $goo_all_price = 0; //商品总金额
        $goo_assign_all_price = $find_order->orcl_rescue_assign_price / 100; //派单金额
        $goo_all_collection_price = 0; //商品代收总金额
        $goo_all_fine = 0; //良品总数量
        $goo_all_priority = 0; //优先总数量
        $recycle_number = 0; //工单计划总的旧货回收数量
        $wor_is_recycle = 2; //  1.回收2.不回收
        $wor_recycle_price = 0; //总的回收金额
        $goo_exchange_id = []; //换货商品id
        // 救援单的服务项目金额
        $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;

        // 获取当前操作账号信息
        $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 (!empty($request['goo_id'])) {
            foreach ($request['goo_id'] as $key => $value) {
                if (!is_numeric($value) || !is_numeric($request['goo_waon_class'][$key]) || !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]) || !in_array($request['goo_inventory'][$key], [1, 2])) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'商品参数类型错误'];
                }
                // 搜索商品id对应的商品名称、商品编号
                $find_goods_data = DB::table('goods')
                    ->where('goo_id', $value)
                    ->select('goo_name', 'goo_goods_encode', 'goo_type', 'goo_ampere_hour', 'goo_price', 'goo_fid', '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 ($request['goo_state'][$key] == 5 && $find_order->orcl_shipment_party != 4) {
                    if ($find_goods_data->goo_fid == '0') {
                        $ware_return = $value;
                    } else {
                        $ware_return = Warehouse::obtain(
                            $request['goo_inventory'][$key],
                            $request['goo_waon_class'][$key],
                            $value,
                            $request['goo_quantity'][$key],
                            $find_goods_data->goo_fid,
                            $find_order->ord_ware_id
                        );
                    }
                    if ($ware_return === false) {
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'仓库内商品数量不足']);
                    } else {
                        $request['goo_waon_class'][$key];
                        $goo_price = $request['goo_price'];
                        $goo_price[$key] = 0;
                        $request->offsetSet('goo_price', $goo_price);
                        $value = $ware_return;
                        $arr_goo = $request['goo_id'];
                        $arr_goo[$key] = $ware_return;
                        $request->offsetSet('goo_id', $arr_goo);
                    }
                }

                if ($request['goo_quantity'][$key]) {
                    $wogo_data[$key]['wogo_ware_id'] = $request['ware_id']; //仓库id
                    $wogo_data[$key]['wogo_actual_goo_id'] = $value; //实际出库商品id
                    $wogo_data[$key]['wogo_wago_id'] = $request['wago_id'][$key]; //仓库商品id
                    $wogo_data[$key]['wogo_waon_class'] = $request['goo_waon_class'][$key]; //仓库类别
                    $wogo_data[$key]['wogo_goo_id'] = $value; //商品id
                    $wogo_data[$key]['wogo_is_recycle'] = $request['goo_recycle'][$key]; //是否回收：1回收2不回收
                    // orcl_shipment_party等于4虚拟加盟店
                    if ($find_order->orcl_shipment_party == 4 || $request['sd_virtual_type'] == 1) {
                        $wogo_data[$key]['wogo_goo_price'] = $request['goo_assign_price'][$key] * 100; //工单商品销售金额
                    } else {
                        $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_goo_inventory'] = $request['goo_inventory'][$key]; //出库类型：1.良品 2.优先
                    $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');

                    // 搜索商品id对应的商品名称、商品编号
                    $find_goods_data = DB::table('goods')
                        ->where('goo_id', $value)
                        ->first(['goo_name', 'goo_goods_encode', 'goo_type', '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;
                        }
                    }
                    $wogo_data[$key]['wogo_goo_name'] = $find_goods_data->goo_name;

                    if (!empty($request['tem_goo_name'][$key])) {
                        $tem_goo_name = $request['tem_goo_name'][$key];
                    } else {
                        $tem_goo_name = '';
                    }
                    $wogo_data[$key]['wogo_tem_goo_name'] = $tem_goo_name;
                    $wogo_data[$key]['wogo_goo_goods_encode'] = $find_goods_data->goo_goods_encode;
                    $wogo_data[$key]['wogo_goo_type'] = isset($request['goo_type'][$key]) ? $request['goo_type'][$key] : $find_goods_data->goo_type;

                    // 正常商品 或 赠品
                    if ($request['goo_state'][$key] == 1 || $request['goo_state'][$key] == 5) {
                        // 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];
                        }

                        if ($request['goo_inventory'][$key] == 1) {
                            $goo_all_fine += $request['goo_quantity'][$key]; //1.良品总数量
                        } else {
                            $goo_all_priority += $request['goo_quantity'][$key]; //2.优先总数量
                        }

                        $goo_id[] = $value; //正常商品id
                        $goo_quantity[] = $request['goo_quantity'][$key];
                        $goo_inventory[] = $request['goo_inventory'][$key];

                        $goo_all_quantity += $request['goo_quantity'][$key];
                        $goo_all_price += $request['goo_price'][$key] * $request['goo_quantity'][$key];
                        $goo_assign_all_price += $request['goo_assign_price'][$key] * $request['goo_quantity'][$key];
                        $goo_all_collection_price += $request['goo_collection_price'][$key];

                        $class_goods['goo_inventory'] = $request['goo_inventory'][$key];
                        $class_goods['goo_quantity'] = $request['goo_quantity'][$key];
                        if (isset($wago_class_goods[$request['goo_waon_class'][$key]][$value]['goo_quantity'])) {
                            $wago_class_goods[$request['goo_waon_class'][$key]][$value]['goo_quantity'] = $wago_class_goods[$request['goo_waon_class'][$key]][$value]['goo_quantity'] + $class_goods['goo_quantity']; //仓库类型对应的出库商品数据
                        } else {
                            $wago_class_goods[$request['goo_waon_class'][$key]][$value] = $class_goods; //仓库类型对应的出库商品数据
                        }
                    } elseif ($request['goo_state'][$key] == 4) {
                        // 换货商品
                        $goo_exchange_id[] = $value; //换货商品id
                        $goo_all_price -= $request['goo_price'][$key] * $request['goo_quantity'][$key];
                        $goo_assign_all_price -= $request['goo_assign_price'][$key] * $request['goo_quantity'][$key];
                    } elseif ($request['goo_state'][$key] == '6') {
                        $goo_id[] = $value; //正常商品id
                        $goo_all_quantity += $request['goo_quantity'][$key];
                    } elseif ($request['goo_state'][$key] == '7') { //临时商品
                        $goo_id[] = $value; //正常商品id
                        $goo_all_quantity += $request['goo_quantity'][$key];
                    } elseif ($request['goo_state'][$key] == '8') { //旧货商品
                        $goo_id[] = $value; //正常商品id
                        $goo_all_quantity += $request['goo_quantity'][$key];
                        $goo_all_price += $request['goo_price'][$key] * $request['goo_quantity'][$key];
                        $goo_assign_all_price += $request['goo_assign_price'][$key] * $request['goo_quantity'][$key];
                        $goo_all_collection_price += $request['goo_collection_price'][$key];
                    }
                    // 商品已派数量
                    $goo_assign_quantity[$value] = $request['goo_quantity'][$key];
                    // 出库类型
                    $goo_goo_inventory[$value] = $request['goo_inventory'][$key];
                }
            }
            if (empty($goo_id)) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'请输入派单数量']);
            }
        } else {
            $goo_all_price = $find_order->ord_actual_price / 100;
            $price = $find_order->orcl_assign_price / 100 + $goo_assign_all_price;
            $goo_assign_all_price = $price;
        }

        if (config('apisystem.ORDER_LOCK_INVENTORY') && $find_order->orcl_shipment_party != 4) {
            // 编辑订单锁定商品库存
            $lock_edit_return = $this->editOrderLockGoodsStock($user_info, $request->all(), $find_order, $goods_data);
            if ($lock_edit_return['code'] == 500) {
                DB::rollBack();
                return response()->json($lock_edit_return);
            }
        } else {
            $lock_edit_return['return_data'] = [];
        }
        // 编辑订单相关数据
        $ord_edit_return = $this->editOrderData($user_info, $request->all(), $find_order, $goods_data, $lock_edit_return['return_data']);
        if ($ord_edit_return['code'] == 500) {
            DB::rollBack();
            return response()->json($ord_edit_return);
        }
        // 如果订单类型为发货单
        if ($request['ord_service_type'] == 5) {
            // 修改发货单商品数量
            $dibi_edit_return = $this->editOrderDispatchBill($user_info, $request->all(), $find_order, $goods_data);
            if ($dibi_edit_return['code'] == 500) {
                DB::rollBack();
                return response()->json($dibi_edit_return);
            }
        }

        // 如果订单类型为退货单
        if ($request['ord_service_type'] == 4 && $find_order->orcl_shipment_party != 4) {
            // 修改退货单商品数量
            $rede_edit_return = $this->editOrderRecede($user_info, $request->all(), $find_order, $goods_data);
            if ($rede_edit_return['code'] == 500) {
                DB::rollBack();
                return response()->json($rede_edit_return);
            }
        }

        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['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'] = $find_order->ord_service_type;
        $wor_data['wor_service_state'] = $find_order->orcl_shipment_party == 4 ? 6 : 1;
        // 是否走技师流程  1是  2否
        if (!empty($request['whether_app']) && ($request['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;
        }
        $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']; //买家类型:1.会员零售2.客户单位3.速电派单
        $wor_data['wor_orla_id'] = $find_order->ord_orla_id; //订单标签id
        $wor_data['wor_remark'] = $request['ord_remark'] ? $request['ord_remark'] : ''; //订单备注
        $wor_data['wor_ware_id'] = $request['ware_id']; //仓库id
        // 工单金额 = 总金额 - 回收金额
        if ($find_order->orcl_shipment_party == 4 || $request['sd_virtual_type'] == 1) {
            $goo_all_price = $goo_assign_all_price + $orcl_rescue_service_price;
        } else {
            $goo_all_price = $goo_all_price - $wor_recycle_price + $orcl_rescue_service_price;
        }
        $party = $find_order->orcl_shipment_party;
        if ($goo_all_price > 0) {
            // 退货单  虚拟加盟店  加盟店工单金额正负相反
            if ($find_order->ord_service_type == 4) {
                $wor_data['wor_plus_minus'] = $party == 3 || $party == 4 || $request['sd_virtual_type'] == 1 ? 1 : 2;
            } else {
                $wor_data['wor_plus_minus'] = $party == 3 || $party == 4 || $request['sd_virtual_type'] == 1 ? 2 : 1;
            }
        } else {
            // 退货单  虚拟加盟店  加盟店工单金额正负相反
            if ($find_order->ord_service_type == 4) {
                $wor_data['wor_plus_minus'] = $party == 3 || $party == 4 || $request['sd_virtual_type'] == 1 ? 2 : 1;
            } else {
                $wor_data['wor_plus_minus'] = $party == 3 || $party == 4 || $request['sd_virtual_type'] == 1 ? 2 : 1;
            }
        }

        $wor_data['wor_actual_price'] = abs($goo_all_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; //工单总的回收金额
        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);

        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($request['goo_id'])) {
            // 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']);

        // 3. 添加工单客户表数据
        $wocl_data = [
            'wocl_wor_id' => $wor_id,
            'wocl_client_id' => $request['orcl_client_id'] ? $request['orcl_client_id'] : 0,
            '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' => $orcl_chin->orcl_chin_type,
            'wocl_collect_state' => isset($request['orcl_collect_state']) ? $request['orcl_collect_state'] : 0,
            '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_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['orcl_junk_type']) ? $request['orcl_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否
        ];
        if ($find_order->orcl_shipment_party == 4) {
            $wocl_data['wocl_wor_type'] = 4;
            $wocl_data['wocl_rescue_service_price'] = $find_order->orcl_rescue_assign_price;
        } else {
            $wocl_data['wocl_rescue_service_price'] = $find_order->orcl_rescue_service_price;
        }
        $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');
        // 速电派单才有订单标签
        if (!empty($request['orla_id'])) {
            $ord_data['ord_orla_id'] = $request['orla_id'];
        }
        $ord_data['ord_service_adm_id'] = $request['wor_service_adm_id'];
        $ord_res =  DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->update($ord_data);

        // 救援单没有商品数据的状态
        if (empty($request['goo_id'])) {
            // 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'=>'派单失败']);
            }
        }
        // 4. 更改订单商品表，剩余可派商品数量
        // 查询订单商品表数据
        $orgo_goo_id = array_merge($goo_id, $goo_exchange_id);
        $goods_data =  DB::table('order_goods')
            ->where('orgo_ord_id', $request['ord_id'])
            ->whereIn('orgo_state', [1, 4, 5, 6, 7, 8])
            ->whereIn('orgo_goo_id', $orgo_goo_id)
            ->select('orgo_id', 'orgo_goo_id', 'orgo_can_assign_quantity')
            ->get();
        // 更新订单商品表数量
        $sql = 'UPDATE `faster_order_goods` SET ';
        $actual_number_sql = '';
        $update_time_sql = '';
        $goo_inventory = '';
        $ids = '';
        foreach ($goods_data as $key => $value) {
            // 商品订单数量
            // 更改可派单商品数量
            $assign_quantity = $value->orgo_can_assign_quantity - $goo_assign_quantity[$value->orgo_goo_id];
            if ($assign_quantity < 0) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'可派单商品数量不足，无法派单']);
            }

            $actual_number_sql = $actual_number_sql . ' WHEN ' . $value->orgo_id;
            $actual_number_sql = $actual_number_sql . ' THEN ' . $assign_quantity;
            $goo_inventory = $goo_inventory . ' WHEN ' . $value->orgo_id;
            $goo_inventory = $goo_inventory . ' THEN ' . $goo_goo_inventory[$value->orgo_goo_id];
            // 更改时间
            $update_time_sql = $update_time_sql . ' WHEN ' . $value->orgo_id;
            $update_time_sql = $update_time_sql . ' THEN "' . date('Y-m-d H:i:s') . '"';

            $ids = $ids . $value->orgo_id . ',';
        }
        $sql = $sql . ' `orgo_can_assign_quantity`=  CASE `orgo_id` ' . $actual_number_sql . ' END,';
        $sql = $sql . ' `orgo_goo_inventory`=  CASE `orgo_id` ' . $goo_inventory . ' END,';
        $sql = $sql . ' `orgo_update_time`=  CASE `orgo_id` ' . $update_time_sql . ' END';
        $sql = $sql . ' WHERE `orgo_id` IN (' . trim($ids, ',') . ')';
        $orgo_res = DB::update($sql);

        // 6. 选择的仓库不为当前技师移动仓时 生成发货单
        $ware_id = DB::table('warehouse')
            ->where('ware_type', 2)
            ->where('ware_leader_id', $request['wor_service_adm_id'])
            ->value('ware_id');
        // 当前仓库不是技师的移动仓 生成发货单 并且订单类型不为退货单
        if ($ware_id != $request['ware_id'] && $find_order->ord_service_type != 4 && $find_order->orcl_shipment_party != 4) {
            // 6.1 发货单表添加数据
            $dego_number = 'FH' . time() . rand(100, 999);

            $bill_data['dego_cid'] = $user_info->adm_cid; //公司id
            $bill_data['dego_shop_id'] = $user_info->adm_shop_id; //门店id
            $bill_data['dego_superior_shop_id'] = $shop_id; //所属总店id
            $bill_data['dego_number'] = $dego_number; //发货单号
            $bill_data['dego_wor_id'] = $wor_id; //发货单关联的工单id
            $bill_data['dego_original_number'] = $wor_order_number; //原始单号,发货单的关联单号(工单号)
            $bill_data['dego_client_type'] = $request['ord_type']; //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
            $bill_data['dego_client_id'] = $request['orcl_client_id'] ? $request['orcl_client_id'] : 0; //选择的客户id,会员id/单位id
            $bill_data['dego_count'] = $goo_all_quantity; //发货总数量
            $bill_data['dego_out_ware_id'] = $request['ware_id']; //出库仓库id
            $bill_data['dego_service_shop_id'] = $request['service_shop_id']; //服务门店id
            $bill_data['dego_service_adm_id'] = $request['service_adm_id']; //服务技师id
            $bill_data['dego_type'] = 1; //类型：1未出库2已出库
            $bill_data['dego_order_type'] = 2; //类型：1.订单发货 2.工单发货
            $bill_data['dego_create_adm_id'] = $user_info->adm_id; //创建人id
            $bill_data['dego_remark'] = $request['ord_remark'] ? $request['ord_remark'] : ''; //备注
            $dispatch_bill = DB::table('dispatch_bill')->insertGetId($bill_data);

            $goo_all_fine = 0;
            $goo_all_priority = 0;
            // 6.2 发货单商品表添加数据
            foreach ($request['goo_id'] as $key => $value) {
                // 正常商品
                if ($request['goo_state'][$key] == 1 || $request['goo_state'][$key] == 5 || $request['goo_state'][$key] == 6) {
                    // 发货商品表数据
                    $digo_data[$key]['digo_dego_id'] = $dispatch_bill;
                    $digo_data[$key]['digo_wago_class'] = $request['goo_waon_class'][$key];
                    $digo_data[$key]['digo_goo_id'] = $value;
                    $digo_data[$key]['digo_goo_price'] = $request['goo_price'][$key] * 100;
                    $digo_data[$key]['digo_goo_quantity'] = $request['goo_quantity'][$key];
                    $digo_data[$key]['digo_is_recycle'] = $request['goo_recycle'][$key];
                    $digo_data[$key]['digo_goo_inventory'] = $request['goo_inventory'][$key];
                    // 搜索商品id对应的商品名称、商品编号
                    $find_goods_data = DB::table('goods')
                        ->where('goo_id', $value)
                        ->first(['goo_name', 'goo_goods_encode', 'goo_type', '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;
                        }
                    }
                    $digo_data[$key]['digo_goo_name'] = $find_goods_data->goo_name;
                    if (!empty($request['tem_goo_name'][$key])) {
                        $tem_goo_name = $request['tem_goo_name'][$key];
                    } else {
                        $tem_goo_name = '';
                    }
                    $digo_data[$key]['digo_tem_goo_name'] = $tem_goo_name;
                    $digo_data[$key]['digo_goo_goods_encode'] = $find_goods_data->goo_goods_encode;
                    $digo_data[$key]['digo_goo_type'] = isset($request['goo_type'][$key]) ? $request['goo_type'][$key] : $find_goods_data->goo_type;
                    $digo_data[$key]['digo_state'] = $request['goo_state'][$key];

                    if ($request['goo_inventory'][$key] == 1) {
                        $goo_all_fine += $request['goo_quantity'][$key]; //1.良品总数量
                    } else {
                        $goo_all_priority += $request['goo_quantity'][$key]; //2.优先总数量
                    }

                    // 商品id和所对应的商品数量
                    $subtract[$value] = $request['goo_quantity'][$key];
                    // 每个商品对应的出库方式
                    $goo_repertory[$value] = $request['goo_inventory'][$key];
                }
            }
            $dispatch_goods = DB::table('dispatch_goods')->insert($digo_data);

            if (config('apisystem.ORDER_LOCK_INVENTORY') && $find_order->ord_type != 3) {
                $dispatch_bill = true;
                $dispatch_goods = true;
                $save_warehouse = true;
            } else {
                // 查询出仓库这些商品数量是否够减
                $goo_waon_class = array_unique($request['goo_waon_class']);
                $warehouse_goods = DB::table('warehouse_goods')
                    ->where('wago_ware_id', $request['ware_id'])
                    ->whereIn('wago_class', $goo_waon_class)
                    ->whereIn('wago_goo_id', $goo_id)
                    ->get(['wago_id', 'wago_goo_id', 'wago_class', 'wago_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity'])
                    ->toArray();
                // 处理要出库的商品库存数量
                if (empty($warehouse_goods)) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'当前仓库未找到出库商品，无法出库3'];
                }

                // 将数据组合成新的数组
                foreach ($warehouse_goods as $key => $value) {
                    $warehouse_class_goods[$value->wago_class][$value->wago_goo_id] = (array) $value;
                }

                $sql = 'UPDATE `faster_warehouse_goods` SET ';
                $stock_fine_sql = '';
                $stock_priority_sql = '';
                $lock_fine_sql = '';
                $lock_priority_sql = '';
                $time_sql = '';
                $ids = '';

                $waon_class_fine_quantity = []; //仓库类别对应良品库存总数量
                $waon_class_priority_quantity = []; //仓库类别对应优先库存总数量
                // 发货单要出库的商品
                foreach ($wago_class_goods as $waon_class_key => $class_goods_data) {
                    foreach ($class_goods_data as $goo_id_key => $value) {
                        // 商品出库类型，良品出库
                        if ($value['goo_inventory'] == 1) {
                            // 良品剩余库存数量
                            $surplus_quantity = $warehouse_class_goods[$waon_class_key][$goo_id_key]['wago_stock_number'] - $value['goo_quantity'];
                            if ($surplus_quantity < 0) {
                                return ['code'=>500, 'msg'=>'error', 'data'=>'仓库内商品数量不足'];
                            }
                            // 更改库存数量
                            $stock_fine_sql = $stock_fine_sql . ' WHEN ' . $warehouse_class_goods[$waon_class_key][$goo_id_key]['wago_id'] . ' THEN `wago_stock_number` - ' . $value['goo_quantity'];
                            // 更改锁定数量
                            $lock_fine_sql = $lock_fine_sql . ' WHEN ' . $warehouse_class_goods[$waon_class_key][$goo_id_key]['wago_id'] . ' THEN `wago_lock_quantity` + ' . $value['goo_quantity'];

                            // 更改库存数量
                            $stock_priority_sql = $stock_priority_sql . ' WHEN ' . $warehouse_class_goods[$waon_class_key][$goo_id_key]['wago_id'] . ' THEN `wago_priority_stock_number` - 0';
                            // 更改锁定数量
                            $lock_priority_sql = $lock_priority_sql . ' WHEN ' . $warehouse_class_goods[$waon_class_key][$goo_id_key]['wago_id'] . ' THEN `wago_priority_lock_quantity` + 0';

                            if (isset($waon_class_fine_quantity[$waon_class_key])) {
                                $waon_class_fine_quantity[$waon_class_key] += $value['goo_quantity']; //仓库类别对应良品库存总数量
                            } else {
                                $waon_class_fine_quantity[$waon_class_key] = $value['goo_quantity']; //仓库类别对应良品库存总数量
                            }
                            // 商品出库类型，优先出库
                        } else {
                            // 优先剩余库存数量
                            $surplus_quantity = $warehouse_class_goods[$waon_class_key][$goo_id_key]['wago_priority_stock_number'] - $value['goo_quantity'];
                            if ($surplus_quantity < 0) {
                                return ['code'=>500, 'msg'=>'error', 'data'=>'仓库内商品数量不足'];
                            }

                            // 更改库存数量
                            $stock_priority_sql = $stock_priority_sql . ' WHEN ' . $warehouse_class_goods[$waon_class_key][$goo_id_key]['wago_id'] . ' THEN `wago_priority_stock_number` - ' . $value['goo_quantity'];
                            // 更改锁定数量
                            $lock_priority_sql = $lock_priority_sql . ' WHEN ' . $warehouse_class_goods[$waon_class_key][$goo_id_key]['wago_id'] . ' THEN `wago_priority_lock_quantity` + ' . $value['goo_quantity'];

                            // 更改库存数量
                            $stock_fine_sql = $stock_fine_sql . ' WHEN ' . $warehouse_class_goods[$waon_class_key][$goo_id_key]['wago_id'] . ' THEN `wago_stock_number` - 0';
                            // 更改锁定数量
                            $lock_fine_sql = $lock_fine_sql . ' WHEN ' . $warehouse_class_goods[$waon_class_key][$goo_id_key]['wago_id'] . ' THEN `wago_lock_quantity`  + 0';

                            if (isset($waon_class_priority_quantity[$waon_class_key])) {
                                $waon_class_priority_quantity[$waon_class_key] += $value['goo_quantity']; //仓库类别对应优先库存总数量
                            } else {
                                $waon_class_priority_quantity[$waon_class_key] = $value['goo_quantity']; //仓库类别对应优先库存总数量
                            }
                        }

                        $time_sql = $time_sql . ' WHEN ' . $warehouse_class_goods[$waon_class_key][$goo_id_key]['wago_id'] . ' THEN "' . date('Y-m-d H:i:s') . '"'; // 更改时间
                        $ids = $ids . $warehouse_class_goods[$waon_class_key][$goo_id_key]['wago_id'] . ',';
                    }
                }

                // 2.1 固定仓商品表减锁定库存
                $sql = $sql . ' `wago_stock_number`=  CASE `wago_id` ' . $stock_fine_sql . ' END,'; //修改库存数量
                $sql = $sql . ' `wago_lock_quantity`=  CASE `wago_id` ' . $lock_fine_sql . ' END,'; //修改库存数量
                $sql = $sql . ' `wago_priority_stock_number`=  CASE `wago_id` ' . $stock_priority_sql . ' END,'; //修改锁定数量
                $sql = $sql . ' `wago_priority_lock_quantity`=  CASE `wago_id` ' . $lock_priority_sql . ' END,'; //修改锁定数量
                $sql = $sql . ' `wago_update_time`=  CASE `wago_id` ' . $time_sql . ' END'; //修改时间
                $sql = $sql . ' WHERE `wago_id` IN (' . trim($ids, ',') . ')';
                $wago_edit_res = DB::update($sql);

                // 查询仓库总数量仓库的类别对应的id
                $find_waon_data = DB::table('warehouse_onhand')
                    ->where('waon_ware_id', '=', $request['ware_id'])
                    ->whereIn('waon_class', $goo_waon_class)
                    ->pluck('waon_id', 'waon_class')->toArray();
                // 良品库存总数量更改
                if ($waon_class_fine_quantity) {
                    $sql = 'UPDATE `faster_warehouse_onhand` SET ';
                    $stock_fine_sql = '';
                    $lock_fine_sql = '';
                    $time_sql = '';
                    $ids = '';
                    foreach ($waon_class_fine_quantity as $key => $value) {
                        $stock_fine_sql = $stock_fine_sql . ' WHEN ' . $find_waon_data[$key] . ' THEN `waon_stock_fine_amount` - ' . $value;
                        $lock_fine_sql = $lock_fine_sql . ' WHEN ' . $find_waon_data[$key] . ' THEN `waon_lock_fine_amount` + ' . $value;
                        $time_sql = $time_sql . ' WHEN ' . $find_waon_data[$key] . ' THEN "' . date('Y-m-d H:i:s') . '"';

                        $ids = $ids . $find_waon_data[$key] . ',';
                    }
                    $sql = $sql . ' `waon_stock_fine_amount`=  CASE `waon_id` ' . $stock_fine_sql . ' END,';
                    $sql = $sql . ' `waon_lock_fine_amount`=  CASE `waon_id` ' . $lock_fine_sql . ' END,';
                    $sql = $sql . ' `waon_update_time`=  CASE `waon_id` ' . $time_sql . ' END';
                    $sql = $sql . ' WHERE `waon_id` IN (' . trim($ids, ',') . ')';
                    $waon_fine_res = DB::update($sql);
                } else {
                    $waon_fine_res = true;
                }

                // 优先库存总数量更改
                if ($waon_class_priority_quantity) {
                    $sql = 'UPDATE `faster_warehouse_onhand` SET ';
                    $stock_fine_sql = '';
                    $lock_fine_sql = '';
                    $time_sql = '';
                    $ids = '';
                    foreach ($waon_class_priority_quantity as $key => $value) {
                        $stock_fine_sql = $stock_fine_sql . ' WHEN ' . $find_waon_data[$key] . ' THEN `waon_stock_priority_amount` - ' . $value;
                        $lock_fine_sql = $lock_fine_sql . ' WHEN ' . $find_waon_data[$key] . ' THEN `waon_lock_priority_amount` + ' . $value;
                        $time_sql = $time_sql . ' WHEN ' . $find_waon_data[$key] . ' THEN "' . date('Y-m-d H:i:s') . '"';

                        $ids = $ids . $find_waon_data[$key] . ',';
                    }
                    $sql = $sql . ' `waon_stock_priority_amount`=  CASE `waon_id` ' . $stock_fine_sql . ' END,';
                    $sql = $sql . ' `waon_lock_priority_amount`=  CASE `waon_id` ' . $lock_fine_sql . ' END,';
                    $sql = $sql . ' `waon_update_time`=  CASE `waon_id` ' . $time_sql . ' END';
                    $sql = $sql . ' WHERE `waon_id` IN (' . trim($ids, ',') . ')';
                    $waon_priority_res = DB::update($sql);
                } else {
                    $waon_priority_res = true;
                }
            }
            $update_warehouse = true;
        } else {
            $dispatch_bill = true;
            $dispatch_goods = true;
            $save_warehouse = true;
            $update_warehouse = true;
        }

        // 7. 订单类型为退货单 生成退换回收单
        if ($find_order->ord_service_type == 4 && $find_order->orcl_shipment_party != 4) {
            // 7.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'] = $wor_id; //工单id
            $add_recycle['rec_ord_order_number'] = $wor_order_number; //工单号
            $add_recycle['rec_source_type'] = 4; //类型
            $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_waon_class'] =  $request['goo_waon_class'][0]; //仓库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);

            // 7.2退换回收商品表添加数据
            foreach ($request['goo_id'] as $key => $value) {
                $rego_data[$key]['rego_rec_id'] = $recycle_id;
                $rego_data[$key]['rego_ware_id'] = $request['ware_id'];
                $rego_data[$key]['rego_waon_class'] = $request['goo_waon_class'][$key];
                $rego_data[$key]['rego_goo_id'] = $value;
                $rego_data[$key]['rego_goo_price'] = $request['goo_price'][$key] * 100;
                $rego_data[$key]['rego_sell_number'] =  $request['goo_quantity'][$key];
                $rego_data[$key]['rego_recycle_number'] =  $request['goo_quantity'][$key];
                $rego_data[$key]['rego_goo_inventory'] =  $request['goo_inventory'][$key];
                $find_goods_data = DB::table('goods')
                    ->where('goo_id', $value)
                    ->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);

            // 7.3 退换回收客户表添加数据
            $jucl_data['recl_rec_id'] = $recycle_id; //回收单id
            $jucl_data['recl_client_id'] = $request['wocl_client_id'] ? $request['wocl_client_id'] : 0; //来往单位id/客户id
            $jucl_data['recl_name'] = $request['wocl_name']; //客户姓名
            $jucl_data['recl_phone'] = $request['wocl_phone']; //联系电话
            if ($request['wor_type'] == 2) {
                $jucl_data['recl_channel_unit'] = $request['wocl_channel_unit']; //渠道单位
                $mem_res = true;
            } else {
                if ($request['wocl_client_id']) {
                    // 零售类型，会员对应的退货数量加1
                    $mem_res =  DB::table('member')
                        ->where('mem_id', $request['wocl_client_id'])
                        ->increment('mem_retreat_trade');
                } else {
                    $mem_res = true;
                }
            }
            $add_client =  DB::table('recede_client')->insert($jucl_data);
        } else {
            $add_client = true;
            $mem_res = true;
            $add_goods = true;
            $recycle_id = true;
        }

        // 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 && $orgo_res && $ord_res && $dispatch_bill && $dispatch_goods && $update_warehouse && $work_record && $assign_record && $add_client && $mem_res && $add_goods && $recycle_id) {
            $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 ($find_order->orcl_shipment_party != 4) {
                $result_push = pushMessage($push_name, '您有新的工单：' . $wor_order_number . ' 请注意查收');
            }
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'派单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'派单失败']);
        }
    }

    // 预约时间
    public function appointmentSet(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderController;
        $error_message = $verify_data->appointmentSetValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $find_order = DB::table('order as o')
            ->leftjoin('order_client as oc', 'oc.orcl_ord_id', '=', 'o.ord_id')
            ->where('ord_id', $request['ord_id'])
            ->select('ord_order_number', 'ord_type', 'ord_wor_state', 'ord_delete', 'ord_other_system_number', 'orcl_appoint_time')
            ->first();
        if (empty($find_order)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单不存在！']);
        }
        if ($find_order->ord_delete != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已经取消！']);
        }
        if (!in_array($find_order->ord_wor_state, [1, 2, 5])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已完成或终止！']);
        }

        // 查询当前订单下是否有正常服务工单
        $find_wor_data = DB::table('work_order')
            ->where('wor_order_id', $request['ord_id'])
            ->where('wor_delete', 1)
            ->where('wor_state', '<>', 11)
            ->first(['wor_id', 'wor_state']);
        if ($find_wor_data && $find_wor_data->wor_state > 6) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单所属工单已经出发，无法预约！']);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        DB::beginTransaction();
        // 订单客户表更改预约时间、预约备注
        $orcl_edit['orcl_appoint_time'] = $request['appoint_time'];
        $orcl_edit['orcl_appoint_remark'] = $request['appoint_remark'];
        $orcl_edit['orcl_update_time'] = date('Y-m-d H:i:s');
        $ord_res = DB::table('order_client')
            ->where('orcl_ord_id', $request['ord_id'])
            ->update($orcl_edit);

        $wor_id = 0; //工单id
        if ($find_wor_data) {
            $wor_id = $find_wor_data->wor_id; //工单id

            $wor_edit['wor_appoint_time'] = $request['appoint_time'];
            $wor_edit['wor_update_time'] = date('Y-m-d H:i:s');
            $wor_edit_res = DB::table('work_order')
                ->where('wor_id', $find_wor_data->wor_id)
                ->update($wor_edit);
            if ($request['appoint_remark']) {
                $wocl_edit['wocl_appoint_remark'] = $request['appoint_remark'];
                $wocl_edit['wocl_update_time'] = date('Y-m-d H:i:s');
                $wocl_edit_res = DB::table('work_client')
                    ->where('wocl_wor_id', $find_wor_data->wor_id)
                    ->update($wocl_edit);
            } else {
                $wocl_edit_res = true;
            }
            // 判断是否更改成功
            if ($wor_edit_res && $wocl_edit_res) {
                $wor_res = true;
            } else {
                $wor_res = false;
            }
        } else {
            $wor_res = true;
        }

        // 生成操作记录
        $cancel_record = orderLog($user_info, $request['ord_id'], $wor_id, '预约设置');
        // 预约备注内容
        $remark_data = '预约时间：' . $request['appoint_time'];
        if (!empty($request['appoint_remark'])) {
            $remark_data .= ' ' . $request['appoint_remark'];
        }
        $remark_res = orderRemark($user_info, $request['ord_id'], $wor_id, $remark_data, '订单列表-预约设置');

        if ($ord_res && $wor_res && $remark_res) {
            // 如果是速电订单,，并且更改了预约时间，调速电预约接口
            if ($find_order->ord_type == 3 && $find_order->orcl_appoint_time != $request['appoint_time']) {
                $param['serial_number'] = $find_order->ord_other_system_number;
                $param['time'] = date('Y-m-d H:i:s');
                $param['daytime'] = $request['appoint_time'];
                $param['ip'] = getRealIp($request);
                $param['token'] = config('apisystem.sd_token');
                $url = config('apisystem.sd_server_name') . '/index.php/Supply/addDayTime';
                $doPost_res = Common::doPost($param, $url);
                $doPost_res = json_decode($doPost_res);
                if ($doPost_res->code != 200) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'失败']);
                }
            }
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '订单列表', '预约设置', '预约设置：' . $find_order->ord_order_number . '成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'预约设置成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'预约设置失败']);
        }
    }

    // 审核可欠金额的订单
    public function isExceed(Request $request)
    {
        if (empty($request['ord_id'])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $find_ord_data = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->where('ord_shop_id', $user_info->adm_shop_id)
            ->select('ord_order_number', 'ord_service_type', 'ord_wor_state')
            ->first();
        if (empty($find_ord_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单不存在！']);
        }
        if ($find_ord_data->ord_wor_state != 12) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单不是待审核状态！']);
        }

        $applet_order = new Order();
        $return_data = $applet_order->isExceed($user_info, $request->all(), $find_ord_data);

        if ($return_data['code'] == 200) {
            Common::addLog($user_info, getRealIp($request), '订单列表', '审核', '订单:' . $find_ord_data->ord_order_number);
            return response()->json($return_data);
        } else {
            return response()->json($return_data);
        }
    }

    // 作废订单
    public function cancelOrder(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderController;
        $error_message = $verify_data->cancelOrderValidator($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_order = DB::table('order as ord')
            ->leftJoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
            ->where('ord_id', $request['ord_id'])
            ->where('ord_shop_id', $user_info->adm_shop_id)
            ->select('ord_order_number', 'ord_state', 'ord_delete', 'ord_wor_quantity', 'ord_wor_state', 'ord_service_type', 'ord_type', 'ord_client_id', 'ord_goods_quantity', 'ord_actual_price', 'ord_service_shop_id', 'ord_create_id', 'orcl_shipment_party', 'ord_ware_id', 'ord_create_time')
            ->first();
        if (empty($find_order)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单不存在！']);
        }
        if ($find_order->ord_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已结算，无法取消！']);
        }
        if ($find_order->ord_delete == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已经作废！']);
        }
        // 查询发货单信息
        $find_digo_data = DB::table('dispatch_bill')
            ->where('dego_original_number', $request['ord_order_number'])
            ->where('dego_wor_id', $request['ord_id'])
            ->where('dego_order_type', 1)
            ->where('dego_shop_id', $user_info->adm_shop_id)
            ->select('dego_number', 'dego_type')
            ->first();
        if ($find_digo_data->dego_type == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已发货，无法作废！']);
        }
        // 查询应收状态
        $find_rece_data = DB::table('receivable_credit')
            ->where('recr_shop_id', $user_info->adm_shop_id)
            ->where('recr_original_id', $request['ord_id'])
            ->where('recr_original_number', $request['ord_order_number'])
            ->value('recr_state');
        if ($find_rece_data == 3) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已收款，无法作废！']);
        }

        DB::beginTransaction();

        // 取消订单
        $order_res = Order::cancelOrder(
            $user_info,
            $request,
            $find_order
        );
        // 生成操作记录
        $cancel_record = orderLog($user_info, $request['ord_id'], 0, '作废订单');
        // 添加备注
        orderRemark($user_info, $request['ord_id'], '', $request['remark'], '订单列表');

        $ord_data['ord_delete'] = 2; //是否删除：1正常订单2取消订单

        if ($order_res['code'] == 200 && $cancel_record) {
            // 添加新增订单信息的提示
            $inhi_data['inhi_original_adm_id'] = $find_order->ord_create_id; //原始单号创建人
            $inhi_data['inhi_original_id'] = $request['ord_id']; //原始单id
            $inhi_data['inhi_original_number'] = $find_order->ord_order_number; //原始单号
            $inhi_data['inhi_original_state'] = $ord_data['ord_delete']; //原始单状态
            $inhi_data['inhi_original_operation'] = '取消订单'; //操作
            $inhi_data['inhi_operation_state'] = 12; //操作状态：12取消订单
            addInformationHint($user_info, $inhi_data, 1);
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '订单列表', '作废订单', '作废订单：' . $find_order->ord_order_number . '成功');
            return response()->json($order_res);
        } else {
            DB::rollBack();
            return response()->json($order_res);
        }
    }
}
