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

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\OrderManage\VerifyWorkOrderController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\Export;
use App\Http\Models\Api\OutinRecord;
use App\Http\Models\Api\ReceivableBill;
use App\Http\Models\Api\Warehouse;
use App\Http\Models\Api\AccountingSettlement;
use App\Http\Models\Api\WorkOrder;
use App\Http\Models\Api\ReceivableCredit;
use App\Http\Models\Api\CashierDesk;
use App\Http\Models\Services\ImageUpload;
use App\Http\Models\Services\Order;
use App\Http\Models\Services\OrderManage\WorkOrders;
use App\Http\Models\Services\WarehouseManage\OutinStockLock;
use App\Http\Models\Services\WarehouseManage\JunkRecycling;
use App\Http\Models\Services\WarehouseManage\ReturnWarehousing;

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

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkOrderController;
        $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_ids = $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['wor_plus_minus'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
            }
            $search_data['min_price'] = $search_data['min_price'] * 100;
            if ($search_data['wor_plus_minus'] == 2) {
                $search_data['min_price'] = -$search_data['min_price'];
            }
        }
        // 实际金额最大钱数
        if (!empty($search_data['max_price'])) {
            if (empty($search_data['wor_plus_minus'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
            }
            $search_data['max_price'] = $search_data['max_price'] * 100;
            if ($search_data['wor_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', 2)
                ->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_ids, $search_data);
            }
            $list_data = DB::table('work_order as a')
                ->leftJoin('work_client as b', 'b.wocl_wor_id', '=', 'a.wor_id')
                ->leftJoin('order_goods_temporary as orgt', 'orgt.orgt_ord_id', '=', 'a.wor_id')
                ->where('wor_cid', $user_info->adm_cid)
                ->where('wor_superior_shop_id', $shop_ids)
                ->where('wor_delete', 1)
                ->where('wor_collection_bill', 1) //是否代收账单：1正常工单2代收账单
                ->where('orgt_adm_id', $user_info->adm_id)
                ->where('orgt_type', 2)
                ->where(function ($query) use ($search_data) { //订单号
                    if (!empty($search_data['wor_order_number'])) {
                        $query->where('wor_order_number', 'like', '%' . $search_data['wor_order_number'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //工单号
                    if (!empty($search_data['wor_number'])) {
                        $query->where('wor_number', 'like', '%' . $search_data['wor_number'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //客户单位
                    if (!empty($search_data['wocl_channel_unit'])) {
                        $query->where('wocl_channel_unit', 'like', '%' . $search_data['wocl_channel_unit'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //姓名
                    if (!empty($search_data['wocl_name'])) {
                        $query->where('wocl_name', 'like', '%' . $search_data['wocl_name'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //联系电话
                    if (!empty($search_data['wocl_phone'])) {
                        $query->where('wocl_phone', 'like', '%' . $search_data['wocl_phone'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //车牌号
                    if (!empty($search_data['wocl_car_num'])) {
                        $query->where('wocl_car_num', 'like', '%' . $search_data['wocl_car_num'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //车型
                    if (!empty($search_data['wocl_car_vehicle_type'])) {
                        $query->where('wocl_car_vehicle_type', 'like', '%' . $search_data['wocl_car_vehicle_type'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //订单类型1会员零售2客户单位3速电派单
                    if (!empty($search_data['wor_type'])) {
                        $query->where('wor_type', $search_data['wor_type']);
                    }
                })
                ->where(function ($query) use ($search_data) { //1.新订单 2未派单 3待接单/已派单 4.未出发/已接单 5.预约/已预约 6.出发/已出发  7.抵达/抵达 8.待审核/完成待审核 9驳回/完成已驳回 10完成/完成已通过 11终止 12锁定13.速电撤销回收
                    if (!empty($search_data['wor_state'])) {
                        $query->where('wor_state', $search_data['wor_state']);
                    }
                })
                ->where(function ($query) use ($search_data) { //服务技师id
                    if (!empty($search_data['wor_service_adm_id'])) {
                        $query->where('wor_service_adm_id', $search_data['wor_service_adm_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //派单人
                    if (!empty($search_data['wor_create_id'])) {
                        $query->where('wor_create_id', $search_data['wor_create_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //备注
                    if (!empty($search_data['wor_remark'])) {
                        $query->where('wor_remark', 'like', '%' . $search_data['wor_remark'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //订单类型
                    if (!empty($search_data['wor_service_type'])) {
                        $query->where('wor_service_type', $search_data['wor_service_type']);
                    }
                })
                ->where(function ($query) use ($search_data) { //创建时间/派单时间
                    // 如果选择开始时间并且选择结束时间
                    if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                        $query->whereBetween('wor_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('wor_create_time', '>=', $search_data['create_time_start']);
                        } else {
                            // 如果选择结束时间
                            if (!empty($search_data['create_time_end'])) {
                                $query->where('wor_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                            }
                        }
                    }
                })
                ->where(function ($query) use ($search_data) { //1系统工单2外派工单
                    if (!empty($search_data['wocl_wor_type']) && $search_data['wocl_wor_type'] == 1) {
                        $query->whereIn('wocl_wor_type', [1, 3]);
                    } elseif (!empty($search_data['wocl_wor_type'])) {
                        $query->whereIn('wocl_wor_type', [2, 4, 5]);
                    }
                })
                ->where(function ($query) use ($search_data) { //1系统工单2外派工单
                    if (!empty($search_data['join_type']) && $search_data['join_type'] == 1) {
                        $query->whereIn('wocl_wor_type', 4);
                    } elseif (!empty($search_data['join_type'])) {
                        $query->where('wocl_wor_type', 2);
                    }
                })
                ->where(function ($query) use ($search_data) { //服务门店id
                    if (!empty($search_data['wor_service_shop_id'])) {
                        $query->where('wor_service_shop_id', $search_data['wor_service_shop_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //实际金额区间搜索
                    // 如果选择最小钱数并且选择最大钱数
                    if (!empty($search_data['min_price']) && !empty($search_data['max_price'])) {
                        $query->whereBetween('wor_actual_price', [$search_data['min_price'], $search_data['max_price']]);
                    } else {
                        // 如果选择最小钱数
                        if (!empty($search_data['min_price'])) {
                            $query->where('wor_actual_price', '>=', $search_data['min_price']);
                        } else {
                            // 如果选择最大钱数
                            if (!empty($search_data['max_price'])) {
                                $query->where('wor_actual_price', '<=', $search_data['max_price']);
                            }
                        }
                    }
                })
                ->where(function ($query) use ($search_data) { //服务项目id
                    if (!empty($search_data['wor_service_sepr_id'])) {
                        $query->where('wor_service_sepr_id', $search_data['wor_service_sepr_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //客户id/会员id
                    if (!empty($search_data['wocl_client_id'])) {
                        $query->where('wocl_client_id', $search_data['wocl_client_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //仓库id
                    if (!empty($search_data['wor_ware_id'])) {
                        $query->where('wor_ware_id', $search_data['wor_ware_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //商品检索编码
                    if (!empty($search_data['goo_goods_encode'])) {
                        $query->where('orgt_goods_encode', 'like', '%' . $search_data['goo_goods_encode'] . '%');
                    }
                })
                ->select('wor_id', 'wor_create_id', 'wor_number', 'wor_order_number', 'wor_service_sepr_id', 'wor_service_adm_id', 'wor_service_type', 'wor_service_state', 'wor_state', 'wor_pass', 'wor_type', 'wor_goo_amount', 'wor_remark', 'wor_shop_id', 'wor_create_time', 'wor_audit_times', 'wocl_channel_unit', 'wocl_name', 'wocl_phone', 'wocl_car_num', 'wocl_address', 'wor_service_shop_id', 'wor_ware_id', 'wor_collection_price', 'wocl_longitude', 'wocl_latitude', 'wor_actual_price', 'wor_plus_minus', 'wocl_province', 'wocl_city', 'wocl_county', 'wocl_wor_type', 'wocl_join_audit', 'wor_account_state', 'wocl_join_wor_id', 'wocl_consent_state', 'wocl_appoint_remark', 'wocl_assign_price', 'wocl_plus_minus', 'wocl_rescue_service_price', 'wocl_rescue_collection_price', 'wocl_client_id', 'wocl_sd_virtual_type', 'wocl_precise_lock', 'wor_appoint_time', 'wocl_whether_app', 'wor_order_id', 'wocl_car_vehicle_type', 'wocl_before_wor_state')
                ->orderBy('wor_id', 'desc')
                ->paginate($this->show_count);
        } else {
            $list_data = DB::table('work_order as a')
                ->leftJoin('work_client as b', 'b.wocl_wor_id', '=', 'a.wor_id')
                ->where('wor_cid', $user_info->adm_cid)
                ->where('wor_superior_shop_id', $shop_ids)
                ->where('wor_delete', 1)
                ->where('wor_collection_bill', 1) //是否代收账单：1正常工单2代收账单
                ->where(function ($query) use ($search_data) { //订单号
                    if (!empty($search_data['wor_order_number'])) {
                        $query->where('wor_order_number', 'like', '%' . $search_data['wor_order_number'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //工单号
                    if (!empty($search_data['wor_number'])) {
                        $query->where('wor_number', 'like', '%' . $search_data['wor_number'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //客户单位
                    if (!empty($search_data['wocl_channel_unit'])) {
                        $query->where('wocl_channel_unit', 'like', '%' . $search_data['wocl_channel_unit'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //姓名
                    if (!empty($search_data['wocl_name'])) {
                        $query->where('wocl_name', 'like', '%' . $search_data['wocl_name'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //联系电话
                    if (!empty($search_data['wocl_phone'])) {
                        $query->where('wocl_phone', 'like', '%' . $search_data['wocl_phone'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //车牌号
                    if (!empty($search_data['wocl_car_num'])) {
                        $query->where('wocl_car_num', 'like', '%' . $search_data['wocl_car_num'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //车型
                    if (!empty($search_data['wocl_car_vehicle_type'])) {
                        $query->where('wocl_car_vehicle_type', 'like', '%' . $search_data['wocl_car_vehicle_type'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //订单类型1会员零售2客户单位3速电派单
                    if (!empty($search_data['wor_type'])) {
                        $query->where('wor_type', $search_data['wor_type']);
                    }
                })
                ->where(function ($query) use ($search_data) { //1.新订单 2未派单 3待接单/已派单 4.未出发/已接单 5.预约/已预约 6.出发/已出发  7.抵达/抵达 8.待审核/完成待审核 9驳回/完成已驳回 10完成/完成已通过 11终止 12锁定13.速电撤销回收
                    if (!empty($search_data['wor_state'])) {
                        $query->where('wor_state', $search_data['wor_state']);
                    }
                })
                ->where(function ($query) use ($search_data) { //服务技师id
                    if (!empty($search_data['wor_service_adm_id'])) {
                        $query->where('wor_service_adm_id', $search_data['wor_service_adm_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //派单人
                    if (!empty($search_data['wor_create_id'])) {
                        $query->where('wor_create_id', $search_data['wor_create_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //备注
                    if (!empty($search_data['wor_remark'])) {
                        $query->where('wor_remark', 'like', '%' . $search_data['wor_remark'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //订单类型
                    if (!empty($search_data['wor_service_type'])) {
                        $query->where('wor_service_type', $search_data['wor_service_type']);
                    }
                })
                ->where(function ($query) use ($search_data) { //创建时间/派单时间
                    // 如果选择开始时间并且选择结束时间
                    if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                        $query->whereBetween('wor_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('wor_create_time', '>=', $search_data['create_time_start']);
                        } else {
                            // 如果选择结束时间
                            if (!empty($search_data['create_time_end'])) {
                                $query->where('wor_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                            }
                        }
                    }
                })
                ->where(function ($query) use ($search_data) { //1系统工单2外派工单
                    if (!empty($search_data['wocl_wor_type']) && $search_data['wocl_wor_type'] == 1) {
                        $query->whereIn('wocl_wor_type', [1, 3]);
                    } elseif (!empty($search_data['wocl_wor_type'])) {
                        $query->whereIn('wocl_wor_type', [2, 4, 5]);
                    }
                })
                ->where(function ($query) use ($search_data) { //1系统工单2外派工单
                    if (!empty($search_data['join_type']) && $search_data['join_type'] == 1) {
                        $query->where('wocl_wor_type', 4);
                    } elseif (!empty($search_data['join_type']) && $search_data['join_type'] == 2) {
                        $query->where('wocl_wor_type', 2);
                    } elseif (!empty($search_data['join_type']) && $search_data['join_type'] == 3) {
                        $query->where('wocl_wor_type', 5);
                    }
                })
                ->where(function ($query) use ($search_data) { //服务门店id
                    if (!empty($search_data['wor_service_shop_id'])) {
                        $query->where('wor_service_shop_id', $search_data['wor_service_shop_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //实际金额区间搜索
                    // 如果选择最小钱数并且选择最大钱数
                    if (!empty($search_data['min_price']) && !empty($search_data['max_price'])) {
                        $query->whereBetween('wor_actual_price', [$search_data['min_price'], $search_data['max_price']]);
                    } else {
                        // 如果选择最小钱数
                        if (!empty($search_data['min_price'])) {
                            $query->where('wor_actual_price', '>=', $search_data['min_price']);
                        } else {
                            // 如果选择最大钱数
                            if (!empty($search_data['max_price'])) {
                                $query->where('wor_actual_price', '<=', $search_data['max_price']);
                            }
                        }
                    }
                })
                ->where(function ($query) use ($search_data) { //服务项目id
                    if (!empty($search_data['wor_service_sepr_id'])) {
                        $query->where('wor_service_sepr_id', $search_data['wor_service_sepr_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //客户id/会员id
                    if (!empty($search_data['wocl_client_id'])) {
                        $query->where('wocl_client_id', $search_data['wocl_client_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //仓库id
                    if (!empty($search_data['wor_ware_id'])) {
                        $query->where('wor_ware_id', $search_data['wor_ware_id']);
                    }
                })
                ->select('wor_id', 'wor_create_id', 'wor_number', 'wor_order_number', 'wor_service_sepr_id', 'wor_service_adm_id', 'wor_service_type', 'wor_service_state', 'wor_state', 'wor_pass', 'wor_type', 'wor_goo_amount', 'wor_remark', 'wor_shop_id', 'wor_create_time', 'wor_audit_times', 'wocl_channel_unit', 'wocl_name', 'wocl_phone', 'wocl_car_num', 'wocl_address', 'wor_service_shop_id', 'wor_ware_id', 'wor_collection_price', 'wocl_longitude', 'wocl_latitude', 'wor_actual_price', 'wor_plus_minus', 'wocl_province', 'wocl_city', 'wocl_county', 'wocl_wor_type', 'wocl_join_audit', 'wor_account_state', 'wocl_join_wor_id', 'wocl_consent_state', 'wocl_appoint_remark', 'wocl_assign_price', 'wocl_plus_minus', 'wocl_rescue_service_price', 'wocl_rescue_collection_price', 'wocl_client_id', 'wocl_sd_virtual_type', 'wocl_precise_lock', 'wor_appoint_time', 'wocl_whether_app', 'wor_order_id', 'wocl_car_vehicle_type', 'wocl_before_wor_state')
                ->orderBy('wor_id', 'desc')
                ->paginate($this->show_count);
        }
        $list_items = $list_data->items();
        $virtual_shop_id = [];
        $shop_id = [];
        $virtual_adm_id = [];
        if ($list_items) {
            $wocl_client_id = array_unique(array_column($list_items, 'wocl_client_id')); //选择的客户id，会员id/单位id
            // 查询客户单位
            $channel = DB::table('channel_unit')
                ->whereIn('chun_id', $wocl_client_id)
                ->where('chun_shop_id', $shop_ids)
                ->where('chun_state', '1')
                ->pluck('chun_unit_name', 'chun_id')
                ->toArray();
            $wor_order_id = array_column($list_items, 'wor_order_id');
            // 查询订单状态
            $find_ord_state = DB::table('order')
                ->whereIn('ord_id', $wor_order_id)
                ->pluck('ord_wor_state', 'ord_id')->toArray();

            $wor_ware_id = array_column($list_items, 'wor_ware_id');
            $find_ware_data = DB::table('warehouse')
                ->whereIn('ware_id', $wor_ware_id)
                ->pluck('ware_name', 'ware_id')
                ->toArray();

            foreach ($list_items as $key => $value) {
                $wor_id[] = $value->wor_id;
                $adm_id[] = $value->wor_create_id;
                $adm_id[] = $value->wor_service_adm_id;
                $service_sepr_id[] = $value->wor_service_sepr_id;
                $shop_id[] = $value->wor_shop_id;
                if ($value->wocl_wor_type != 4) {
                    $shop_id[] = $value->wor_service_shop_id;
                } else {
                    $virtual_shop_id[] = $value->wor_service_shop_id;
                    $virtual_adm_id[] = $value->wor_service_adm_id;
                }
                $shop_id[] = $value->wor_service_shop_id;
                if ($value->wocl_appoint_remark) {
                    $list_items[$key]->wor_remark = $value->wor_remark . '【预约备注】' . $value->wocl_appoint_remark;
                }
                // 客户单位名称
                if (isset($channel[$value->wocl_client_id])) {
                    $list_items[$key]->wocl_channel_unit = $channel[$value->wocl_client_id];
                } else {
                    if ($value->wor_type == 3) {
                        $list_items[$key]->wocl_channel_unit = '速电快保';
                    } else {
                        $list_items[$key]->wocl_channel_unit = $value->wocl_channel_unit;
                    }
                }
                // 门店未发货,APP拒单,速电锁定,速电撤销后,锁定库存没有还回原仓库,需要把锁定库存还回原仓库
                $list_items[$key]->revocation = 1; //速电锁定撤销订单状态值1无取消工单2取消工单
                if ($value->wor_type == 3) { //速电派单
                    if ($value->wor_state == 12 && $value->wor_service_state == 10 && $find_ord_state[$value->wor_order_id] == 9 && $value->wocl_before_wor_state == 2) {
                        $list_items[$key]->revocation = 2;
                    }
                }

                // 仓库名称
                if (isset($find_ware_data[$value->wor_ware_id])) {
                    $list_items[$key]->wor_ware_id = $find_ware_data[$value->wor_ware_id];
                } else {
                    $list_items[$key]->wor_ware_id = '';
                }
            }
            $shop_id = array_unique($shop_id);
            // 查找账号id对应的账号姓名
            $find_shop = DB::table('shop')
                ->whereIn('shop_id', $shop_id)
                ->get(['shop_id', 'shop_store_name', 'shop_type']);

            // 查找虚拟加盟店数据
            $virtual_shop = DB::table('virtual_shop')
                ->whereIn('vish_id', $virtual_shop_id)
                ->get(['vish_id', 'vish_store_name']);

            $adm_id = array_unique($adm_id);
            // 查找账号id对应的账号姓名
            $find_admin = DB::table('admin')
                ->whereIn('adm_id', $adm_id)
                ->get(['adm_id', 'adm_name']);
            // 查找工单商品
            $work_goods = DB::table('work_good as wogo')
                ->leftjoin('goods as goo', 'goo.goo_id', '=', 'wogo.wogo_goo_id')
                ->whereIn('wogo_wor_id', $wor_id)
                // ->where('wogo_state', '!=', 2)
                ->select('wogo_wor_id', 'wogo_goo_id', 'wogo_goo_name', 'wogo_goo_goods_encode', 'wogo_goo_type', 'wogo_goo_price', 'wogo_goo_amount', 'wogo_is_recycle', 'wogo_actual_recycle_number', 'wogo_collection_price', 'wogo_state', 'wogo_recycle_quantity', 'wogo_recycle_price', 'wogo_tem_goo_name as tem_goo_name', 'wogo_assign_price', 'goo_brse_id', 'goo_bra_name', 'goo_class')
                ->get()->toArray();
            // 查询系列数据
            $goo_brse_id = array_column($work_goods, 'goo_brse_id');
            $brse_data = DB::table('brand_serie')
                ->whereIn('brse_id', $goo_brse_id)
                ->pluck('brse_name', 'brse_id')
                ->toArray();
            foreach ($work_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) {
                            $work_goods[$key]->wogo_goo_name = $brse_data[$value->goo_brse_id] . ' ' . $value->wogo_goo_name;
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $work_goods[$key]->wogo_goo_name = $brse_data[$value->goo_brse_id] . ' ' . $value->wogo_goo_name;
                            }
                        }
                    }
                }
                // 显示品牌名称
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                    if ($value->goo_class == 2) {
                        $work_goods[$key]->wogo_goo_name = $value->goo_bra_name . ' ' . $value->wogo_goo_name;
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $work_goods[$key]->wogo_goo_name = $value->goo_bra_name . ' ' . $value->wogo_goo_name;
                        }
                    }
                }
                unset($work_goods[$key]->goo_class);
                unset($work_goods[$key]->goo_brse_id);
            }
            // 查询备注信息
            $wor_reamrks = DB::table('order_remarks')
                ->whereIn('orre_wor_id', $wor_id)
                ->select('orre_create_adm_name', 'orre_content', 'orre_time', 'orre_wor_id', 'orre_module')
                ->orderby('orre_id', 'desc')
                ->get();

            // 服务项目
            $service_project = DB::table('service_project')
                ->whereIn('sepr_id', $service_sepr_id)
                ->get(['sepr_id', 'sepr_name']);

            // 查找所有订单回收金额
            $recycle_price = DB::table('junk_recycle')
                ->whereIn('jur_wor_id', $wor_id)
                ->where('jur_price', '!=', 0)
                ->get(['jur_wor_id', 'jur_price']);
            // 查找操作记录
            $work_log = DB::table('order_log')
                ->whereIn('orlo_wor_id', $wor_id)
                ->orderBy('orlo_id', 'desc')
                ->get(['orlo_wor_id', 'orlo_time', 'orlo_create_adm_name', 'orlo_content']);
        } else {
            $find_admin = [];
            $work_goods = [];
            $service_project = [];
            $find_shop = [];
            $work_log = [];
            $recycle_price = 0;
            $wor_reamrks = [];
            $virtual_shop = [];
        }
        $state_count = DB::table('work_order')
            ->where('wor_cid', $user_info->adm_cid)
            ->where('wor_superior_shop_id', $shop_ids)
            ->where('wor_delete', 1)
            ->where('wor_collection_bill', 1) //是否代收账单：1正常工单2代收账单
            ->select(DB::raw('count(*) as count, wor_state'))
            ->groupBy('wor_state')
            ->get();
        // 查询门店打印模板
        $shpt_data = DB::table('shop_print_template')
            ->where('shpt_shop_id', $user_info->adm_shop_id)
            ->whereIn('shpt_print_type', [8, 9, 10])
            ->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['find_shop'] = $find_shop;                    //返回门店名称
        $data_info['find_admin'] = $find_admin;                  //返回账号姓名
        $data_info['work_goods'] = $work_goods;                  //订单商品数据
        $data_info['service_project'] = $service_project;        //服务项目
        $data_info['state_count'] = $state_count;                //状态数量统计
        $data_info['recycle_price'] = $recycle_price;            //订单回收金额
        $data_info['work_log'] = $work_log;                      //操作记录
        $data_info['wor_reamrks'] = $wor_reamrks;                //工单备注
        $data_info['virtual_shop'] = $virtual_shop;              //虚拟加盟店
        $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_ids, $search_data)
    {
        set_time_limit(0);

        $list_data = DB::table('work_good')
            ->where('wogo_state', '!=', 2)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_goods_encode'])) {
                    $query->where('wogo_goo_goods_encode', $search_data['goo_goods_encode']);
                }
            }) //商品检索编码
            ->select('wogo_wor_id', 'wogo_goo_name', 'wogo_goo_goods_encode')
            ->groupBy('wogo_wor_id')
            ->get()->toArray();
        foreach ($list_data as $key => $value) {
            // 查询该单是否存在
            $orgt_id = DB::table('order_goods_temporary')
                ->where('orgt_ord_id', $value->wogo_wor_id)
                ->where('orgt_adm_id', $user_info->adm_id)
                ->where('orgt_type', 2)
                ->value('orgt_id');
            if (empty($orgt_id)) {
                // 查询工单单号
                $wor_number = DB::table('work_order')
                    ->where('wor_id', $value->wogo_wor_id)
                    ->where('wor_cid', $user_info->adm_cid)
                    ->where('wor_shop_id', $shop_ids)
                    ->where('wor_delete', 1)
                    ->where('wor_collection_bill', 1) //是否代收账单：1正常工单2代收账单
                    ->value('wor_number');
                $orgt_data['orgt_ord_id'] = $value->wogo_wor_id; //工单id
                $orgt_data['orgt_order_number'] = $wor_number ?? ''; //工单单号
                $orgt_data['orgt_adm_id'] = $user_info->adm_id; //操作人
                $orgt_data['orgt_goods_encode'] = $value->wogo_goo_goods_encode; //检索编码
                $orgt_data['orgt_type'] = 2; //类型：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 VerifyWorkOrderController;
        $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']);

        $select_field = "wor_id, wor_number, wor_service_sepr_id, wor_audit_times, wor_service_adm_id, wor_code, wor_create_id, wor_service_type, wor_service_state, wor_state, wor_type, wor_goo_amount, wor_remark, wor_pass, wor_create_time, wocl_channel_unit, wocl_name, wocl_phone, wocl_car_num, wocl_address, ware_name, ware_type, ware_id, wor_shop_id, wor_service_shop_id, wor_collection_price, wocl_collect_state, wocl_province, wocl_city, wocl_county, wor_actual_price, wocl_rescue_service_price, wocl_join_wor_id, wocl_assign_price, wocl_plus_minus, wor_plus_minus, wocl_car_vehicle_type, wocl_rescue_collection_price, wocl_join_ord_id, wocl_wor_type, wor_order_id, wocl_client_id, wocl_sd_virtual_type, wocl_shit_id, wor_order_number";
        $work_order = new WorkOrders();
        $return_data = $work_order->info($user_info, $request->all(), 1, $select_field);
        return response()->json($return_data);
    }

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

        // 查询工单信息
        $wor_data = DB::table('work_order as wo')
            ->leftjoin('order as o', 'o.ord_id', '=', 'wo.wor_order_id')
            ->where('wor_id', $request['wor_id'])
            ->select('wor_number', 'wor_create_id', 'wor_service_type', 'wor_service_sepr_id', 'wor_state', 'wor_service_state', 'wor_pass', 'wor_service_adm_id', 'wor_service_shop_id', 'wor_ware_id', 'wor_order_id', 'wor_order_number', 'wor_remark', 'wor_type', 'ord_state', 'ord_payment_way')
            ->first();
        // 判断工单是否存在
        if (empty($wor_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单不存在！']);
        }
        // 结算状态1未结算2已结算3已核销4已收款
        if ($wor_data->ord_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单已结算，无法改单！']);
        }
        // 订单类型为服务单类型的可以编辑
        if ($wor_data->wor_service_type != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'订单类型不是服务单，无法改单！']);
        }
        // 服务状态：1待接单2已接单3预约4出发5抵达6完成待审核7完成已驳回8完成通过9终止
        // 技师完成之前可以改单，完成以后不能改单；原来定的改单条件
        if ($wor_data->wor_service_state > 5 &&  $wor_data->wor_service_state != 10) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单已服务完成，无法改单！']);
        }

        // 获取用户信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 返回工单数据
        if ($request['type'] == 1) {
            // 锁定之后不可以改单
            if ($wor_data->wor_pass == 4) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单已锁定，无法改单！']);
            }
            // 改单锁定
            $lock_return = $this->editLockUnlock($user_info, $request['wor_id'], 4);
            if ($lock_return['code'] == 500) {
                return response()->json($lock_return);
            }

            // 获取账号id对应的姓名
            $adm_id[] = $wor_data->wor_create_id;
            $adm_id[] = $wor_data->wor_service_adm_id;
            $adm_id = array_filter($adm_id); //如果没有回调函数，默认就是删除数组中值为false的元素
            $find_admin = DB::table('admin')
                ->whereIn('adm_id', $adm_id)
                ->pluck('adm_name', 'adm_id')->toArray();

            $wor_data->wor_create_name = $find_admin[$wor_data->wor_create_id];
            $wor_data->wor_service_adm_name = isset($find_admin[$wor_data->wor_service_adm_id]) ? $find_admin[$wor_data->wor_service_adm_id] : '';

            // 查询服务项目名称
            $wor_data->wor_service_sepr_name = DB::table('service_project')
                ->where('sepr_id', $wor_data->wor_service_sepr_id)
                ->value('sepr_name');
            // 查询服务门店名称
            $wor_data->wor_service_shop_name = DB::table('shop')
                ->where('shop_id', $wor_data->wor_service_shop_id)
                ->value('shop_store_name');
            // 查询仓库名称
            $wor_data->ware_name = DB::table('warehouse')
                ->where('ware_id', $wor_data->wor_ware_id)
                ->value('ware_name');

            // 获取工单商品数据
            $wogo_goods = DB::table('work_good')
                ->where('wogo_wor_id', $request['wor_id'])
                ->where('wogo_state', '!=', 2)
                ->select('wogo_id', 'wogo_waon_class', 'wogo_goo_id', 'wogo_goo_name', 'wogo_goo_type', 'wogo_goo_goods_encode', 'wogo_goo_price', 'wogo_state', 'wogo_collection_price', 'wogo_recycle_price', 'wogo_goo_amount', 'wogo_goo_inventory', 'wogo_recycle_quantity', 'wogo_is_recycle', 'wogo_tem_goo_name as tem_goo_name')
                ->get()->toArray();

            // 获取工单技师代收状态
            $wor_client = DB::table('work_client')
                ->where('wocl_wor_id', $request['wor_id'])
                ->first(['wocl_collect_state', 'wocl_name', 'wocl_phone', 'wocl_car_num', 'wocl_province', 'wocl_city', 'wocl_county', 'wocl_address', 'wocl_wor_type', 'wocl_standby_battery_type']);
            if ($wor_client->wocl_wor_type == 2) {
                $data['wor_client'] = $wor_client;
            } else {
                $data['wor_client'] = [];
            }
            $wor_data->wocl_collect_state = $wor_client->wocl_collect_state;
            $wor_data->standby_battery_type = $wor_client->wocl_standby_battery_type;
            $data['wor_data'] = $wor_data;
            $data['wogo_goods'] = $wogo_goods;
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        } elseif ($request['type'] == 3) {
            // 改单取消，取消锁定
            $lock_return = $this->editLockUnlock($user_info, $request['wor_id'], 1);
            return response()->json($lock_return);
        }

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

        // 判断是否为外派工单
        $join_ord_data = DB::table('work_client')
            ->where('wocl_wor_id', $request['wor_id'])
            ->first(['wocl_join_ord_id', 'wocl_wor_type']);
        // 处理提交的商品数据
        $goo_all_price = 0; //商品总金额
        $goo_all_quantity = 0; //商品总数量
        $goo_all_collection = 0; //总的代收金额
        $recycle_number = 0; //工单计划总的旧货回收数量
        $recycle_price = 0; //工单计划总的旧货回收金额
        $wor_is_recycle = 2; //是否回收：1.回收2.不回收

        $del_wogo_id = [];
        $del_goo_id = [];
        $del_is_recycle = [];
        $del_goo_amount = [];
        $del_goo_inventory = [];
        $del_goo_price = [];
        $del_collection_price = [];
        $add_goo_id = [];
        $add_goo_inventory = [];
        $add_goo_is_recycle = [];
        $add_goo_price = [];
        $add_goo_amount = [];
        $add_goo_collection_price = [];
        $add_goo_name = [];
        $add_goo_goods_encode = [];
        $add_goo_data = [];
        foreach ($request['wogo_goo_id'] as $key => $value) {
            if (!is_numeric($value) || !is_numeric($request['wogo_waon_class'][$key]) || !is_numeric($request['wogo_goo_price'][$key]) || !is_numeric($request['wogo_goo_amount'][$key]) || !in_array($request['wogo_is_recycle'][$key], [1, 2]) || !is_numeric($request['wogo_recycle_price'][$key]) || !is_numeric($request['wogo_recycle_quantity'][$key]) || !is_numeric($request['wogo_id'][$key]) || !in_array($request['wogo_state'][$key], [1, 2, 5, 6]) || !in_array($request['wogo_goo_inventory'][$key], [1, 2]) || !is_numeric($request['wogo_collection_price'][$key])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品参数类型错误']);
            }
            // 判断是否有删除的商品 wogo_state 商品状态1.正常 2.删除
            if ($request['wogo_state'][$key] == 2) {
                // 改单时删除的商品信息
                $del_wogo_id[] = $request['wogo_id'][$key]; //删除的商品工单主键id
                $del_goo_id[] = $value; //删除的商品id
                $del_is_recycle[] = $request['wogo_is_recycle'][$key]; //删除的商品是否回收
                $del_goo_amount[$value] = $request['wogo_goo_amount'][$key]; //删除的商品数量
                $del_goo_inventory[$value] = $request['wogo_goo_inventory'][$key]; //删除的商品出库类型1.良品 2.优先
                $del_goo_price[$value] = $request['wogo_goo_price'][$key]; //删除的商品金额
                $del_collection_price[$value] = $request['wogo_collection_price'][$key]; //删除的商品代收金额
            } else {
                // 需要保存的商品数据，包括新添加的商品，更改的商品
                // 没有被删除的都计算到  工单结算金额内
                $goo_all_price += $request['wogo_goo_price'][$key] * $request['wogo_goo_amount'][$key];
                // 没有被删除的都计算到  总的商品数量内
                $goo_all_quantity += $request['wogo_goo_amount'][$key];
                // 没有被删除的都计算到  代收金额，代收金额不乘以数量
                $goo_all_collection += $request['wogo_collection_price'][$key];
                // 没有被删除的都计算到  工单计划总的旧货回收数量
                if ($request['wogo_is_recycle'][$key] == 1) {
                    // 回收商品
                    $wor_is_recycle = 1; //是否回收：1.回收2.不回收
                    $recycle_number += $request['wogo_recycle_quantity'][$key]; //回收总数量
                    $recycle_price += $request['wogo_recycle_price'][$key] * $request['wogo_recycle_quantity'][$key]; //回收总金额
                }

                // 组合发货单商品表数据
                $dego_goo_data[$key]['digo_wago_class'] = $request['wogo_waon_class'][$key];
                $dego_goo_data[$key]['digo_goo_id'] = $value;
                $dego_goo_data[$key]['digo_goo_price'] = $request['wogo_goo_price'][$key] * 100;
                $dego_goo_data[$key]['digo_goo_quantity'] = $request['wogo_goo_amount'][$key];
                $dego_goo_data[$key]['digo_is_recycle'] = $request['wogo_is_recycle'][$key];
                $dego_goo_data[$key]['digo_goo_inventory'] = $request['wogo_goo_inventory'][$key];
                $dego_goo_data[$key]['digo_state'] = $request['wogo_state'][$key];
                $find_goods_data = DB::table('goods')
                    ->where('goo_id', $value)
                    ->first(['goo_name', 'goo_goods_encode', 'goo_type', 'goo_ampere_hour', '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_goo_data[$key]['digo_goo_name'] =  $find_goods_data->goo_name;
                $dego_goo_data[$key]['digo_goo_goods_encode'] = $find_goods_data->goo_goods_encode;
                $dego_goo_data[$key]['digo_goo_type'] = $find_goods_data->goo_type;
                if (!empty($request['tem_goo_name'][$key])) {
                    $tem_goo_name = $request['tem_goo_name'][$key];
                } else {
                    $tem_goo_name = '';
                }
                $dego_goo_data[$key]['digo_tem_goo_name'] = $tem_goo_name; //商品临时名称

                // 组合仓库商品改变的数据
                $ware_goo_id[$key] = $value; //商品id
                $ware_goo_number[$value] = $request['wogo_goo_amount'][$key]; //商品数量
                $ware_goo_inventory[$value] = $request['wogo_goo_inventory'][$key]; //商品出库方式1.良品 2.优先
                $ware_goo_wago_class[$value] = $request['wogo_waon_class'][$key]; //商品仓库类别
                // 判断是否有新增的商品
                if ($request['wogo_id'][$key] == 0) {
                    // 工单商品主键id为0的，说明是新添加的商品
                    $add_goo_id[] = $value; //新增商品的id
                    $add_goo_inventory[] = $request['wogo_goo_inventory'][$key]; //商品出库方式1.良品 2优先
                    $add_goo_is_recycle[] = $request['wogo_is_recycle'][$key]; //新增商品的是否回收
                    $add_goo_price[] = $request['wogo_goo_price'][$key]; //新增商品的售价
                    $add_goo_amount[] = $request['wogo_goo_amount'][$key]; //新增商品的数量
                    $add_goo_collection_price[] = $request['wogo_collection_price'][$key]; //新增商品的代收金额
                    $add_goo_name[] = $find_goods_data->goo_name; //新增商品名称
                    $add_goo_goods_encode[] = $find_goods_data->goo_goods_encode; //新增商品的检索编码
                    $add_goo_type[] = $find_goods_data->goo_type; //新增商品类型

                    $add_goo_data['waon_class'][$value] = $request['wogo_waon_class'][$key]; //新增仓库类别
                    $add_goo_data['recycle_price'][$value] = $request['wogo_recycle_price'][$key]; //新增回收金额
                    $add_goo_data['recycle_quantity'][$value] = $request['wogo_recycle_quantity'][$key]; //新增回收数量
                    $add_goo_data['goo_state'][$value] = $request['wogo_state'][$key]; //新增商品状态
                    $add_goo_data['goo_type'][$value] = $find_goods_data->goo_type; //新增商品类型
                    $add_goo_data['goo_name'][$value] = $find_goods_data->goo_name; //新增商品名称
                    $add_goo_data['goo_goods_encode'][$value] = $find_goods_data->goo_goods_encode; //新增商品的检索编码
                    $add_goo_data['goo_amount'][$value] = $request['wogo_goo_amount'][$key]; //新增商品的数量
                    $add_goo_data['goo_price'][$value] = $request['wogo_goo_price'][$key]; //新增商品的售价
                    $add_goo_data['goo_is_recycle'][$value] = $request['wogo_is_recycle'][$key]; //新增商品的是否回收
                    $add_goo_data['goo_inventory'][$value] = $request['wogo_goo_inventory'][$key]; //商品出库方式1.良品 2优先
                    $add_goo_data['goo_collection_price'][$value] = $request['wogo_collection_price'][$key]; //新增商品的代收金额
                    $add_goo_data['goo_ampere_hour'][$value] = $find_goods_data->goo_ampere_hour; //新增的商品安时数
                    if (!empty($request['tem_goo_name'][$key])) {
                        $tem_goo_name = $request['tem_goo_name'][$key];
                    } else {
                        $tem_goo_name = '';
                    }
                    $add_goo_data['tem_goo_name'][$value] = $tem_goo_name;
                }
            }

            // 如果是外派工单
            if ($join_ord_data->wocl_wor_type == 2) {
                $find_goods_data = DB::table('goods')
                    ->where('goo_id', $value)
                    ->first(['goo_name', 'goo_goods_encode', 'goo_type', 'goo_ampere_hour', '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;
                    }
                }
                $join[$key]['wged_wogo_id'] = $request['wogo_id'][$key]; //主键id
                $join[$key]['wged_order_id'] = $join_ord_data->wocl_join_ord_id; //主键id
                $join[$key]['wged_wor_id'] = $request['wor_id']; //工单id
                $join[$key]['wged_ware_id'] = $request['wor_ware_id']; //仓库id
                $join[$key]['wged_waon_class'] = $request['wogo_waon_class'][$key]; //商品仓库类别
                $join[$key]['wged_goo_id'] = $value; //商品id
                $join[$key]['wged_is_recycle'] = $request['wogo_is_recycle'][$key];
                $join[$key]['wged_goo_name'] = $find_goods_data->goo_name; //商品名称
                $join[$key]['wged_goo_goods_encode'] = $find_goods_data->goo_goods_encode;
                $join[$key]['wged_goo_type'] = $find_goods_data->goo_type;
                $join[$key]['wged_state'] = $request['wogo_state'][$key];
                $join[$key]['wged_goo_price'] = $request['wogo_goo_price'][$key] * 100;
                $join[$key]['wged_collection_price'] = $request['wogo_collection_price'][$key] * 100;
                $join[$key]['wged_recycle_price'] = $request['wogo_is_recycle'][$key]; //新增商品的是否回收
                $join[$key]['wged_goo_amount'] = $request['wogo_goo_amount'][$key]; //新增商品的数量
                $join[$key]['wged_goo_inventory'] = $request['wogo_goo_inventory'][$key]; //商品出库方式1.良品
                $join[$key]['wged_recycle_quantity'] = $request['wogo_recycle_quantity'][$key]; //新增回收数量
                $join[$key]['wged_type'] = 2;
            }
        }
        // 判断是否为加盟店账号,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. 处理发货单的数据
        DB::beginTransaction();

        // 如果改单属于外派工单
        if (isset($join)) {
            $time = date('Y-m-d H:i:s');
            $work_res = DB::table('work_order')
                ->where('wor_id', $request['wor_id'])
                ->update(['wor_pass' => 8, 'wor_update_time' => $time]);
            $order_res = DB::table('order')
                ->where('ord_id', $wor_data->wor_order_id)
                ->update(['ord_order_state' => 7, 'ord_update_time' => $time]);
            $wged_res = DB::table('work_good_edit')->insert($join);

            // 修改加盟店数据
            $join_order_res = DB::table('order')
                ->where('ord_id', $join_ord_data->wocl_join_ord_id)
                ->update(['ord_order_state' => 9, 'ord_update_time' => $time]);

            $join_wor_id = DB::table('work_order')
                ->where('wor_order_id', $join_ord_data->wocl_join_ord_id)
                ->value('wor_id');
            if (!empty($join_wor_id)) {
                $join_wor_id = DB::table('work_order')
                    ->where('wor_id', $join_wor_id)
                    ->update(['wor_pass' => 10, 'wor_update_time' => $time]);
            }
            // $work_client = DB::table('work_client')
            //     ->where('wocl_wor_id',$request['wor_id'])
            //     ->first(['wocl_name','wocl_phone','wocl_province','wocl_city','wocl_county','wocl_address','wocl_collect_state']);
            if (!empty($request['wocl_name'])) {
                $wced_data['wced_name'] = $request['wocl_name'];
                $wced_data['wced_wor_id'] = $request['wor_id'];
                $wced_data['wced_order_id'] = $join_ord_data->wocl_join_ord_id;
                $wced_data['wced_phone'] = $request['wocl_phone'];
                $wced_data['wced_province'] = $request['wocl_province'];
                $wced_data['wced_city'] = $request['wocl_city'];
                $wced_data['wced_county'] = $request['wocl_county'];
                $wced_data['wced_address'] = $request['wocl_address'];
                $wced_data['wced_ware_id'] = 0;
                $wced_data['wced_service_adm_id'] = 0;
                $wced_res = DB::table('work_client_edit')->insert($wced_data);
            } else {
                $wced_res = true;
            }


            if ($wged_res && $work_res && $order_res && $wced_res) {
                Common::addLog($user_info, getRealIp($request), '工单列表', '改单', '改单：' . $wor_data->wor_number . '提交改单申请');
                // 添加操作记录
                orderLog($user_info, $wor_data->wor_order_id, 0, '提交改单申请');
                orderLog($user_info, 0, $request['wor_id'], '提交改单申请');
                DB::commit();
                return response()->json(['code'=>200, 'msg'=>'error', 'data'=>'已经提交改单申请']);
            } else {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'改单失败']);
            }
        }

        // 如果传过来的仓库id不等于原来的id说明更换了仓库
        if ($wor_data->wor_ware_id != $request['wor_ware_id']) {
            $work_res = DB::table('work_order')
                ->where('wor_id', $request['wor_id'])
                ->update(['wor_ware_id' => $request['wor_ware_id']]);
            $order_res = DB::table('order')
                ->where('ord_id', $wor_data->wor_order_id)
                ->update(['ord_ware_id' => $request['wor_ware_id']]);
            if (empty($work_res) || empty($order_res)) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'改单失败']);
            }
            $wor_data->wor_ware_id = $request['wor_ware_id'];
        }
        $workOrder = new WorkOrder;
        $dibi_return = $workOrder->editDispatchBill(
            $user_info, //用户信息
            $shop_id, //总店id
            $request['wor_id'], //工单id
            $wor_data, //工单数据
            $request['wor_service_adm_id'], //改单的服务技师id
            $goo_all_quantity, //改单的商品总数量
            $dego_goo_data, //改单的发货单商品数据
            $ware_goo_id, //改单的商品id
            $ware_goo_number, //改单的商品数量：商品id=>商品数量
            $ware_goo_inventory, //改单的出库类型：商品id=>出库类型
            $ware_goo_wago_class, //改单的仓库类别：商品id=>仓库类别
            $add_goo_id, //改单添加的商品
            $add_goo_is_recycle, //改单添加的商品回收类型
            $add_goo_price, //改单添加的商品售价
            $add_goo_amount, //改单添加的商品数量
            $add_goo_inventory, //改单添加的商品出库类型
            $add_goo_name, //改单添加的商品名称
            $add_goo_goods_encode //改单添加的商品检索编码
        );
        if ($dibi_return['code'] == 500) {
            DB::rollBack();
            return response()->json($dibi_return);
        }

        //客户信息
        $ord_client = DB::table('order_client')
            ->where('orcl_ord_id', $wor_data->wor_order_id)
            ->first(['orcl_channel_unit', 'orcl_name', 'orcl_phone', 'orcl_id']);

        // 获取到当前工单的订单信息
        $ord_info = DB::table('order')
            ->where('ord_id', $wor_data->wor_order_id)
            ->first(['ord_client_id']);

        // 2. 处理工单数据
        $wor_return = $workOrder->editWorkData(
            $user_info,
            $request->all(),
            $wor_data,
            $ord_info,
            $ord_client,
            $del_wogo_id,
            $del_goo_id,
            $del_goo_price,
            $del_goo_amount,
            $add_goo_id,
            $add_goo_is_recycle,
            $add_goo_price,
            $add_goo_amount,
            $add_goo_collection_price,
            $add_goo_inventory,
            $goo_all_price,
            $recycle_number,
            $wor_is_recycle,
            $goo_all_quantity,
            $goo_all_collection,
            $add_goo_data
        );
        if ($wor_return['code'] == 500) {
            DB::rollBack();
            return response()->json($wor_return);
        }

        // 3.订单商品表做修改
        $ord_return = $workOrder->editOrderData(
            $wor_data,
            $del_goo_id,
            $del_is_recycle,
            $del_goo_amount,
            $add_goo_id,
            $add_goo_price,
            $add_goo_amount,
            $add_goo_is_recycle,
            $add_goo_collection_price,
            $add_goo_data
        );
        if ($ord_return['code'] == 500) {
            DB::rollBack();
            return response()->json($ord_return);
        }

        // 添加操作记录
        $order_record = orderLog($user_info, $wor_data->wor_order_id, 0, '改单');
        $work_record = orderLog($user_info, 0, $request['wor_id'], '改单');

        if ($order_record && $work_record) {
            $adm_phone =  DB::table('admin')
                ->where('adm_id', $request['wor_service_adm_id'])
                ->value('adm_phone');
            $push_name['alias'][] = $adm_phone; //发送对象
            $result_push = pushMessage($push_name, '您有新的工单：' . $wor_data->wor_number . ' 请注意查收');

            // 添加新增订单信息的提示
            $inhi_data['inhi_original_adm_id'] = $wor_data->wor_create_id; //原始单号创建人
            $inhi_data['inhi_original_id'] = $request['wor_id']; //原始单id
            $inhi_data['inhi_original_number'] = $wor_data->wor_number; //原始单号
            $inhi_data['inhi_original_state'] = $wor_data->wor_state; //原始单状态
            $inhi_data['inhi_original_operation'] = '工单改单'; //操作
            $inhi_data['inhi_operation_state'] = 13; //操作状态：13工单改单
            addInformationHint($user_info, $inhi_data, 2);

            Common::addLog($user_info, getRealIp($request), '工单列表', '改单', '改单：' . $wor_data->wor_number . '成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'改单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'改单失败']);
        }
    }

    /**
     * [editLockUnlock 改单锁定，取消锁定；改单的时候需要把跟工单相关的数据都锁定]
     * @param  [int] $user_info [用户信息]
     * @param  [int] $wor_id    [工单id]
     * @param  [int] $type      [类型：4锁定 1取消锁定]
     * @return [type]         [description]
     */
    private function editLockUnlock($user_info, $wor_id, $type)
    {
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        // 1总店  2加盟店
        $shop_type = $user_info->shop_superior_id ? 2 : 1;

        // 工单状态数据
        $wor = DB::table('work_order')
            ->where('wor_id', $wor_id)
            ->first(['wor_state', 'wor_order_id']);
        if ($wor->wor_state == 8) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'当前工单是待审核状态，不可锁定'];
        }
        // 订单数据  判断是否为第三方派单
        $order_data = DB::table('order')
            ->where('ord_id', $wor->wor_order_id)
            ->first(['ord_type', 'ord_other_system_number', 'ord_wor_state', 'ord_order_state']);
        DB::beginTransaction();
        // 如果是第三方派单通知速电锁单 type = 4 锁定 1取消锁定
        if ($order_data->ord_type == 3 && $type == 4) {
            $orci['orcl_update_time'] = date('Y-m-d H:i:s');
            $orci['orcl_before_wor_state'] = $order_data->ord_wor_state;
            $before_state = DB::table('order_client')
                ->where('orcl_ord_id', $wor->wor_order_id)
                ->update($orci);
            $order_edit_data['ord_update_time'] = date('Y-m-d H:i:s');
            $order_edit_data['ord_order_state'] = 2; //订单锁单状态1正常2系统锁定3第三方系统锁定
            $order_edit_data['ord_wor_state'] = 8; //8锁定
            $ord_res = DB::table('order')
                ->where('ord_id', $wor->wor_order_id)
                ->update($order_edit_data);

            $param['time'] = date('Y-m-d H:i:s'); //收货时间
            $param['serial_num'] = $order_data->ord_other_system_number; //派工单号
            $param['token'] = md5(md5($param['time'] . 'c883e5e641818d993a2d8d966ca450bf')); //token
            $url = config('apisystem.sd_server_name') . '/index.php/lockorder';
            $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'=>'失败']);
            }
        } elseif ($order_data->ord_type == 3 && $type == 1) {
            $before_state = DB::table('order_client')
                ->where('orcl_ord_id', $wor->wor_order_id)
                ->value('orcl_before_wor_state');
            $order_edit_data['ord_update_time'] = date('Y-m-d H:i:s');
            $order_edit_data['ord_wor_state'] = $before_state;
            $order_edit_data['ord_order_state'] = 1; //订单锁单状态1正常2系统锁定3第三方系统锁单
            $ord_res = DB::table('order')
                ->where('ord_id', $wor->wor_order_id)
                ->update($order_edit_data);
            $param['time'] = date('Y-m-d H:i:s'); //收货时间
            $param['serial_num'] = $order_data->ord_other_system_number; //派工单号
            $param['token'] = md5(md5($param['time'] . 'c883e5e641818d993a2d8d966ca450bf')); //token
            $url = config('apisystem.sd_server_name') . '/index.php/undoive';
            $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'=>'失败']);
            }
        }
        if ($type == 1) {
            //如果此工单已经取消锁定
            if ($wor->wor_state != 12) {
                if ($wor->wor_state == 15) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'当前工单已经被运营中心锁定！'];
                }
                return ['code'=>500, 'msg'=>'error', 'data'=>'当前工单已经被解锁,请刷新页面'];
            }
            $hint = '取消锁定';
            $wocl_state = DB::table('work_client')
                ->where('wocl_wor_id', $wor_id)
                ->value('wocl_before_wor_state');
            if (in_array($wocl_state, [1, 2, 3])) {
                $wor_edit_data['wor_service_state'] = 1;
            } else {
                $wor_edit_data['wor_service_state'] = stateSetting($wocl_state);
            }
            $wor_edit_data['wor_state'] = $wocl_state;

            // 总店
            if ($shop_type == 1) {
                // 总店订单状态修改
                $before_wor_state = DB::table('order_client')
                    ->where('orcl_ord_id', $wor->wor_order_id)
                    ->value('orcl_before_wor_state');
                $join_ord['ord_order_state'] = 1;
                $join_ord['ord_wor_state'] = $before_wor_state;
                $join_ord['ord_update_time'] = date('Y-m-d H:i:s');
                $head_order_res = DB::table('order')
                    ->where('ord_id', $wor->wor_order_id)
                    ->update($join_ord);

                // 判断是否为加盟店派单
                $join_ord_id = DB::table('work_client')
                    ->where('wocl_wor_id', $wor_id)
                    ->value('wocl_join_ord_id');
                if (!empty($join_ord_id)) {
                    // 加盟店订单
                    $join_ord_wor_state = DB::table('order_client')
                        ->where('orcl_ord_id', $join_ord_id)
                        ->value('orcl_before_wor_state');
                    $join_ord['ord_order_state'] = 1; //总店加盟店锁单
                    $join_ord['ord_wor_state'] = $join_ord_wor_state;
                    $join_order_res = DB::table('order')
                        ->where('ord_id', $join_ord_id)
                        ->update($join_ord);
                    // 加盟店工单
                    $join_wor_info = DB::table('work_order')
                        ->where('wor_order_id', $join_ord_id)
                        ->first(['wor_state', 'wor_id']);
                    if (!empty($join_wor_info)) {
                        $wocl_state = DB::table('work_client')
                            ->where('wocl_wor_id', $join_wor_info->wor_id)
                            ->value('wocl_before_wor_state');
                        if (in_array($wocl_state, [1, 2, 3])) {
                            $join_wor_data['wor_service_state'] = 1;
                        } else {
                            $join_wor_data['wor_service_state'] = stateSetting($wocl_state);
                        }
                        $join_wor_data['wor_state'] = $wocl_state;
                        $join_wor_data['wor_update_time'] = date('Y-m-d H:i:s');
                        $join_wor_res = DB::table('work_order')
                            ->where('wor_id', $join_wor_info->wor_id)
                            ->update($join_wor_data);

                        // 2.1 查询当前工单的发货单的状态，已发货的发货单不需要更改
                        $dego_type = 1;
                        $find_dego =  DB::table('dispatch_bill')
                            ->where('dego_order_type', 2) //类型：1.订单发货 2.工单发货
                            ->where('dego_type', $dego_type) //   类型：1未出库2已出库3作废4锁定
                            ->where('dego_wor_id', $join_wor_info->wor_id)
                            ->select('dego_id')
                            ->orderBy('dego_id', 'desc')
                            ->first();
                        if (empty($find_dego)) {
                            $dego_res = true;
                        } else {
                            // 2.2 把还未发货的发货单改成锁定状态
                            $dego_edit_data['dego_type'] = $type;
                            $dego_edit_data['dego_update_time'] = date('Y-m-d H:i:s');
                            $dego_res = DB::table('dispatch_bill')
                                ->where('dego_id', $find_dego->dego_id)
                                ->update($dego_edit_data);
                        }
                        if (empty($dego_res)) {
                            DB::rollBack();
                            return ['code'=>500, 'msg'=>'error', 'data'=>'当前工单改单' . $hint . '失败'];
                        }
                    } else {
                        $join_wor_res = true;
                    }
                } else {
                    $join_order_res = true;
                    $join_wor_res = true;
                }
            } else {
                // 加盟店订单数据
                $join_order_info = DB::table('order_client')
                    ->where('orcl_ord_id', $wor->wor_order_id)
                    ->first(['orcl_before_wor_state', 'orcl_join_wor_id']);
                $join_order_data['ord_wor_state'] = $join_order_info->orcl_before_wor_state;
                $join_order_data['ord_order_state'] = 1;
                $join_order_res = DB::table('order')
                    ->where('ord_id', $wor->wor_order_id)
                    ->update($join_order_data);

                // 总店工单数据
                $head_wor_info = DB::table('work_client')
                    ->where('wocl_wor_id', $join_order_info->orcl_join_wor_id)
                    ->first(['wocl_before_wor_state', 'wocl_wor_type']);

                // 如果是外派工单
                if (isset($head_wor_info->wocl_wor_type) && $head_wor_info->wocl_wor_type == 2) {
                    if (in_array($head_wor_info->wocl_before_wor_state, [1, 2, 3])) {
                        $join_wor_data['wor_service_state'] = 1;
                    } else {
                        $join_wor_data['wor_service_state'] = stateSetting($head_wor_info->wocl_before_wor_state);
                    }
                    $join_wor_data['wor_state'] = $head_wor_info->wocl_before_wor_state;
                    $join_wor_res = DB::table('work_order')
                        ->where('wor_id', $join_order_info->orcl_join_wor_id)
                        ->update($join_wor_data);

                    $head_wor_info = DB::table('work_order')
                        ->where('wor_id', $join_order_info->orcl_join_wor_id)
                        ->first(['wor_order_id']);
                    // 总店工单数据
                    $state = DB::table('order_client')
                        ->where('orcl_ord_id', $head_wor_info->wor_order_id)
                        ->first(['orcl_before_wor_state']);
                    $head_order_data['ord_order_state'] = 1; //总店加盟店锁单
                    $head_order_data['ord_wor_state'] = $state->orcl_before_wor_state; //锁定
                    $head_order_data['ord_update_time'] = date('Y-m-d H:i:s'); //锁定
                    $head_order_res = DB::table('order')
                        ->where('ord_id', $head_wor_info->wor_order_id)
                        ->update($head_order_data);
                } else {
                    $head_order_res = true;
                    $join_wor_res = true;
                }
            }
        } else {
            // 如果此工单已经锁定
            if ($wor->wor_state == 12) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'当前工单已经被锁定,请刷新页面'];
            }
            $hint = '锁定';
            $wor_edit_data['wor_state'] = 12;
            $wor_edit_data['wor_service_state'] = 10;
            $wocl['wocl_before_wor_state'] = $wor->wor_state;
            $wocl['wocl_update_time'] = date('Y-m-d H:i:s');
            $wocl_state = DB::table('work_client')
                ->where('wocl_wor_id', $wor_id)
                ->update($wocl);
            // 总店
            $shop_versions = $user_info->shop_versions;
            if ($shop_type == 1) {
                $head_order_data['orcl_before_wor_state'] = $order_data->ord_wor_state;
                $head_order_data['orcl_before_order_state'] = $order_data->ord_order_state;
                $head_order_data['ord_wor_state'] = 8;
                $head_order_data['ord_order_state'] = 6;
                $head_order_data['ord_update_time'] = date('Y-m-d H:i:s');
                // 总店订单数据
                $head_order_res = DB::table('order as o')
                    ->join('order_client as oc', 'oc.orcl_ord_id', '=', 'o.ord_id')
                    ->where('ord_id', $wor->wor_order_id)
                    ->update($head_order_data);

                // 判断是否派给加盟店派单
                $join_ord_id = DB::table('work_client')
                    ->where('wocl_wor_id', $wor_id)
                    ->value('wocl_join_ord_id');
                if (!empty($join_ord_id)) {
                    $join_ord_wor_state = DB::table('order')
                        ->where('ord_id', $join_ord_id)
                        ->value('ord_wor_state');
                    $join_ord['ord_order_state'] = 6; //总店加盟店锁单
                    $join_ord['ord_wor_state'] = 8; //锁定
                    $join_ord['orcl_before_wor_state'] = $join_ord_wor_state;
                    $join_order_res = DB::table('order as o')
                        ->join('order_client as oc', 'oc.orcl_ord_id', '=', 'o.ord_id')
                        ->where('ord_id', $join_ord_id)
                        ->update($join_ord);

                    $join_wor_info = DB::table('work_order')
                        ->where('wor_order_id', $join_ord_id)
                        ->first(['wor_state', 'wor_id']);
                    if (!empty($join_wor_info)) {
                        $join_wor_data['wocl_before_wor_state'] = $join_wor_info->wor_state;
                        $join_wor_data['wor_service_state'] = 10;
                        $join_wor_data['wor_state'] = 12;
                        $join_wor_res = DB::table('work_order as wo')
                            ->join('work_client as wc', 'wc.wocl_wor_id', '=', 'wo.wor_id')
                            ->where('wor_id', $join_wor_info->wor_id)
                            ->update($join_wor_data);

                        // 2.1 查询当前工单的发货单的状态，已发货的发货单不需要更改
                        $dego_type = 4;
                        $find_dego =  DB::table('dispatch_bill')
                            ->where('dego_order_type', 2) //类型：1.订单发货 2.工单发货
                            ->where('dego_type', $dego_type) //   类型：1未出库2已出库3作废4锁定
                            ->where('dego_wor_id', $join_wor_info->wor_id)
                            ->select('dego_id')
                            ->orderBy('dego_id', 'desc')
                            ->first();
                        if (empty($find_dego)) {
                            $dego_res = true;
                        } else {
                            // 2.2 把还未发货的发货单改成锁定状态
                            $dego_edit_data['dego_type'] = $type;
                            $dego_edit_data['dego_update_time'] = date('Y-m-d H:i:s');
                            $dego_res = DB::table('dispatch_bill')
                                ->where('dego_id', $find_dego->dego_id)
                                ->update($dego_edit_data);
                        }
                        if (empty($dego_res)) {
                            DB::rollBack();
                            return ['code'=>500, 'msg'=>'error', 'data'=>'当前工单改单' . $hint . '失败'];
                        }
                    } else {
                        $join_wor_res = true;
                    }
                } else {
                    $join_order_res = true;
                    $join_wor_res = true;
                }
            } else {
                // 加盟店订单数据
                $join_order_info = DB::table('order as o')
                    ->join('order_client as oc', 'oc.orcl_ord_id', '=', 'o.ord_id')
                    ->where('ord_id', $wor->wor_order_id)
                    ->first(['ord_wor_state', 'orcl_join_wor_id', 'orcl_order_type']);

                $join_order_data['orcl_before_wor_state'] = $join_order_info->ord_wor_state;
                $join_order_data['ord_wor_state'] = 8;
                $join_order_data['ord_order_state'] = 6;
                $join_order_res = DB::table('order as o')
                    ->join('order_client as oc', 'oc.orcl_ord_id', '=', 'o.ord_id')
                    ->where('ord_id', $wor->wor_order_id)
                    ->update($join_order_data);
                // 如果是外派工单
                if (isset($join_order_info->orcl_order_type) && $join_order_info->orcl_order_type == 2) {
                    // 加盟店工单数据
                    $head_wor_info = DB::table('work_order')
                        ->where('wor_id', $join_order_info->orcl_join_wor_id)
                        ->first(['wor_order_id', 'wor_state']);
                    $join_wor_data['wocl_before_wor_state'] = $head_wor_info->wor_state;
                    $join_wor_data['wor_service_state'] = 10;
                    $join_wor_data['wor_state'] = 12;
                    $join_wor_res = DB::table('work_order as wo')
                        ->join('work_client as wc', 'wc.wocl_wor_id', '=', 'wo.wor_id')
                        ->where('wor_id', $join_order_info->orcl_join_wor_id)
                        ->update($join_wor_data);

                    $head_order_info = DB::table('order')
                        ->where('ord_id', $head_wor_info->wor_order_id)
                        ->first(['ord_wor_state']);
                    $head_order_data['orcl_before_wor_state'] = $head_order_info->ord_wor_state;
                    $head_order_data['ord_order_state'] = 6; //总店加盟店锁单
                    $head_order_data['ord_wor_state'] = 8; //锁定
                    $head_order_data['ord_update_time'] = date('Y-m-d H:i:s');
                    $head_order_res = DB::table('order as o')
                        ->join('order_client as oc', 'oc.orcl_ord_id', '=', 'o.ord_id')
                        ->where('ord_id', $head_wor_info->wor_order_id)
                        ->update($head_order_data);
                } else {
                    $head_order_res = true;
                    $join_wor_res = true;
                }
            }
        }

        // 1. 将工单改成锁定状态
        $wor_edit_data['wor_pass'] = $type; //审核：1.待审核 2.合格 3.不合格 4锁定
        $wor_edit_data['wor_update_time'] = date('Y-m-d H:i:s');
        $wor_res = DB::table('work_order')
            ->where('wor_id', $wor_id)
            ->update($wor_edit_data);

        // 2.1 查询当前工单的发货单的状态，已发货的发货单不需要更改
        $dego_type = $type == 1 ? 4 : 1;
        $find_dego =  DB::table('dispatch_bill')
            ->where('dego_order_type', 2) //类型：1.订单发货 2.工单发货
            ->where('dego_type', $dego_type) //   类型：1未出库2已出库3作废4锁定
            ->where('dego_wor_id', $wor_id)
            ->select('dego_id')
            ->orderBy('dego_id', 'desc')
            ->first();

        if (empty($find_dego)) {
            $dego_res = true;
        } else {
            // 2.2 把还未发货的发货单改成锁定状态
            $dego_edit_data['dego_type'] = $type;
            $dego_edit_data['dego_update_time'] = date('Y-m-d H:i:s');
            $dego_res = DB::table('dispatch_bill')
                ->where('dego_id', $find_dego->dego_id)
                ->update($dego_edit_data);
        }
        if ($dego_res && $wor_res && $wocl_state && $join_wor_res && $join_order_res && $head_order_res) {
            orderLog($user_info, 0, $wor_id, $hint);
            DB::commit();
            return ['code'=>200, 'msg'=>'success', 'data'=>'当前工单改单' . $hint . '成功'];
        } else {
            DB::rollBack();
            return ['code'=>500, 'msg'=>'error', 'data'=>'当前工单改单' . $hint . '失败'];
        }
    }

    /**
     * [editLockUnlock 改单锁定，取消锁定；改单的时候需要把跟工单相关的数据都锁定]
     * @param  [int] $user_info [用户信息]
     * @param  [int] $wor_id    [工单id]
     * @param  [int] $type      [类型：4锁定 1取消锁定]
     * @return [type]         [description]
     */
    private function cityLockUnlock($user_info, $wor_id, $type, $wor_ord)
    {
        // 工单状态数据
        if ($wor_ord->wor_state == 8) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'当前工单是待审核状态，不可锁定'];
        }

        if ($type == 1) { //取消锁单
            // 如果此工单已经锁定
            if ($wor_ord->wor_state != 12) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'当前工单已经被解锁,请刷新页面'];
            }
            $hint = '取消锁定';
            $wocl_state = DB::table('work_client')
                ->where('wocl_wor_id', $wor_id)
                ->value('wocl_before_wor_state');
            if ($wocl_state == 12) {
                $wocl_state = DB::table('order_client')
                    ->where('orcl_ord_id', $wor_ord->wocl_join_ord_id)
                    ->value('orcl_before_wor_state');
            }
            if (in_array($wocl_state, [1, 2, 3])) {
                $wor_edit_data['wor_service_state'] = 1;
            } else {
                $wor_edit_data['wor_service_state'] = stateSetting($wocl_state);
            }
            $wor_edit_data['wor_state'] = $wocl_state;

            // 城市运营中心锁单解锁 门店 锁单之前的状态
            $shop_ord = DB::table('order as o')
                ->leftJoin('order_client as oc', 'oc.orcl_ord_id', '=', 'o.ord_id')
                ->where('ord_id', $wor_ord->wocl_join_ord_id)
                ->select('ord_id', 'ord_state', 'orcl_before_cilo_order_state', 'orcl_before_cilo_wor_state')
                ->first();
            $shop_wor = DB::table('work_order as wo')
                ->leftJoin('work_client as wc', 'wc.wocl_wor_id', '=', 'wo.wor_id')
                ->where('wor_order_id', $shop_ord->ord_id)
                ->select('wor_id', 'wor_state', 'wocl_before_cilo_wor_state')
                ->first();
            if (!empty($shop_wor)) {
                $shop_wocl_state = $shop_wor->wocl_before_cilo_wor_state;
                if (in_array($shop_wocl_state, [1, 2, 3])) {
                    $shop_wor_edit_data['wor_service_state'] = 1;
                } else {
                    $shop_wor_edit_data['wor_service_state'] = stateSetting($shop_wocl_state);
                }
                $shop_wor_edit_data['wor_state'] = $shop_wocl_state;
            }

            // $shop_orcl_state = $shop_ord->orcl_before_order_state;
            // $shop_worcl_state = $shop_ord->orcl_before_wor_state;
            $shop_orcl_state = $shop_ord->orcl_before_cilo_order_state;
            $shop_worcl_state = $shop_ord->orcl_before_cilo_wor_state;
            // 运营中心订单
            $head_order_data['ord_wor_state'] = $wor_ord->orcl_before_wor_state;
            $head_order_data['ord_order_state'] = 1; //订单锁定状态1正常2系统锁定3速电锁定4第三方系统锁定5速电待审核6总店加盟店锁单7等待加盟店审核8等待总店待审核9审核改单10可欠超出设置11运营中心锁定
            $head_order_data['ord_update_time'] = date('Y-m-d H:i:s');
            // 运营中心订单数据
            $head_order_res = DB::table('order as o')
                ->join('order_client as oc', 'oc.orcl_ord_id', '=', 'o.ord_id')
                ->where('ord_id', $wor_ord->wor_order_id)
                ->update($head_order_data);

            // 门店订单
            $shop_order_data['ord_wor_state'] = $shop_worcl_state; //orcl_before_wor_state
            $shop_order_data['ord_order_state'] = $shop_orcl_state; //orcl_before_order_state
            $shop_order_data['ord_update_time'] = date('Y-m-d H:i:s');
            // 门店订单数据
            $shop_order_res = DB::table('order')
                ->where('ord_id', $shop_ord->ord_id)
                ->update($shop_order_data);
        } else {
            // 如果此工单已经锁定
            if ($wor_ord->wor_state == 12) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'当前工单已经被锁定,请刷新页面'];
            }
            $find_shop_ord = DB::table('order as o')
                ->join('order_client as oc', 'oc.orcl_ord_id', '=', 'o.ord_id')
                ->where('ord_id', $wor_ord->wocl_join_ord_id)
                ->select('ord_id', 'ord_wor_state', 'ord_order_state')
                ->first();
            if (in_array($find_shop_ord->ord_wor_state, [1, 7])) { //门店没有工单
                $shop_wor = '';
            } else {
                // 下级门店工单
                $shop_wor = DB::table('work_order as wo')
                    ->leftJoin('work_client as wc', 'wo.wor_id', '=', 'wc.wocl_wor_id')
                    ->where('wor_order_id', $wor_ord->wocl_join_ord_id)
                    ->select('wor_id', 'wor_state', 'wocl_before_wor_state')
                    ->first();
                if ($wor_ord->wor_service_state != 1 && !empty($shop_wor)) { //wor_service_state 1待接单
                    $shop_wor_edit_data['wor_state'] = 15;
                    $shop_wor_edit_data['wor_service_state'] = 10;
                    $wocl_shop['wocl_before_cilo_wor_state'] = $shop_wor->wor_state;
                    $wocl_shop['wocl_update_time'] = date('Y-m-d H:i:s');
                    $wocl_shop_state = DB::table('work_client')
                        ->where('wocl_wor_id', $shop_wor->wor_id)
                        ->update($wocl_shop);
                }
            }
            $hint = '锁定';
            $wor_edit_data['wor_state'] = 12; //12锁定
            $wor_edit_data['wor_service_state'] = 10; //服务状态：10锁定
            $wocl['wocl_before_wor_state'] = $wor_ord->wor_state;
            $wocl['wocl_update_time'] = date('Y-m-d H:i:s');
            $wocl_state = DB::table('work_client')
                ->where('wocl_wor_id', $wor_id)
                ->update($wocl);

            // 运营中心订单
            $head_order_data['orcl_before_wor_state'] = $wor_ord->ord_wor_state;
            $head_order_data['orcl_before_order_state'] = $wor_ord->ord_order_state;
            $head_order_data['ord_wor_state'] = 8; //订单的工单状态1未派工单2服务中3售后中4已完成5无工单6审核活动7待接单8锁定9速电撤销回收10终止11取消订单12超出可欠天数待审核
            $head_order_data['ord_order_state'] = 2; //订单锁定状态1正常2系统锁定3速电锁定4第三方系统锁定5速电待审核6总店加盟店锁单7等待加盟店审核8等待总店待审核9审核改单10可欠超出设置11运营中心锁定
            $head_order_data['ord_update_time'] = date('Y-m-d H:i:s');
            // 运营中心订单数据
            $head_order_res = DB::table('order as o')
                ->join('order_client as oc', 'oc.orcl_ord_id', '=', 'o.ord_id')
                ->where('ord_id', $wor_ord->wor_order_id)
                ->update($head_order_data);

            // 门店订单
            $shop_order_data['orcl_before_cilo_wor_state'] = $find_shop_ord->ord_wor_state;
            $shop_order_data['orcl_before_cilo_order_state'] = $find_shop_ord->ord_order_state;
            $shop_order_data['ord_wor_state'] = 8;
            $shop_order_data['ord_order_state'] = 11; //11运营中心锁定
            $shop_order_data['ord_update_time'] = date('Y-m-d H:i:s');
            // 门店订单数据
            $shop_order_res = DB::table('order as o')
                ->join('order_client as oc', 'oc.orcl_ord_id', '=', 'o.ord_id')
                ->where('ord_id', $find_shop_ord->ord_id)
                ->update($shop_order_data);
        }

        // 1. 将工单改成锁定状态
        $wor_edit_data['wor_pass'] = $type; //审核：1.待审核 2.合格 3.不合格 4锁定
        $wor_edit_data['wor_update_time'] = date('Y-m-d H:i:s');
        $wor_res = DB::table('work_order')
            ->where('wor_id', $wor_id)
            ->update($wor_edit_data);
        if (!empty($shop_wor)) {
            if ($type == 1) {
                $shop_wocl_state = $shop_wor->wocl_before_cilo_wor_state;
                if ($shop_wocl_state == 12) {
                    $shop_wor_edit_data['wor_pass'] = 4; //审核：1.待审核 2.合格 3.不合格 4锁定
                } else {
                    $shop_wor_edit_data['wor_pass'] = $type; //审核：1.待审核 2.合格 3.不合格 4锁定
                }
            }

            $shop_wor_edit_data['wor_update_time'] = date('Y-m-d H:i:s');
            $shop_wor_res = DB::table('work_order')
                ->where('wor_id', $shop_wor->wor_id)
                ->update($shop_wor_edit_data);
            // 2.1 查询当前工单的发货单的状态，已发货的发货单不需要更改
            $dego_type = $type == 1 ? 4 : 1;
            $find_dego =  DB::table('dispatch_bill')
                ->where('dego_order_type', 2) //类型：1.订单发货 2.工单发货
                ->where('dego_type', $dego_type) //   类型：1未出库2已出库3作废4锁定
                ->where('dego_wor_id', $shop_wor->wor_id)
                ->select('dego_id')
                ->orderBy('dego_id', 'desc')
                ->first();
        } else {
            $find_dego = '';
            $shop_wor_res = true;
        }

        if (empty($find_dego)) {
            $dego_res = true;
        } else {
            // 2.2 把还未发货的发货单改成锁定状态
            $dego_edit_data['dego_type'] = $type;
            $dego_edit_data['dego_update_time'] = date('Y-m-d H:i:s');
            $dego_res = DB::table('dispatch_bill')
                ->where('dego_id', $find_dego->dego_id)
                ->update($dego_edit_data);
        }
        if ($dego_res && $wor_res && $wocl_state && $head_order_res && $shop_order_res && $shop_wor_res) {
            orderLog($user_info, 0, $wor_id, $hint);
            return ['code'=>200, 'msg'=>'success', 'data'=>'当前工单改单' . $hint . '成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'当前工单改单' . $hint . '失败'];
        }
    }

    // 锁定
    public function lock(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkOrderController;
        $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']);
        $find_wor_ord = DB::table('work_order as wo')
            ->leftJoin('work_client as wc', 'wo.wor_id', '=', 'wc.wocl_wor_id')
            ->leftJoin('order as o', 'wo.wor_order_id', '=', 'o.ord_id')
            ->leftJoin('order_client as oc', 'o.ord_id', '=', 'oc.orcl_ord_id')
            ->where('wor_id', $request['wor_id'])
            ->select('wor_number', 'wo.wor_type', 'wor_state', 'wor_order_id', 'wor_service_state', 'wc.wocl_join_ord_id', 'oc.orcl_shipment_party', 'wor_service_shop_id', 'ord_order_state', 'ord_wor_state', 'orcl_before_order_state')
            ->first();
        // $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        $shop_versions = $user_info->shop_versions;
        if ($shop_versions != 1 && $find_wor_ord->orcl_shipment_party == 5 && !empty($find_wor_ord->wocl_join_ord_id)) {
            DB::beginTransaction();
            $lock_city_res = $this->cityLockUnlock($user_info, $request['wor_id'], 4, $find_wor_ord);
            if ($lock_city_res['code'] == 200) {
                DB::commit();
                Common::addLog($user_info, getRealIp($request), '工单列表', '锁定', $find_wor_ord->wor_number . '锁定成功');
                $find_shop_ord = DB::table('order')
                    ->where('ord_id', $find_wor_ord->wocl_join_ord_id)
                    ->select('ord_id', 'ord_shop_id', 'ord_order_number', 'ord_create_id', 'ord_wor_state')
                    ->first();
                // 城市运营中心锁单信息的提示
                $find_shop_superior_id = DB::table('shop')
                    ->where('shop_id', $find_shop_ord->ord_shop_id)
                    ->select('shop_superior_id')
                    ->first();
                if ($find_shop_superior_id) {
                    $user_info->adm_shop_superior_id = $find_shop_superior_id->shop_superior_id;
                } else {
                    $user_info->adm_shop_superior_id = $find_shop_ord->ord_shop_id;
                }

                $user_info->adm_shop_id = $find_shop_ord->ord_shop_id;
                $inhi_data['inhi_original_adm_id'] = $find_shop_ord->ord_create_id; //原始单号创建人
                $inhi_data['inhi_original_id'] = $find_shop_ord->ord_id; //原始单id
                $inhi_data['inhi_original_number'] = $find_shop_ord->ord_order_number; //原始单号
                $inhi_data['inhi_original_state'] = $find_shop_ord->ord_wor_state; //原始单状态
                $inhi_data['inhi_original_operation'] = '城市运营中心锁单'; //操作
                $inhi_data['inhi_operation_state'] = 24; //操作状态：24城市运营中心锁单
                addInformationHint($user_info, $inhi_data, 1);
                // 查询技师信息，推送消息
                // if ($find_shop_wor->wor_service_adm_id) {
                //     $adm_phone =  DB::table('admin')
                //         ->where('adm_id', $find_shop_wor->wor_service_adm_id)
                //         ->value('adm_phone');
                //     $push_name['alias'][] = $adm_phone; //发送对象
                //     $result_push = pushMessage($push_name, '工单：' . $find_shop_wor->wor_number . ' 城市运营中心已锁定', 6);
                // }
                return response()->json($lock_city_res);
            } else {
                DB::rollBack();
                return response()->json($lock_city_res);
            }
        }
        // 锁定 order_client
        $lock_return = $this->editLockUnlock($user_info, $request['wor_id'], 4);
        if ($lock_return['code'] == 200) {
            $find_wor = DB::table('work_order')
                ->where('wor_id', $request['wor_id'])
                ->first(['wor_number', 'wor_service_adm_id']);
            // 查询技师信息，推送消息
            if ($find_wor->wor_service_adm_id) {
                $adm_phone =  DB::table('admin')
                    ->where('adm_id', $find_wor->wor_service_adm_id)
                    ->value('adm_phone');
                $push_name['alias'][] = $adm_phone; //发送对象
                $result_push = pushMessage($push_name, '工单：' . $find_wor->wor_number . ' 系统已锁定', 6);
            }
            Common::addLog($user_info, getRealIp($request), '工单列表', '锁定', $find_wor->wor_number . '锁定成功');
        }
        return response()->json($lock_return);
    }

    // 取消锁定
    public function unlock(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkOrderController;
        $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']);

        $find_wor_ord = DB::table('work_order as wo')
            ->leftJoin('work_client as wc', 'wo.wor_id', '=', 'wc.wocl_wor_id')
            ->leftJoin('order as o', 'wo.wor_order_id', '=', 'o.ord_id')
            ->leftJoin('order_client as oc', 'o.ord_id', '=', 'oc.orcl_ord_id')
            ->where('wor_id', $request['wor_id'])
            ->select('wor_number', 'wo.wor_type', 'wor_state', 'wor_order_id', 'wor_service_state', 'wc.wocl_join_ord_id', 'oc.orcl_shipment_party', 'wor_service_shop_id', 'ord_order_state', 'ord_wor_state', 'orcl_before_order_state', 'orcl_before_wor_state')
            ->first();
        // $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        $shop_versions = $user_info->shop_versions;
        if ($shop_versions != 1 && $find_wor_ord->orcl_shipment_party == 5 && !empty($find_wor_ord->wocl_join_ord_id)) {
            DB::beginTransaction();
            $lock_city_res = $this->cityLockUnlock($user_info, $request['wor_id'], 1, $find_wor_ord);
            if ($lock_city_res['code'] == 200) {
                DB::commit();
                Common::addLog($user_info, getRealIp($request), '工单列表', '取消锁定', $find_wor_ord->wor_number . '取消锁定成功');
                $find_shop_ord = DB::table('order')
                    ->where('ord_id', $find_wor_ord->wocl_join_ord_id)
                    ->select('ord_id', 'ord_order_number', 'ord_create_id', 'ord_wor_state', 'ord_shop_id')
                    ->first();
                // 城市运营中心锁单信息的提示
                $find_shop_superior_id = DB::table('shop')
                    ->where('shop_id', $find_shop_ord->ord_shop_id)
                    ->select('shop_superior_id')
                    ->first();
                if ($find_shop_superior_id) {
                    $user_info->adm_shop_superior_id = $find_shop_superior_id->shop_superior_id;
                } else {
                    $user_info->adm_shop_superior_id = $find_shop_ord->ord_shop_id;
                }
                $user_info->adm_shop_id = $find_shop_ord->ord_shop_id;
                $inhi_data['inhi_original_adm_id'] = $find_shop_ord->ord_create_id; //原始单号创建人
                $inhi_data['inhi_original_id'] = $find_shop_ord->ord_id; //原始单id
                $inhi_data['inhi_original_number'] = $find_shop_ord->ord_order_number; //原始单号
                $inhi_data['inhi_original_state'] = $find_shop_ord->ord_wor_state; //原始单状态
                $inhi_data['inhi_original_operation'] = '城市运营中心锁单'; //操作
                $inhi_data['inhi_operation_state'] = 24; //操作状态：24城市运营中心锁单
                addInformationHint($user_info, $inhi_data, 1);
                // 查询技师信息，推送消息
                // if ($find_shop_wor->wor_service_adm_id) {
                //     $adm_phone =  DB::table('admin')
                //         ->where('adm_id', $find_shop_wor->wor_service_adm_id)
                //         ->value('adm_phone');
                //     $push_name['alias'][] = $adm_phone; //发送对象
                //     $result_push = pushMessage($push_name, '工单：' . $find_shop_wor->wor_number . ' 城市运营中心已锁定', 6);
                // }
                return response()->json($lock_city_res);
            } else {
                DB::rollBack();
                return response()->json($lock_city_res);
            }
        }
        // 改单锁定
        $lock_return = $this->editLockUnlock($user_info, $request['wor_id'], 1);
        if ($lock_return['code'] == 200) {
            $find_wor = DB::table('work_order')
                ->where('wor_id', $request['wor_id'])
                ->first(['wor_number', 'wor_service_adm_id']);
            // 查询技师信息，推送消息
            if ($find_wor->wor_service_adm_id) {
                $adm_phone =  DB::table('admin')
                    ->where('adm_id', $find_wor->wor_service_adm_id)
                    ->value('adm_phone');
                $push_name['alias'][] = $adm_phone; //发送对象
                $result_push = pushMessage($push_name, '工单：' . $find_wor->wor_number . ' 系统取消锁定', 8);
            }
            Common::addLog($user_info, getRealIp($request), '工单列表', '取消锁定', $find_wor->wor_number . '取消锁定成功');
        }
        return response()->json($lock_return);
    }

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

        // 提交重新派单数据
        $return_data = WashWorkService::assign($user_info, $request->all());
        if ($return_data['code'] == 200) {
            DB::commit();
            return $this->success('重新派单成功');
        } else {
            DB::rollBack();
            return $this->error('重新派单失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 取消工单
    public function delete(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkOrderController;
        $error_message = $verify_data->rejectValidator($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_wor = DB::table('work_order as wor')
            ->leftjoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wor.wor_id')
            ->where('wor_id', $request['wor_id'])
            ->where('wor_shop_id', $user_info->adm_shop_id)
            ->select('wor_number', 'wor_state', 'wor_order_id', 'wor_goo_amount', 'wor_type', 'wor_actual_price', 'wor_ware_id', 'wor_remark', 'wor_pass', 'wor_service_type', 'wor_type', 'wocl_client_id', 'wocl_sd_virtual_type', 'wocl_wor_type', 'wor_order_number', 'wor_delete')
            ->first();
        if (empty($find_wor)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单不存在，无法取消工单！']);
        }
        if (!in_array($find_wor->wor_state, [1, 2, 12])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单不是未派单状态，无法取消工单！']);
        }
        if ($find_wor->wor_pass == 4) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单已经锁定，无法取消工单！']);
        }
        if ($find_wor->wor_delete != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单已经取消！']);
        }

        DB::beginTransaction();

        $work_order = new WorkOrders();
        $return_data = $work_order->deletes($user_info, $request->all(), $find_wor);
        if ($return_data['code'] == 200) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '工单列表', '取消工单', $find_wor->wor_number . '工单取消成功');
            return response()->json($return_data);
        } else {
            DB::rollBack();
            return response()->json($return_data);
        }
    }

    // 通过之前判断是否回收
    public function beforePass(Request $request)
    {
        // 查询信息
        $find_wor = DB::table('work_order as wor')
            ->leftjoin('work_client as wc', 'wor.wor_id', '=', 'wc.wocl_wor_id')
            ->where('wor_id', $request['wor_id'])
            ->select('wor_id', 'wor_is_recycle', 'wor_service_state', 'wor_service_type', 'wocl_wor_type')
            ->first();
        // wor_service_state 服务状态：1待接单2已接单3预约4出发5抵达6完成待审核7完成已驳回8完成通过
        if ($find_wor->wor_service_state != 6) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单服务未完成，无法审核通过']);
        }
        if ($find_wor->wocl_wor_type == 4) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'成功']);
        }

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

        // 通过之前判断是否合格，退货、旧货商品是否回收
        $esel_return = $this->estimateEligibility(
            $user_info,
            $request['wor_id'],
            $find_wor->wor_service_type,
            $find_wor->wor_is_recycle
        );
        return response()->json($esel_return);
    }

    /**
     * [estimateEligibility 通过之前判断是否合格]
     * @param  [type] $user_info           [用户信息]
     * @param  [type] $wor_id           [工单id]
     * @param  [type] $wor_service_type [订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单]
     * @param  [type] $recycle_state    [回收状态  1.回收2.不回收]
     * @return [type]                   [description]
     */
    private function estimateEligibility(
        $user_info,
        $wor_id,
        $wor_service_type,
        $recycle_state
    ) {
        // 判断是否为加盟店账号,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 ($wor_service_type == 4) {
            // 退货单，判断是否回收退货商品
            $find_rec = DB::table('recede_recycle')
                ->where('rec_cid', $user_info->adm_cid)
                ->where('rec_superior_shop_id', $shop_id)
                ->where('rec_source_type', 4)
                ->where('rec_ord_id', $wor_id)
                ->value('rec_state');
            if ($find_rec == 2) {
                return ['code'=>200, 'msg'=>'success', 'data'=>'成功'];
            } else {
                return ['code'=>500, 'msg'=>'error', 'data'=>'请先回收退货商品！'];
            }
        } elseif ($wor_service_type == 3) {
            // 换货单，判断退货商品是否回收，
            // rec_source_type 来源类型1. 售后退货 2. 工单退货(换货单) 3 页面新增 4 退货单 5技师退回
            $find_rec = DB::table('recede_recycle')
                ->where('rec_cid', $user_info->adm_cid)
                ->where('rec_superior_shop_id', $shop_id)
                ->where('rec_source_type', 2)
                ->where('rec_ord_id', $wor_id)
                ->value('rec_state');
            if ($find_rec != 2) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'请先回收退货商品！'];
            }
            // 判断是否有旧货回收商品，旧货回收商品是否回收
            if ($recycle_state == 1) {
                // jur_state 回收状态 1.未回收 2.已回收 3不回收
                $find_jur = DB::table('junk_recycle')
                    ->where('jur_cid', $user_info->adm_cid)
                    ->where('jur_superior_shop_id', $shop_id)
                    ->where('jur_wor_id', $wor_id)
                    ->value('jur_state');
                if ($find_jur == 1) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'请先回收旧货商品！'];
                }
            }
            return ['code'=>200, 'msg'=>'success', 'data'=>'成功'];
        } else {
            // 判断是否有旧货回收商品，旧货回收商品是否回收
            // if ($recycle_state == 1) {
            // jur_state 回收状态 1.未回收 2.已回收 3不回收
            $find_jur = DB::table('junk_recycle')
                ->where('jur_cid', $user_info->adm_cid)
                ->where('jur_superior_shop_id', $shop_id)
                ->where('jur_wor_id', $wor_id)
                ->value('jur_state');
            if ($find_jur == 1) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'请先回收旧货商品！'];
            }
            // }
            return ['code'=>200, 'msg'=>'success', 'data'=>'成功'];
        }
    }

    // 更改工单信息，审核通过
    public function updatePass(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkOrderController;
        $error_message = $verify_data->infoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 查询信息
        $find_wor = DB::table('work_order as wor')
            ->leftjoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wor.wor_id')
            ->where('wor_id', $request['wor_id'])
            ->select('wor_id', 'wor_number', 'wor_service_state', 'wor_order_id', 'wocl_client_id', 'wor_collection_price', 'wor_order_number', 'wor_service_shop_id', 'wor_is_recycle', 'wor_service_type', 'wor_plus_minus', 'wor_collection_bill', 'wocl_collect_state', 'wocl_name', 'wocl_channel_unit', 'wocl_acti_id', 'wor_service_sepr_id', 'wocl_join_wor_id', 'wocl_wor_type', 'wocl_join_ord_id', 'wor_actual_price', 'wor_service_adm_id', 'wor_type', 'wor_create_id', 'wocl_assign_price', 'wocl_plus_minus', 'wor_recycle_price', 'wor_ware_id', 'wocl_rescue_service_price', 'wor_remark', 'wocl_sd_virtual_type', 'wocl_shit_id')
            ->first();
        if ($find_wor->wor_service_state == 8) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'该工单已审核通过，请勿重复审核！']);
        }
        // wor_service_state 服务状态：1待接单2已接单3预约4出发5抵达6完成待审核7完成已驳回8完成通过
        if ($find_wor->wor_service_state != 6) {
            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;

        // 系统版本：1门店版2运营中心版
        $shop_versions = $user_info->shop_versions;
        if ($request['type'] == 1) { //获取页面数据
            $select_field = "wor_id, wor_number, wor_service_sepr_id, wor_audit_times, wor_service_adm_id, wor_code, wor_create_id, wor_service_type, wor_service_state, wor_state, wor_type, wor_goo_amount, wor_remark, wor_pass, wor_create_time, wocl_channel_unit, wocl_name, wocl_phone, wocl_car_num, wocl_address, ware_name, ware_type, ware_id, wor_shop_id, wor_service_shop_id, wor_collection_price, wocl_collect_state, wocl_province, wocl_city, wocl_county, wor_actual_price, wocl_rescue_service_price, wocl_join_wor_id, wocl_assign_price, wocl_plus_minus, wor_plus_minus, wocl_car_vehicle_type, wocl_rescue_collection_price, wocl_join_ord_id, wocl_wor_type, wor_order_id, wocl_client_id, wocl_sd_virtual_type, wocl_shit_id, wor_order_number";
            $work_order = new WorkOrders();
            $return_data = $work_order->info($user_info, $request->all(), 2, $select_field);
            return response()->json($return_data);
        }
        DB::beginTransaction();

        // 虚拟加盟店另外一个逻辑
        if ($find_wor->wocl_wor_type == 4) {
            // 通过之前判断是否合格，退货、旧货商品是否回收
            $esel_return = $this->virtualUpdatePass(
                $user_info,
                $shop_id,
                $find_wor,
                $request
            );
            return response()->json($esel_return);
        }

        if ($shop_versions == 1) { //系统版本：1门店版
            $shop_upd_res = $this->shopUpdatePass($user_info, $verify_data, $request->all());
            if ($shop_upd_res['code'] == 200) {
                DB::commit();
                Common::addLog($user_info, getRealIp($request), '工单列表', '审核', $find_wor->wor_number . '审核通过成功');
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'通过成功']);
            } else {
                Db::rollBack();
                return response()->json($shop_upd_res);
            }
        }

        if ($request['wor_service_type'] != 4) {
            // 通过之前判断是否合格，退货、旧货商品是否回收
            $esel_return = $this->estimateEligibility(
                $user_info,
                $request['wor_id'],
                $find_wor->wor_service_type,
                $find_wor->wor_is_recycle
            );
            if ($esel_return['code'] === 500) {
                return response()->json($esel_return);
            }
        }

        // 救援单类型，查询服务项目的订单金额
        $sepr_order_money = 0; //服务项目的订单金额
        if ($find_wor->wocl_wor_type == 4) {
            $sepr_order_money = $request['sepr_order_money'] * 100;
        } elseif ($find_wor->wor_service_type == 7) {
            // $sepr_order_money = $find_wor->wocl_rescue_service_price;
            $sepr_order_money = $request['sepr_order_money'] * 100;
        }
        // 查询出工单商品
        $work_good = DB::table('work_good')
            ->where('wogo_state', '<>', 2)
            ->where('wogo_wor_id', $request['wor_id'])
            ->select('wogo_id', 'wogo_goo_id', 'wogo_goo_amount', 'wogo_goo_inventory', 'wogo_goo_price', 'wogo_collection_price', 'wogo_state', 'wogo_recycle_price', 'wogo_recycle_quantity', 'wogo_ware_id', 'wogo_waon_class', 'wogo_assign_price', 'wogo_orgo_id')
            ->get()->toArray();
        $total_price = $sepr_order_money; //总的金额

        $before_price = 0;
        $before_collection_price = 0;
        $total_collection_price = 0;
        $reduce_total_price  = 0; //回收的总金额，工单订单需要减少的金额

        $voucher_sell_total_price  = 0; //销售总额，换货单，用友系统使用
        $voucher_refund_total_price  = 0; //退货总额，换货单，用友系统使用
        $voucher_cost  = 0; //凭证成本，上传用友系统
        $refund_voucher_cost  = 0; //换货单，换回商品成本，凭证成本，上传用友系统
        $total_vouchar_cost = 0;

        if (!empty($work_good)) {
            $voucher_state = false; //默认不生成凭证
            foreach ($work_good as $key => $value) {
                if ($value->wogo_state == 1) { //商品状态1.正常 2.删除3回收的商品4换货商品5赠品商品6备用电池7临时商品8旧货商品
                    // 商品id
                    $goo_id[$key] = $value->wogo_goo_id;
                    // 商品数量
                    $goo_number[$key] = $value->wogo_goo_amount;
                    // 商品价格
                    $goo_price[$key] = $value->wogo_goo_price;
                    // 之前商品总价格
                    $before_price += $value->wogo_goo_price * $value->wogo_goo_amount;
                    // 之前商品代收总价格
                    $before_collection_price += $value->wogo_collection_price;

                    // 销售总额，换货单，用友系统使用
                    $voucher_sell_total_price += $request['goo_price'][$key] * $value->wogo_goo_amount;

                    // 工单商品总价
                    $total_price += $request['goo_price'][$key] * $value->wogo_goo_amount * 100;
                    // 工单商品代收总价
                    $total_collection_price += $request['goo_collection_price'][$key] * 100;
                    // 库存扣除方式1.良品 2.优先
                    $goo_inventory[$key] = $value->wogo_goo_inventory;
                    // 商品id所对应的商品数量
                    $subtract[$value->wogo_goo_id] = $value->wogo_goo_amount;
                    // 商品id所对应的出库方式
                    $goo_repertory[$value->wogo_goo_id] = $value->wogo_goo_inventory;
                } elseif ($value->wogo_state == 4) {
                    $before_price -= $value->wogo_goo_price * $value->wogo_goo_amount;
                    $total_price -= $request['goo_price'][$key] * $value->wogo_goo_amount * 100;
                    // 退货总额，换货单，用友系统使用
                    $voucher_refund_total_price += $request['goo_price'][$key] * $value->wogo_goo_amount;
                } elseif ($value->wogo_state == 6) {
                    // 工单商品总价
                    $total_price += $request['goo_price'][$key] * $value->wogo_goo_amount * 100;
                    // 工单商品代收总价
                    $total_collection_price += $request['goo_collection_price'][$key] * 100;
                }
                $wogo_goo_id_amount[$value->wogo_id] = $value->wogo_goo_amount;

                // 计算凭证成本
                // 商品状态1.正常 2.删除3.回收的商品4.换货商品5.赠品商品6.备用电池7.临时商品8.旧货商品
                if ($value->wogo_waon_class == 1 || ($value->wogo_waon_class == 3 && $value->wogo_goo_price != 0)) { //货物仓
                    $voucher_state = true; //生成凭证
                    if (in_array($value->wogo_state, [1, 5, 8])) {
                        $find_end_price = DB::table('enters_sells_saves')
                            ->where('ense_goo_id', $value->wogo_goo_id)
                            ->where('ense_goo_warehouse', $value->wogo_ware_id)
                            ->where('ense_goo_waretype', $value->wogo_waon_class)
                            ->where('ense_order_number', $find_wor->wor_order_number)
                            ->orderBy('ense_id', 'desc')
                            ->value('ense_end_price');
                        $find_end_price = sprintf('%.2f', $find_end_price);
                        if ($find_end_price) {
                            $voucher_cost += $find_end_price * $value->wogo_goo_amount;
                        } else {
                            $voucher_cost = 0;
                        }
                    }
                }
                if ($value->wogo_state == 4) { //商品状态1.正常 2.删除3回收的商品4换货商品5赠品商品6备用电池7临时商品8旧货商品
                    // 查询当时的商品对应的成本
                    $find_end_price = DB::table('enters_sells_saves')
                        ->where('ense_goo_id', $value->wogo_goo_id)
                        ->where('ense_goo_warehouse', $value->wogo_ware_id)
                        ->where('ense_goo_waretype', $value->wogo_waon_class)
                        ->where('ense_order_number', $find_wor->wor_order_number)
                        ->orderBy('ense_id', 'desc')
                        ->value('ense_end_price');
                    $find_end_price = sprintf('%.2f', $find_end_price);
                    if ($find_end_price) {
                        $refund_voucher_cost += $find_end_price * $value->wogo_goo_amount;
                    } else {
                        $refund_voucher_cost = 0;
                    }
                }
                $total_vouchar_cost = $voucher_cost - $refund_voucher_cost;
            }

            $goo_work_goods = array_column($work_good, null, 'wogo_goo_id');
            // 编辑工单商品表数据
            $sql = 'UPDATE `faster_work_good` SET ';
            $actual_price_sql = '';
            $collection_price_sql = '';
            $update_time_sql = '';
            $ids = '';
            $junk_recycle = [];
            $goo_exchange_price  = [];
            $edit_wogo_id = [];
            if (!is_array($request['wogo_id'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'wogo_id 必传']);
            }
            foreach ($request['wogo_id'] as $key => $value) {
                if (!is_numeric($value) || !is_numeric($request['goo_price'][$key]) || !is_numeric($request['goo_collection_price'][$key])) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品参数类型错误1']);
                }
                if (!in_array($value, $edit_wogo_id)) {
                    if (isset($request['wogo_state'][$key]) && $request['wogo_state'][$key] != 5) {
                        $edit_wogo_data['wogo_goo_price'] = $request['goo_price'][$key] * 100;
                        $edit_wogo_data['wogo_collection_price'] = $request['goo_collection_price'][$key] * 100;
                        $edit_wogo_data['wogo_update_time'] = date('Y-m-d H:i:s');
                        $wogo_res = DB::table('work_good')
                            ->where('wogo_id', $value)
                            ->where('wogo_wor_id', $request['wor_id'])
                            ->update($edit_wogo_data);
                        if (!$wogo_res) {
                            DB::rollBack();
                            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'审核失败1！']);
                        }
                        unset($edit_wogo_data);
                    }
                    // 旧货回收商品价格
                    if (isset($request['wogo_state'][$key]) && $request['wogo_state'][$key] == 3) {
                        //审核输入的回收金额，进销存金额使用
                        $goo_exchange_price[$value] = $request['goo_price'][$key] * 100; //进销存金额
                        $goo_exchange_amount[$value] = $wogo_goo_id_amount[$value]; //进销存数量
                        $junk_recycle[] = $value; //旧货回收商品id
                        $reduce_total_price += $request['goo_price'][$key] * 100 * $wogo_goo_id_amount[$value];
                    } elseif (isset($request['wogo_state'][$key]) && $request['wogo_state'][$key] == 8) {
                        $goo_exchange_price[$value] = $request['goo_price'][$key] * 100; //进销存金额
                        $goo_exchange_amount[$value] = $wogo_goo_id_amount[$value]; //进销存数量
                        $junk_recycle[] = $value; //旧货回收商品id
                        $reduce_total_price -= $request['goo_price'][$key] * 100 * $wogo_goo_id_amount[$value];
                    } else {
                        // $reduce_total_price += $goo_work_goods[$value]->wogo_recycle_price * $goo_work_goods[$value]->wogo_recycle_quantity;
                        // $reduce_total_price += $request['goo_price'][$key] * 100 * $goo_work_goods[$value]->wogo_recycle_quantity;
                    }
                    $edit_wogo_id[] = $value;
                }
            }
            $wogo_res = true;
        } else {
            $voucher_state = true; //没有商品的救援单需要生成凭证
            $wogo_res = true;
        }
        // 如果是外派工单并且是派单方审核
        if ($find_wor->wocl_wor_type == 2 && $find_wor->wocl_join_wor_id == 0) {
            $wor_data['wor_service_state'] = 8; //完成通过
            $request->offsetSet('wor_actual_price', $find_wor->wor_actual_price / 100);
        } elseif ($find_wor->wocl_wor_type == 1) {
            $wor_data['wor_service_state'] = 8; //完成通过
        } elseif ($find_wor->wocl_wor_type == 5) {//门店派单
            $wor_data['wor_service_state'] = 8; //完成通过
        }
        $virtual_goo_price = 0; //虚拟加盟店订单金额
        // 编辑订单商品表数据
        if (!empty($work_good) && $find_wor->wocl_wor_type == 1) {
            $sql = 'UPDATE `faster_order_goods` SET ';
            $actual_price_sql = '';
            $collection_price_sql = '';
            $update_time_sql = '';
            $ids = '';
            $edit_wogo_id = [];
            if (!is_array($request['wogo_orgo_id'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'wogo_orgo_id 必传']);
            }
            foreach ($request['wogo_orgo_id'] as $key => $value) {
                if (!is_numeric($value) || !is_numeric($request['goo_price'][$key]) || !is_numeric($request['goo_collection_price'][$key])) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品参数类型错误']);
                }
                if (!in_array($value, $edit_wogo_id)) {
                    if (isset($request['wogo_state'][$key]) && $request['wogo_state'][$key] != 5) {
                        $edit_wogo_data['orgo_goo_price'] = $request['goo_price'][$key] * 100;
                        $edit_wogo_data['orgo_collection_price'] = $request['goo_collection_price'][$key] * 100;
                        $edit_wogo_data['orgo_update_time'] = date('Y-m-d H:i:s');
                        $orgo_res = DB::table('order_goods')
                            ->where('orgo_id', $value)
                            ->where('orgo_ord_id', $find_wor->wor_order_id)
                            ->update($edit_wogo_data);
                        if (!$orgo_res) {
                            DB::rollBack();
                            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'审核失败2！']);
                        }
                        unset($edit_wogo_data);
                    } else {
                        $orgo_res = true;
                    }
                    $edit_wogo_id[] = $value;
                }
            }
        } elseif (!empty($work_good) && $find_wor->wocl_wor_type == 4) {
            $sql = 'UPDATE `faster_order_goods` SET ';
            $actual_price_sql = '';
            $collection_price_sql = '';
            $update_time_sql = '';
            $ids = '';
            $junk_goo_price = 0;
            $old_junk_goo_price = 0;
            if (!is_array($request['wogo_orgo_id'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'wogo_orgo_id 必传']);
            }
            foreach ($request['wogo_orgo_id'] as $key => $value) {
                if (!is_numeric($value) || !is_numeric($request['orgo_goo_price'][$key]) || !is_numeric($request['goo_collection_price'][$key])) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品参数类型错误']);
                }

                // 更改商品价格
                $actual_price_sql = $actual_price_sql . ' WHEN ' . $value;
                $actual_price_sql = $actual_price_sql . ' THEN ' . $request['orgo_goo_price'][$key] * 100;

                // 更改商品代收价格
                $collection_price_sql = $collection_price_sql . ' WHEN ' . $value;
                $collection_price_sql = $collection_price_sql . ' THEN ' . $request['goo_collection_price'][$key] * 100;

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

                if ($request['wogo_state'][$key] != 3) {
                    $virtual_goo_price += $request['orgo_goo_price'][$key] * 100 * $wogo_goo_id_amount[$request['wogo_id'][$key]];
                } else {
                    $virtual_goo_price -= $request['orgo_goo_price'][$key] * 100 * $wogo_goo_id_amount[$request['wogo_id'][$key]];
                    // 计算原来的旧货金额
                    $old_junk_goo_price += $request['orgo_goo_price'][$key] * 100 * $wogo_goo_id_amount[$request['wogo_id'][$key]];
                }
            }
            $sql = $sql . ' `orgo_goo_price` = CASE `orgo_id`' . $actual_price_sql . ' END,'; //商品售价
            $sql = $sql . ' `orgo_collection_price` = CASE `orgo_id`' . $collection_price_sql . ' END,'; //商品代收金额
            $sql = $sql . ' `orgo_update_time`=  CASE `orgo_id` ' . $update_time_sql . ' END';
            $sql = $sql . ' WHERE `orgo_ord_id` = ' . $find_wor->wor_order_id . ' AND `orgo_id` IN (' . trim($ids, ',') . ')';
            $orgo_res = DB::update($sql);
            $virtual_goo_price += $sepr_order_money;

            if (!empty($request['virtual_goo_id'])) {
                foreach ($request['virtual_goo_id'] as $key => $value) {
                    $junk_goo_price += $request['virtual_goo_price'][$key] * 100 * $request['virtual_goo_quantity'][$key];
                    $goods_data = DB::table('goods')
                        ->where('goo_id', $value)
                        ->first(['goo_name', 'goo_goods_encode', 'goo_class']);
                    if ($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)) {
                            $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)) {
                            $goods_data->goo_name = $gosa_another_name;
                        }
                    }

                    $virtual_wor[$key]['wogo_wor_id'] = $request['wor_id'];
                    $virtual_wor[$key]['wogo_goo_id'] = $value;
                    $virtual_wor[$key]['wogo_waon_class'] = 3;
                    $virtual_wor[$key]['wogo_is_recycle'] = 2;
                    $virtual_wor[$key]['wogo_goo_name'] = $goods_data->goo_name;
                    $virtual_wor[$key]['wogo_goo_goods_encode'] = $goods_data->goo_goods_encode;
                    $virtual_wor[$key]['wogo_goo_type'] = 4;
                    $virtual_wor[$key]['wogo_state'] = 3;
                    $virtual_wor[$key]['wogo_goo_price'] = $request['virtual_goo_price'][$key] * 100;
                    $virtual_wor[$key]['wogo_goo_amount'] = $request['virtual_goo_quantity'][$key];
                    $virtual_wor[$key]['wogo_recycle_quantity'] = $request['virtual_goo_quantity'][$key];
                    $virtual_wor[$key]['wogo_actual_recycle_number'] = $request['virtual_goo_quantity'][$key];

                    $virtual_order[$key]['orgo_ord_id'] = $find_wor->wor_order_id;
                    $virtual_order[$key]['orgo_order_number'] = $find_wor->wor_order_number;
                    $virtual_order[$key]['orgo_waon_class'] = 3;
                    $virtual_order[$key]['orgo_goo_id'] = $value;
                    $virtual_order[$key]['orgo_goo_name'] = $goods_data->goo_name;
                    $virtual_order[$key]['orgo_goo_goods_encode'] = $goods_data->goo_goods_encode;
                    $virtual_order[$key]['orgo_goo_type'] = 4;
                    $virtual_order[$key]['orgo_goo_inventory'] = 1;
                    $virtual_order[$key]['orgo_is_recycle'] = 2;
                    $virtual_order[$key]['orgo_state'] = 3;
                    $virtual_order[$key]['orgo_goo_price'] = $request['virtual_goo_price'][$key] * 100;
                    $virtual_order[$key]['orgo_goo_quantity'] = $request['virtual_goo_quantity'][$key];
                    $virtual_order[$key]['orgo_recycle_quantity'] = $request['virtual_goo_quantity'][$key];
                }
                DB::table('order_goods')->insert($virtual_order);
                DB::table('work_good')->insert($virtual_wor);
            }
        } else {
            $orgo_res = true;
        }

        // 查询订单商品是否全部派完
        $find_orgo_id = DB::table('order_goods')
            ->where('orgo_ord_id', $find_wor->wor_order_id)
            ->where('orgo_can_assign_quantity', '>', 0)
            ->value('orgo_id');
        if ($find_orgo_id) {
            $ord_wor_state = '';
        } else {
            // 没有可以派单的商品了，订单状态改为完成状态
            $ord_edit_data['ord_wor_state'] = 4; //订单的工单状态1未派工单2服务中3售后中4已完成
            $ord_wor_state = ', ord_wor_state = 4 '; //订单的工单状态1未派工单2服务中3售后中4已完成
        }

        $jur_price = 0;
        // 修改旧货回收价格
        if (!empty($junk_recycle)) {
            $jur_amount =  DB::table('work_good')
                ->where('wogo_wor_id', $request['wor_id'])
                ->where('wogo_state', 3)
                ->whereIn('wogo_id', $junk_recycle)
                ->get(['wogo_actual_recycle_number', 'wogo_goo_id', 'wogo_ware_id', 'wogo_id', 'wogo_orgo_id']);
            $jur_id =  DB::table('junk_recycle')
                ->where('jur_wor_id', $request['wor_id'])
                ->value('jur_id');
            foreach ($jur_amount as $key => $value) {
                $jur_price  += $goo_exchange_price[$value->wogo_id] * $value->wogo_actual_recycle_number;
                $junk_goods_update = DB::table('junk_goods')
                    ->where('jugo_jur_id', $jur_id)
                    ->where('jugo_wogo_id', $value->wogo_id)
                    ->update(['jugo_goo_price' => $goo_exchange_price[$value->wogo_id], 'jugo_update_time' => date('Y-m-d H:i:s')]);
                if ($junk_goods_update || $junk_goods_update === 0) {
                } else {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'通过失败']);
                }
                // 更新返回影响行数为0的问题，可能是并发的问题，参考下面的文章，暂时先用这种方式解决
                // https://blog.csdn.net/weixin_41750790/article/details/85335206
                $res2 = DB::table('work_good')
                    ->where('wogo_wor_id', $find_wor->wor_id)
                    ->where('wogo_id', $value->wogo_id)
                    ->update(['wogo_goo_price' => $goo_exchange_price[$value->wogo_id], 'wogo_update_time' => date('Y-m-d H:i:s')]);

                if ($res2 || $res2 === 0) {
                } else {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'通过失败']);
                }

                $res3 = DB::table('order_goods')
                    ->where('orgo_ord_id', $find_wor->wor_order_id)
                    ->where('orgo_id', $value->wogo_orgo_id)
                    ->update(['orgo_goo_price' => $goo_exchange_price[$value->wogo_id], 'orgo_update_time' => date('Y-m-d H:i:s')]);

                if ($res3 || $res3 === 0) {
                } else {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'通过失败']);
                }
                $goo_state_update = true;
            }
            // 判断是否有该工单
            $jur_wor_id =  DB::table('junk_recycle')
                ->where('jur_wor_id', $request['wor_id'])
                ->value('jur_wor_id');
            if ($jur_wor_id) {
                $jur_price_res =  DB::table('junk_recycle')
                    ->where('jur_wor_id', $request['wor_id'])
                    ->update(['jur_price' => $jur_price, 'jur_check_state' => 2, 'jur_update_time' => date('Y-m-d H:i:s')]);
            } else {
                $jur_price_res = true;
            }
        } else {
            $jur_price_res = true;
            $goo_state_update = true;
            $ord_res = true;
        }

        // 获取到当前工单的订单信息
        $ord_info = DB::table('order')
            ->where('ord_id', $find_wor->wor_order_id)
            ->first(['ord_type', 'ord_client_id', 'ord_state', 'ord_remark', 'ord_actual_price', 'ord_payment_way', 'ord_order_price', 'ord_collection_price', 'ord_plus_minus', 'ord_other_system_number', 'ord_service_type', 'ord_create_time']);

        // 计算订单总的金额，订单中已经有了服务项目金额所以计算的时候要减去
        $total_price = $total_price - $sepr_order_money;
        // 现在的代收价格减去之前代收价格
        $diff_collection_price = $total_collection_price - $before_collection_price;
        // 计算新的订单代收总金额
        // $new_collection_price = $ord_info->ord_collection_price + $diff_collection_price;
        $new_collection_price = $request['wocl_rescue_collection_price'] * 100 + $total_collection_price;
        //现在的价格减去之前价格 减去回收价格
        if ($ord_info->ord_state == 2) {
            // 订单已经结算，订单的金额不再减去回收的金额
            $diff_price = $total_price - $before_price;
        } else {
            $diff_price = $total_price - $before_price - $reduce_total_price;
        }
        // 计算新的订单结算总金额
        if ($ord_info->ord_plus_minus == 1) {
            // 新的结算总金额 = 订单原来的结算金额 + 现在的金额
            $new_actual_price = $ord_info->ord_actual_price + $diff_price;
        } else {
            $new_actual_price = $diff_price - $ord_info->ord_actual_price;
        }
        // 新的订单金额正负值
        if ($new_actual_price >= 0 && $request['wor_service_type'] != 4) {
            $ord_plus_minus = 1;
        } else {
            $ord_plus_minus = 2;
        }

        // 查询订单客户信息表
        $cli_info = DB::table('order_client')
            ->where('orcl_ord_id', $find_wor->wor_order_id)
            ->first(['orcl_acc_subject_id', 'orcl_channel_unit', 'orcl_name', 'orcl_collect_state']);

        // 应收账款显示客户名称
        $wocl_client_name = $find_wor->wocl_channel_unit ? $find_wor->wocl_channel_unit : $find_wor->wocl_name;
        if ($find_wor->wor_type == 5 && $shop_versions == 1) {
            $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
            $parent_shop_id = DB::table('shop')
                ->where('shop_id', $shop_id)
                ->value('shop_parent_id');
            $wocl_client_name = DB::table('shop')
                ->where('shop_id', $parent_shop_id)
                ->value('shop_store_name');
        }

        $goo_info = collect(DB::table('order_goods')
            ->where('orgo_ord_id', $find_wor->wor_order_id)
            ->get(['orgo_goo_id', 'orgo_goo_price', 'orgo_collection_price']))
            ->keyBy('orgo_goo_id')
            ->toArray();
        // 服务名称
        if ($find_wor->wocl_wor_type == 4) {
            $shop_info = DB::table('virtual_shop')
                ->where('vish_id', $find_wor->wor_service_shop_id)
                ->first(['vish_store_name as shop_store_name']);
            $shop_info->shop_type = 4;
        } else {
            $shop_info = DB::table('shop')
                ->where('shop_id', $find_wor->wor_service_shop_id)
                ->first(['shop_store_name', 'shop_type']);
        }
        // 如果订单类型是退货单金额为负数，金额类型为负数的
        $plus_minus = 1;
        if ($request['wor_service_type'] == 4 || $find_wor->wor_plus_minus == 2) {
            $plus_minus = 2;
        }

        // 计算应收账款的金额，前面计算订单金额时减去了，计算应收账款时在加回来
        // $total_price = $total_price + $sepr_order_money;
        $now_order_total_price = $total_price + $sepr_order_money; //订单总金额
        $total_price = $total_price + $sepr_order_money - $reduce_total_price; //结算金额
        // 应收账款的金额 现在的价格 减去回收价格
        // 根据工单金额的正负判断
        if (empty($work_good)) {
            $now_wor_price = $total_price;
            $now_order_price = $now_order_total_price;
        } else {
            $now_wor_price = $total_price;
            $now_order_price = $now_order_total_price;
        }

        $image_change_state = 1; //工单审核图片更改状态：1未上传新图2重新传图
        $old_img_delete = []; //原来的被替换的图片需要删除
        $new_img_delete = []; //新上传的图片，提交失败时删除
        // 如果是虚拟加盟店
        if ($find_wor->wocl_wor_type == 4) {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'虚拟加盟店审核失败']);
        } else {
            // 不是虚拟加盟店的上传图片处理
            if (!empty($request['imgs64'])) {
                // 根据图片上传模板判断上传图片
                $find_image_template = DB::table('shop_image_template')
                    ->where('shit_id', $find_wor->wocl_shit_id)
                    ->value('shit_template_set');
                $find_image_template = json_decode($find_image_template, true);
                $upload_file = json_decode(json_encode($request['imgs64']), true);
                // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
                $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
                $imup_data = [];
                foreach ($find_image_template as $key => $value) {
                    // 判断必传图片是否上传 must_state 为1是门店设置的必传图片
                    if ($value['must_state'] == 1 && empty($upload_file[$key])) {
                        DB::rollBack();
                        return response()->json(['code'=>500, 'data'=>'请上传 ' . $value['show_word'] . ' 图片', 'msg'=>'error']);
                    }
                }
                $new_key = 0;
                foreach ($upload_file as $key => $value) {
                    if (!empty($value)) {
                        // 判断是否有新图片上传
                        if (strpos($value, 'data:image') === 0) {
                            // 有新图片上传，将原来的图片改为删除状态
                            $imup_edit['imup_delete'] = 2;
                            $imup_edit['imup_update_time'] = date('Y-m-d H:i:s');
                            $edit_res = DB::table('image_upload')
                                ->where('imup_wor_id', $request['wor_id'])
                                ->where('imup_delete', 1)
                                ->where('imup_image_name', $find_image_template[$key]['show_word'])
                                ->update($imup_edit);
                            if ($find_wor->wocl_wor_type == 5) {
                                DB::rollBack();
                                return response()->json(['code'=>500, 'data'=>'请不要更改图片', 'msg'=>'error']);
                            }
                            unset($imup_edit);
                            if (!$edit_res) {
                                DB::rollBack();
                                return response()->json(['code'=>500, 'data'=>'图片上传失败001', 'msg'=>'error']);
                            }
                            // 调用全局函数 上传图片
                            $image_path = uploadBase64ImgFolder($shop_id, $value, 2);
                            $imup_data[$new_key]['imup_path'] = $image_path;
                            $imup_data[$new_key]['imup_cid'] = $user_info->adm_cid;
                            $imup_data[$new_key]['imup_shop_id'] = $user_info->adm_shop_id;
                            $imup_data[$new_key]['imup_superior_shop_id'] = $shop_id;
                            $imup_data[$new_key]['imup_ord_id'] = $find_wor->wor_order_id;
                            $imup_data[$new_key]['imup_wor_id'] = $request['wor_id'];
                            $imup_data[$new_key]['imup_image_name'] = $find_image_template[$key]['show_word'];
                            $new_key++;
                            $new_img_delete[] = $image_path; //新上传的图片路径
                        }
                    }
                }
                if ($imup_data) {
                    $imup_res = DB::table('image_upload')->insert($imup_data);
                    if (!$imup_res) {
                        DB::rollBack();
                        return response()->json(['code'=>500, 'data'=>'图片上传失败', 'msg'=>'error']);
                    }
                }
            }
        }
        $party = $find_wor->wocl_wor_type;

        // 应收账款的金额正负值
        if ($now_wor_price > 0) {
            // 如果是退货单不一定是负数  虚拟加盟店  加盟店
            if ($request['wor_service_type'] == 4) {
                $wor_plus_minus = $party == 2 || $party == 4 ? 1 : 2;
            } else {
                $wor_plus_minus = $party == 2 || $party == 4 ? 2 : 1;
            }
        } else {
            if ($request['wor_service_type'] == 4) {
                $wor_plus_minus = $party == 2 || $party == 4 ? 2 : 1;
            } else {
                $wor_plus_minus = $party == 2 || $party == 4 ? 1 : 2;
            }
        }
        // 更改工单信息
        $wor_data['wor_actual_price'] = $now_wor_price; //工单结算金额(单位:分)
        $wor_data['wor_collection_price'] = $new_collection_price;
        $wor_data['wor_service_type'] = $request['wor_service_type'];   //服务类型
        $wor_data['wor_service_sepr_id'] = $request['wor_service_sepr_id'];   //服务项目
        if ($find_wor->wocl_wor_type == 3) {
            $wor_data['wor_pass'] = 11;  //审核状态1.待审核 2.合格 3.不合格 11.等待速电审核
        } elseif ($find_wor->wocl_wor_type == 5 && $shop_versions == 1) {
            $wor_data['wor_pass'] = 12;  //审核状态1.待审核 2.合格 3.不合格 12.等待城市运营中心审核
        } else {
            $wor_data['wor_pass'] = 2;
        }

        $wor_data['wor_state'] = 10;    //状态1.新订单 2未派单 3待接单/已派单 4.未出发/已接单 5.预约/已预约 6.出发/已出发  7.抵达/抵达 8.待审核/完成待审核 9驳回/完成已驳回 10完成/完成已通过 11终止
        $wor_data['wor_remark'] = $request['remark'] ? $request['remark'] : ''; //工单备注
        $wor_data['wor_plus_minus'] = $wor_plus_minus; //金额正负：1正值2负值
        $wor_data['wor_recycle_price'] = $reduce_total_price; //回收金额
        $wor_data['wor_update_time'] = date('Y-m-d H:i:s');
        $wor_res = DB::table('work_order')
            ->where('wor_id', $request['wor_id'])
            ->update($wor_data);
        if ($find_wor->wocl_wor_type == 5 && $shop_versions != 1) {
            $shop_update['wor_pass'] = 2;
            $shop_update_res = DB::table('work_order')
                ->where('wor_order_id', $find_wor->wocl_join_ord_id)
                ->update($shop_update);
        }
        // 工单客户信息
        $wocl_data['wocl_name'] = $request['wocl_name'];    //姓名
        $wocl_data['wocl_phone'] = $request['wocl_phone'];    //联系电话
        $wocl_data['wocl_car_num'] = $request['wocl_car_num'];  //车牌号
        $wocl_data['wocl_car_vehicle_type'] = $request['wocl_car_vehicle_type'];
        $wocl_data['wocl_province'] = $request['wocl_province'] ? $request['wocl_province'] : '';  //省
        $wocl_data['wocl_city'] = $request['wocl_city'] ? $request['wocl_city'] : '';  //市
        $wocl_data['wocl_county'] = $request['wocl_county'] ? $request['wocl_county'] : '';  //县
        $wocl_data['wocl_address'] = $request['wocl_address'];  //地址
        $wocl_data['wocl_rescue_collection_price'] = $request['wocl_rescue_collection_price'] * 100;  //代收金额
        $wocl_data['wocl_update_time'] = date('Y-m-d H:i:s');  //时间
        $wocl_data['wocl_join_audit_adm_id'] = $user_info->adm_id;
        $wocl_data['wocl_rescue_service_price'] = $request['sepr_order_money'] * 100;
        // 修改工单客户表数据
        $wocl_id = DB::table('work_client')
            ->where('wocl_wor_id', $find_wor->wor_id)
            ->update($wocl_data);
        $wocl_rescue_collection_price = $request['wocl_rescue_collection_price'] * 100;
        $orcl_rescue_service_price = $request['sepr_order_money'] * 100;
        // 修改订单客户表数据
        DB::table('order_client')
            ->where('orcl_ord_id', $find_wor->wor_order_id)
            ->update(['orcl_rescue_collection_price' => $wocl_rescue_collection_price, 'orcl_rescue_service_price' => $orcl_rescue_service_price]);
        // 1不是总店审核的外派   2是
        $genre = 1;
        // 如果是总店审核不修改总店的订单价格
        if ($find_wor->wocl_wor_type == 2 && $find_wor->wocl_join_wor_id == 0) {
            // 查询订单商品是否全部派完
            $find_orgo_id = DB::table('order_goods')
                ->where('orgo_ord_id', $find_wor->wocl_join_ord_id)
                ->where('orgo_can_assign_quantity', '>', 0)
                ->value('orgo_id');
            if ($find_orgo_id) {
                $ord_wor_state = '';
            } else {
                // 没有可以派单的商品了，订单状态改为完成状态
                $ord_edit_data['ord_wor_state'] = 4; //订单的工单状态1未派工单2服务中3售后中4已完成
                $ord_wor_state = ', ord_wor_state = 4 '; //订单的工单状态1未派工单2服务中3售后中4已完成
            }
            $ord_edit_data['ord_update_time'] = date('Y-m-d H:i:s');
            $ord_res = DB::table('order')
                ->where('ord_id', $find_wor->wor_order_id)
                ->update($ord_edit_data);
            $join_ord_res = DB::table('order')
                ->where('ord_id', $find_wor->wocl_join_ord_id)
                ->update($ord_edit_data);
            $genre = 2;
            $wor_update['wor_update_time'] = date('Y-m-d H:i:s');
            $wor_update['wor_service_state'] = 8;

            $join_wor_id = DB::table('work_order')
                ->where('wor_order_id', $find_wor->wocl_join_ord_id)
                ->value('wor_id');
            // 修改加盟店审核状态
            $join_in_wor = DB::table('work_order')
                ->where('wor_id', $join_wor_id)
                ->update($wor_update);
            // 生成操作记录
            $edit_record = orderLog($user_info, 0, $join_wor_id, '总店审核通过工单');
        } elseif ($find_wor->wocl_wor_type == 1) { //1系统工单 2外派工单 3速电派单
            // 更新订单表数据
            $ord_edit_data['ord_actual_price'] = $now_wor_price; //结算金额
            $ord_edit_data['ord_order_price'] = $now_order_price; //订单金额
            $ord_edit_data['ord_collection_price'] = $new_collection_price;
            $ord_edit_data['ord_plus_minus'] = $wor_plus_minus;
            $ord_edit_data['ord_order_plus_minus'] = $wor_plus_minus;
            $ord_edit_data['ord_update_time'] = date('Y-m-d H:i:s');
            $ord_res = DB::table('order')
                ->where('ord_id', $find_wor->wor_order_id)
                ->update($ord_edit_data);
            $join_in_wor = true;
        } else {
            // 如果是外派工单
            if ($find_wor->wocl_wor_type == 2 && isset($ord_edit_data['ord_wor_state'])) {
                unset($ord_edit_data['ord_wor_state']);
            }
            if ($find_wor->wocl_wor_type != 4 && $find_wor->wocl_wor_type != 5) {
                // 更新订单表数据
                $ord_edit_data['ord_actual_price'] = $now_wor_price;
                $ord_edit_data['ord_order_price'] = $now_order_price;
                $ord_edit_data['ord_plus_minus'] = $wor_plus_minus;
            } elseif ($find_wor->wocl_wor_type == 4) {
                $ord_actual_price = $virtual_goo_price - $junk_goo_price;
                $ord_info->ord_actual_price = $ord_actual_price;
                $virtual_ord_plus_minus = 1;
                if ($ord_actual_price < 0) {
                    $virtual_ord_plus_minus = 2;
                }
                $ord_plus_minus = $virtual_ord_plus_minus;
                // 订单金额应该是不减回收的金额
                $virtual_goo_price = $old_junk_goo_price + $virtual_goo_price;
                $ord_edit_data['ord_actual_price'] = $ord_actual_price; //减回收金额
                $ord_edit_data['ord_order_price'] = $virtual_goo_price;     //不减回收金额
                $ord_edit_data['ord_plus_minus'] = $virtual_ord_plus_minus; //新正负值
            }
            $ord_edit_data['ord_collection_price'] = $new_collection_price;
            $ord_edit_data['ord_update_time'] = date('Y-m-d H:i:s');
            $ord_res = DB::table('order')
                ->where('ord_id', $find_wor->wor_order_id)
                ->update($ord_edit_data);

            $join_in_wor = true;
        }
        // ord_payment_way 结算方式1.账期 2.现结 3微信 4支付宝
        // 计算出 工单代收金额/应收金额
        $wor_coll_price = 0;
        $wor_price = 0;
        if (!empty($work_good)) {
            // 查询出工单商品
            $work_good = DB::table('work_good')
                ->where('wogo_state', 1)
                ->where('wogo_wor_id', $request['wor_id'])
                ->select('wogo_goo_id', 'wogo_goo_amount', 'wogo_goo_inventory', 'wogo_goo_price', 'wogo_collection_price')
                ->get()
                ->toArray();
            foreach ($work_good as $key => $value) {
                $wor_coll_price += $value->wogo_collection_price; //代收金额
            }
        }
        $wor_coll_price = $request['wocl_rescue_collection_price'] * 100 + $wor_coll_price;

        if ($find_wor->wocl_wor_type == 2 && $find_wor->wocl_join_wor_id != 0) { //如果是外派工单  加盟店审核
            unset($wor_data['wor_pass']);
            unset($wor_data['wor_state']);
            $join_wor_res = true;
            $wocl_data['wocl_join_audit'] = 2;  // 1未审核 2已审核
            $join_wocl_id = DB::table('work_client')
                ->where('wocl_wor_id', $find_wor->wocl_join_wor_id)
                ->update($wocl_data);

            $join_order_id = DB::table('work_order')
                ->where('wor_id', $find_wor->wocl_join_wor_id)
                ->value('wor_order_id');

            // 生成操作记录
            $edit_record = orderLog($user_info, 0, $request['wor_id'], '审核通过工单');
            if ($wor_res && $ord_res && $wogo_res && $wocl_id && $edit_record  && $orgo_res && $jur_price_res && $goo_state_update && $join_wocl_id && $join_wor_res && $join_in_wor) {
                DB::commit();
                Common::addLog($user_info, getRealIp($request), '工单列表', '通过', $find_wor->wor_number . '通过成功');
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'通过成功']);
            } else {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'通过失败']);
            }
        } elseif ($find_wor->wocl_wor_type == 3) { //3速电派单
            if ($image_change_state == 2) {
                $log_hint = '改图审核通过工单';
            } else {
                $log_hint = '审核通过工单';
            }
            // 生成操作记录
            $edit_record = orderLog($user_info, 0, $request['wor_id'], $log_hint);
            if ($wor_res && $ord_res && $wogo_res && $wocl_id && $edit_record  && $orgo_res && $jur_price_res && $goo_state_update && $join_in_wor) {
                Common::addLog($user_info, getRealIp($request), '工单列表', '通过', $find_wor->wor_number . '通过成功');
                if (config('apisystem.SYNC_STATE')) {
                    //如果是速电派单
                    if ($ord_info->ord_type == 3) {
                        $lat = DB::table('lat')
                            ->where('lat_aid', $find_wor->wor_service_adm_id)
                            ->first(['lat_lat', 'lat_lon']);
                        // 查询工单的技师完成时间
                        $orlo_time = DB::table('order_log')
                            ->where('orlo_shop_id', $user_info->adm_shop_id)
                            ->where('orlo_wor_id', $request['wor_id'])
                            ->where('orlo_content', '完成')
                            ->value('orlo_time');

                        $adm_data = DB::table('admin')
                            ->where('adm_id', $find_wor->wor_service_adm_id)
                            ->first(['adm_name', 'adm_phone']);
                        $param['serial_number'] = $ord_info->ord_other_system_number;
                        $param['state'] = 5;
                        $param['ip'] = $param['ip'] = getRealIp($request);
                        $param['line'] = $lat->lat_lat . ',' . $lat->lat_lon;
                        $param['install_name'] = $adm_data->adm_name;
                        $param['install_phone'] = $adm_data->adm_phone;
                        $param['app_achieve_time'] = $orlo_time; //APP完成提交时间
                        $param['time'] = date('Y-m-d H:i:s');
                        $server = config('apisystem.server_name') . '/';
                        $find_image_upload = DB::table('image_upload')
                            ->where('imup_wor_id', $request['wor_id'])
                            ->where('imup_delete', 1)
                            ->select('imup_path', 'imup_image_name')
                            ->get()->toArray();
                        $find_image_upload = json_decode(json_encode($find_image_upload), true);
                        foreach ($find_image_upload as $key => $value) {
                            if ($value['imup_path']) {
                                $find_image_upload[$key]['imup_path'] = $server . $value['imup_path'];
                            }
                        }
                        $param['filePic'] = $find_image_upload; //速电模板图片
                        $param['image_change_state'] = $image_change_state; //工单审核图片更改状态：1未上传新图2重新传图
                        $param['token'] = config('apisystem.sd_token');
                        $url = config('apisystem.sd_server_name') . '/index.php/Supply/installLine';
                        $doPost_res = Common::doPost($param, $url);
                        $doPost_res = json_decode($doPost_res);
                        if ($doPost_res->code != 200) {
                            deleteImage($new_img_delete);
                            DB::rollBack();
                            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'失败']);
                        }
                        if ($voucher_state == true) {
                            // 上传数据到凭证列表
                            if (config('apiu8cloud.CODE_STARTS') && in_array($user_info->adm_shop_id, config('apiu8cloud.u8cloud_shop'))) {
                                // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
                                $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
                                // 生成凭证单据
                                $vore_data = WorkOrder::voucherReceipts($user_info, $shop_id, 2, $request['wor_id'], $find_wor->wor_number, $find_wor->wor_order_id, $find_wor->wor_order_number, $now_wor_price, $find_wor->wor_recycle_price, $find_wor->wor_collection_price, $total_vouchar_cost, $find_wor->wor_service_type, $find_wor->wor_type, $find_wor->wocl_client_id, $wocl_client_name);
                                if (!$vore_data) {
                                    deleteImage($new_img_delete);
                                    DB::rollBack();
                                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'生成凭证单失败']);
                                }
                            }
                        }
                    }
                }
                DB::commit();
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'通过成功']);
            } else {
                deleteImage($new_img_delete);
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'通过失败']);
            }
            // 如果是外派工单  总店审核
        } elseif ($find_wor->wocl_wor_type == 2 && $find_wor->wocl_join_wor_id == 0) {
            // 救援单没有商品的情况，这变量就不存在
            if (!isset($subtract)) {
                $subtract = [];
            }
            // 加盟店应收账款
            $join_rece_res = WorkOrder::joinReceivable($request->all(), $user_info, $find_wor, $wor_coll_price, $find_wor->wocl_assign_price, $subtract, $goo_info, $wor_plus_minus);
            // 记录日志
            $log_data['ord_bill'] = $join_rece_res;
            $log_data['user_info'] = $user_info;
            $log_data['request'] = $request->all();
            $log_data['find_wor'] = $find_wor;
            $log_data['find_wor'] = $find_wor;
            $log_data['wor_plus_minus'] = $wor_plus_minus;
            Common::write_record_log($log_data, 'work_order_log.txt', 'updatePass-joinReceivable');
            unset($log_data);
            $join_wor_res = true;
            $join_wocl_id = true;
        } elseif ($find_wor->wocl_wor_type == 5 && $shop_versions == 1) { //门店版城市运营中心派单 门店审核
            // 工单修改为完成状态
            $update_parwor['wor_update_time'] = date('Y-m-d H:i:s');
            $update_parwor['wor_service_state'] = 6; //修改服务状态为已完成待审核
            $update_parwor['wor_state'] = 8; //修改状态为已完成
            $update_parwor['wor_pass'] = 1; //改为待审核状态
            $sel_paretworid = DB::table('work_client')
                ->where('wocl_join_ord_id', $find_wor->wor_order_id)
                ->value('wocl_wor_id');
            $wocl_data['wocl_join_audit'] = 2;  // 1未审核 2已审核
            if ($sel_paretworid) {
                $join_wocl_id = DB::table('work_client')
                    ->where('wocl_wor_id', $sel_paretworid)
                    ->update($wocl_data);
                $save_state = DB::table('work_order')
                    ->where('wor_id', $sel_paretworid)
                    ->update($update_parwor);
            }
            $join_wor_res = true;
            $join_rece_res = true;
        } else {
            $join_wor_res = true;
            $join_wocl_id = true;
            $join_rece_res = true;
        }
        // wocl_collect_state技师代收1是2否  代收金额为0   结算方式为现结
        if ($find_wor->wocl_collect_state == 1 && $find_wor->wor_collection_price == 0 && $ord_info->ord_payment_way == 2) {
            // 生成结款明细
            $acset_id = AccountingSettlement::add(
                $user_info, // [用户信息]
                1, // [单据类型1订单结算2订单账单3工单账单11订单退款12工单代收]
                $find_wor->wor_order_id, // [与单据类型对应的id]
                $find_wor->wor_order_number, // [与单据类型对应的单号]
                $ord_info->ord_type, // [买家类型1门店零售2来往单位]
                $find_wor->wocl_client_id, // [会员/客户id]
                $wocl_client_name, // [来往单位名称]
                $find_wor->wocl_acti_id, // [会计科目id]
                1, // [类型1收入2支出]
                $total_price, // [实际金额](此次的实收金额)
                $total_price, // [合计金额](此次的应收金额)
                0, // [欠收金额](此次结款后还应收金额)
                0, // [抹零金额]
                $request['remark'] ? $request['remark'] : '' //[备注]
            );

            // 3.订单应收
            $ord_bill = ReceivableBill::create(
                $user_info, //用户信息
                1, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $find_wor->wor_order_id, //原始id(订单id)
                $find_wor->wor_order_number, //应收账款单号/原始号(订单编号)
                $ord_info->ord_type, //客户类型：1.门店零售 2.来往单位
                $ord_info->ord_client_id, //会员id/来往单位id
                $wocl_client_name, //来往单位名称
                $genre == 1 ? $total_price : $ord_info->ord_actual_price, //结算金额(应收金额)
                '', //结款时间
                $cli_info->orcl_acc_subject_id, //会计科目id
                $ord_info->ord_state == 1 ? 0 : $total_price, //实际金额(应收金额)
                0, //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                $ord_info->ord_remark,  //备注
                $ord_info->ord_state == 1 ? 0 : $total_price,  //已收金额
                '', //截止时间
                $wor_plus_minus, //金额正负1正   2负值
                1, //显示类型：1订单收款
                1, //是否合并代收：1是2否
                $ord_info->ord_create_time
            );
            // 记录日志
            $log_data['ord_bill'] = $ord_bill;
            $log_data['user_info'] = $user_info;
            $log_data['request'] = $request->all();
            $log_data['wor_order_number'] = $find_wor->wor_order_number;
            $log_data['wocl_client_name'] = $wocl_client_name;
            $log_data['total_price'] = $total_price;
            $log_data['ord_info'] = $ord_info;
            $log_data['find_wor'] = $find_wor;
            $log_data['wor_plus_minus'] = $wor_plus_minus;
            Common::write_record_log($log_data, 'work_order_log.txt', 'updatePass-ReceivableBill');
            unset($log_data);
            // 生成操作记录
            $edit_record = orderLog($user_info, 0, $request['wor_id'], '审核通过工单');
            if ($wor_res && $ord_res && $wogo_res && $wocl_id && $edit_record && $orgo_res && $jur_price_res && $goo_state_update && $ord_bill && $acset_id && $join_wor_res && $join_wocl_id && $join_rece_res && $join_in_wor) {
                // 添加新增订单信息的提示
                $inhi_data['inhi_original_adm_id'] = $find_wor->wor_create_id; //原始单号创建人
                $inhi_data['inhi_original_id'] = $request['wor_id']; //原始单id
                $inhi_data['inhi_original_number'] = $find_wor->wor_number; //原始单号
                $inhi_data['inhi_original_state'] = $wor_data['wor_state']; //原始单状态
                $inhi_data['inhi_original_operation'] = '工单审核通过'; //操作
                $inhi_data['inhi_operation_state'] = 15; //操作状态：15工单审核通过
                addInformationHint($user_info, $inhi_data, 2);

                DB::commit();
                Common::addLog($user_info, getRealIp($request), '工单列表', '通过', $find_wor->wor_number . '通过成功');
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'通过成功']);
            } else {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'通过失败']);
            }
        }
        $request_voucher['find_wocl'] = ''; //用友接口上传凭证使用
        if ($find_wor->wocl_collect_state == 1 || $wor_coll_price > 0) {
            // ord_payment_way 2现结，订单结算方式为现结的，可以生成代收的应收账款
            // 计算出订单 代收金额/应收金额
            // 救援单没有商品的情况，这变量就不存在
            if (!isset($subtract)) {
                $subtract = [];
            } else {
                $ord_coll_price = 0;
                foreach ($subtract as $key => $value) {
                    // $ord_coll_price += $goo_info[$key]->orgo_collection_price * $value; //代收金额
                    $ord_coll_price += $goo_info[$key]->orgo_collection_price; //代收金额
                }
            }

            // 让技师收款，就要在生成结款明细 wocl_collect_state 技师收钱：0未选择1是2否
            $find_wocl = DB::table('work_client')
                ->where('wocl_wor_id', $request['wor_id'])
                ->first(['wocl_client_id', 'wocl_channel_unit', 'wocl_name', 'wocl_acti_id', 'wocl_collect_state']);
            $request_voucher['find_wocl'] = $find_wocl;
            $request_voucher['wor_coll_price'] = $wor_coll_price;
            // 1. 订单代收
            $ord_coll_bill = ReceivableBill::create(
                $user_info, //用户信息
                3, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $find_wor->wor_order_id, //原始id(订单id)
                $find_wor->wor_order_number, //应收账款单号/原始号(订单编号)
                $ord_info->ord_type, //客户类型：1.会员零售 2.来往单位 3.加盟店 4会员零售(工单代收）
                $ord_info->ord_client_id, //会员id/来往单位id
                $wocl_client_name, //来往单位名称
                $new_collection_price, //结算金额(代收金额)
                '', //结款时间
                $cli_info->orcl_acc_subject_id, //会计科目id
                $find_wocl->wocl_collect_state == 1 ? $new_collection_price : 0, //实际金额(未结算:0，已结算：代收金额)
                0, //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                $ord_info->ord_remark,  //备注
                0,  //已收金额
                '', //截止时间
                2, //金额正负1正   2负值
                2, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
                1, //是否合并代收：1是2否
                $ord_info->ord_create_time
            );
            // 记录日志
            $log_data['ord_coll_bill'] = $ord_coll_bill;
            $log_data['user_info'] = $user_info;
            $log_data['request'] = $request->all();
            $log_data['wor_order_number'] = $find_wor->wor_order_number;
            $log_data['wocl_client_name'] = $wocl_client_name;
            $log_data['ord_info'] = $ord_info;
            $log_data['find_wor'] = $find_wor;
            Common::write_record_log($log_data, 'work_order_log.txt', 'updatePass-ReceivableBill-create订单代收');
            unset($log_data);
            // 虚拟加盟店
            if ($find_wor->wocl_wor_type == 4) {
                $client_type = 7;
            } else {
                $client_type = $ord_info->ord_type;
            }

            // 2 工单代收，生成工单代收应收账款，判断是否让技师收款
            $recr_id = ReceivableBill::create(
                $user_info, //用户信息
                4, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $find_wor->wor_id, //原始id(工单id)
                $find_wor->wor_number, //应收账款单号/原始号(工单编号)
                $find_wor->wocl_wor_type == 2 ? 3 : $client_type, //客户类型：1.门店零售 2.来往单位 3.加盟店 4会员零售(工单代收）
                $find_wor->wocl_wor_type == 2 || $find_wor->wocl_wor_type == 4 ? $find_wor->wor_service_shop_id : $ord_info->ord_client_id, //会员id/来往单位id
                $find_wor->wocl_wor_type == 2 || $find_wor->wocl_wor_type == 4 ? $shop_info->shop_store_name : $wocl_client_name, //来往单位名称
                // $wor_coll_price, //结算金额
                $new_collection_price, //结算金额
                '', //结款时间
                $find_wocl->wocl_acti_id, //会计科目id
                // $find_wocl->wocl_collect_state == 1 ? $wor_coll_price : 0, //实际金额
                $find_wocl->wocl_collect_state == 1 ? $new_collection_price : 0, //实际金额
                0, //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                $request['remark'] ? $request['remark'] : '',  //备注
                0,  //已收金额
                '', //截止时间
                1, //金额正负:1正2负值
                3, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
                2, //是否合并代收：1是2否
                $ord_info->ord_create_time,
                $find_wocl->wocl_collect_state //技师是否收钱：0未选择1是2否
            );
            // 记录日志
            $log_data['recr_id'] = $recr_id;
            $log_data['user_info'] = $user_info;
            $log_data['request'] = $request->all();
            $log_data['wor_order_number'] = $find_wor->wor_number;
            $log_data['wocl_client_name'] = $find_wor->wocl_wor_type == 2 || $find_wor->wocl_wor_type == 4 ? $shop_info->shop_store_name : $wocl_client_name;
            $log_data['ord_info'] = $ord_info;
            $log_data['find_wor'] = $find_wor;
            Common::write_record_log($log_data, 'work_order_log.txt', 'updatePass-ReceivableBill-create工单代收');
            unset($log_data);

            // 判断是否生成结款明细，让技师收款，就生成结款明细
            if ($find_wocl->wocl_collect_state == 1) {
                // 生成结款明细
                $acset_id = AccountingSettlement::add(
                    $user_info, // [用户信息]
                    12, // [单据类型1订单结算2订单账单3工单账单11订单退款12工单代收]
                    $find_wor->wor_id, // [与单据类型对应的id]
                    $find_wor->wor_number, // [与单据类型对应的单号]
                    $ord_info->ord_type, // [买家类型1门店零售2来往单位]
                    $find_wocl->wocl_client_id, // [会员/客户id]
                    $wocl_client_name, // [来往单位名称]
                    $find_wocl->wocl_acti_id, // [会计科目id]
                    1, // [类型1收入2支出]
                    $new_collection_price, // [实际金额](此次的实收金额)
                    $new_collection_price, // [合计金额](此次的应收金额)
                    0, // [欠收金额](此次结款后还应收金额)
                    0, // [抹零金额]
                    $request['remark'] ? $request['remark'] : '' //[备注]
                );
            } else {
                $acset_id = true;
            }
        } else {
            $ord_coll_bill = true;
            $recr_id = true;
            $acset_id = true;
        }
        // 判断是否应该生成应收账款、结款明细
        // 订单状态为未结算时，可以生成应收账款、结款明细
        if ($ord_info->ord_state == 1) {
            // 3.订单应收
            $ord_bill = ReceivableBill::create(
                $user_info, //用户信息
                3, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $find_wor->wor_order_id, //原始id(订单id)
                $find_wor->wor_order_number, //应收账款单号/原始号(订单编号)
                $ord_info->ord_type, //客户类型：1.门店零售 2.来往单位
                $ord_info->ord_client_id, //会员id/来往单位id
                $wocl_client_name, //来往单位名称
                $genre == 1 && $find_wor->wocl_wor_type != 4 && $find_wor->wocl_wor_type != 5 ? abs($now_wor_price) : abs($ord_info->ord_actual_price), //结算金额(应收金额)
                // $genre == 1 ? $find_wor->wocl_assign_price : $ord_info->ord_actual_price, //结算金额(应收金额)
                '', //结款时间
                $cli_info->orcl_acc_subject_id, //会计科目id
                $ord_info->ord_state == 1 ? 0 : $find_wor->wocl_assign_price, //实际金额(应收金额)
                0, //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                $ord_info->ord_remark,  //备注
                $ord_info->ord_state == 1 ? 0 : $find_wor->wocl_assign_price,  //已收金额
                '', //截止时间
                $ord_plus_minus, //金额正负1正   2负值
                $find_wor->wor_service_type == 4 ? 10 : 1, //显示类型：1订单收款 10订单退款
                1, //是否合并代收：1是2否
                $ord_info->ord_create_time
            );
            // 记录日志
            $log_data['ord_bill'] = $ord_bill;
            $log_data['user_info'] = $user_info;
            $log_data['request'] = $request->all();
            $log_data['wor_order_number'] = $find_wor->wor_order_number;
            $log_data['wocl_client_name'] = $wocl_client_name;
            $log_data['ord_info'] = $ord_info;
            $log_data['find_wor'] = $find_wor;
            $log_data['ord_plus_minus'] = $ord_plus_minus;
            Common::write_record_log($log_data, 'work_order_log.txt', 'updatePass-ReceivableBill-create订单应收');
            unset($log_data);
            // 4.工单应收  工单的销售金额不生成应收账款，加盟店的生成
            if ($shop_info->shop_type == 3 && $find_wor->wocl_wor_type == 2) {
                $wor_bill = ReceivableBill::create(
                    $user_info, //用户信息
                    4, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                    0, //应收账款id
                    $find_wor->wor_id, //原始id(工单id)
                    $find_wor->wor_number, //应收账款单号/原始号(工单编号)
                    3, //客户类型：1.门店零售 2.来往单位3.外派门店（加盟店或总店）
                    $find_wor->wor_service_shop_id, //派单门店id
                    $shop_info->shop_store_name, //派单门店名称
                    $find_wor->wocl_assign_price, //结算金额
                    '', //结款时间
                    $cli_info->orcl_acc_subject_id, //会计科目id
                    $ord_info->ord_state == 1 ? 0 : $find_wor->wocl_assign_price, //实际金额
                    0,  //抹零金额
                    1,  //状态：1.未核销 2.已核销
                    1,  //应收账单id是否是自己 1.不是 2.是
                    $request['remark'] ? $request['remark'] : '',  //备注
                    $ord_info->ord_state == 1 ? 0 : $find_wor->wocl_assign_price,  //已收金额
                    '', //截止时间
                    2, //金额正负1正   2负值
                    4, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
                    1, //是否合并代收：1是2否
                    $ord_info->ord_create_time
                );
                $log_data['wor_plus_minus'] = 2;
            } elseif ($find_wor->wocl_wor_type == 4) { //虚拟加盟店
                $wor_bill = ReceivableBill::create(
                    $user_info, //用户信息
                    4, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                    0, //应收账款id
                    $find_wor->wor_id, //原始id(工单id)
                    $find_wor->wor_number, //应收账款单号/原始号(工单编号)
                    7, //客户类型：1.门店零售 2.来往单位3.外派门店（加盟店或总店）
                    $find_wor->wor_service_shop_id, //派单门店id
                    $shop_info->shop_store_name, //派单门店名称
                    abs($now_wor_price), //结算金额
                    '', //结款时间
                    $cli_info->orcl_acc_subject_id, //会计科目id
                    $ord_info->ord_state == 1 ? 0 : abs($now_wor_price), //实际金额
                    0,  //抹零金额
                    1,  //状态：1.未核销 2.已核销
                    1,  //应收账单id是否是自己 1.不是 2.是
                    $request['remark'] ? $request['remark'] : '',  //备注
                    $ord_info->ord_state == 1 ? 0 : abs($now_wor_price),  //已收金额
                    '', //截止时间
                    $wor_plus_minus, //金额正负1正   2负值
                    4, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
                    1, //是否合并代收：1是2否
                    $ord_info->ord_create_time
                );
                $log_data['wor_plus_minus'] = $wor_plus_minus;
            } elseif ($find_wor->wocl_wor_type == 5 && $shop_versions != 1) { //门店接城市运营中心单
                $wor_bill = ReceivableBill::create(
                    $user_info, //用户信息
                    4, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                    0, //应收账款id
                    $find_wor->wor_id, //原始id(工单id)
                    $find_wor->wor_number, //应收账款单号/原始号(工单编号)
                    5, //客户类型：1.门店零售 2.来往单位3.外派门店（加盟店或总店）
                    $find_wor->wor_service_shop_id, //派单门店id
                    $shop_info->shop_store_name, //派单门店名称
                    abs($find_wor->wor_actual_price), //结算金额
                    '', //结款时间
                    $cli_info->orcl_acc_subject_id, //会计科目id
                    0, //实际金额
                    0,  //抹零金额
                    1,  //状态：1.未核销 2.已核销
                    1,  //应收账单id是否是自己 1.不是 2.是
                    $request['remark'] ? $request['remark'] : '',  //备注
                    0, //已收金额
                    '', //截止时间
                    2, //金额正负1正   2负值
                    4, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
                    1, //是否合并代收：1是2否
                    $ord_info->ord_create_time
                );
                $log_data['wor_plus_minus'] = 2;
            } else {
                $wor_bill = true;
            }
            $goo_state_update = true;
        } else {
            // 订单状态为已结算状态，不生成应收账款
            $wor_bill = true;
            $ord_bill = true;
            $goo_state_update = true;
        }
        // 记录日志
        $log_data['wor_bill'] = $wor_bill;
        $log_data['user_info'] = $user_info;
        $log_data['request'] = $request->all();
        $log_data['wor_order_number'] = $find_wor->wor_number;
        $log_data['shop_store_name'] = $shop_info->shop_store_name;
        $log_data['ord_info'] = $ord_info;
        $log_data['find_wor'] = $find_wor;
        Common::write_record_log($log_data, 'work_order_log.txt', 'updatePass-ReceivableBill-create工单应收');
        unset($log_data);
        // 生成操作记录
        $edit_record = orderLog($user_info, 0, $request['wor_id'], '审核通过工单');

        // 添加备注
        if (!empty($request['remark'])) {
            orderRemark($user_info, $find_wor->wor_order_id, $request['wor_id'], $request['remark'], '工单列表-审核');
        }
        if ($wor_res && $ord_res && $wogo_res && $wocl_id && $edit_record && $ord_bill && $ord_coll_bill && $recr_id && $acset_id && $wor_bill && $orgo_res && $jur_price_res && $goo_state_update && $join_rece_res && $join_in_wor) {
            // 上传数据到凭证列表
            if ($voucher_state == true) {
                if (config('apiu8cloud.CODE_STARTS') && in_array($user_info->adm_shop_id, config('apiu8cloud.u8cloud_shop'))) {
                    // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
                    $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
                    // 生成凭证单据
                    if ($request['wor_service_type'] == '3') { //订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单 7救援单
                        if ($total_vouchar_cost != '0') {
                            $vore_data = WorkOrder::voucherReceipts($user_info, $shop_id, 2, $request['wor_id'], $find_wor->wor_number, $find_wor->wor_order_id, $find_wor->wor_order_number, $now_wor_price, $reduce_total_price, $find_wor->wor_collection_price, $total_vouchar_cost, $find_wor->wor_service_type, $find_wor->wor_type, $find_wor->wocl_client_id, $wocl_client_name);
                            if (!$vore_data) {
                                deleteImage($new_img_delete);
                                DB::rollBack();
                                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'生成凭证单失败']);
                            }
                        }
                    } else {
                        $vore_data = WorkOrder::voucherReceipts($user_info, $shop_id, 2, $request['wor_id'], $find_wor->wor_number, $find_wor->wor_order_id, $find_wor->wor_order_number, $now_wor_price, $reduce_total_price, $find_wor->wor_collection_price, $total_vouchar_cost, $find_wor->wor_service_type, $find_wor->wor_type, $find_wor->wocl_client_id, $wocl_client_name);
                        if (!$vore_data) {
                            deleteImage($new_img_delete);
                            DB::rollBack();
                            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'生成凭证单失败']);
                        }
                    }
                }
            }
            // 增加审核次数
            $order_wor_updatetimes = DB::table('work_order')
                ->where('wor_id', $find_wor->wor_id)
                ->value('wor_audit_times');
            $order_wor_updatetimes += 1;
            $work_order_update['wor_audit_times'] = $order_wor_updatetimes;
            $order_wor_upres = DB::table('work_order')
                ->where('wor_id', $find_wor->wor_id)
                ->update($work_order_update);

            // 添加新增订单信息的提示
            $inhi_data['inhi_original_adm_id'] = $find_wor->wor_create_id; //原始单号创建人
            $inhi_data['inhi_original_id'] = $request['wor_id']; //原始单id
            $inhi_data['inhi_original_number'] = $find_wor->wor_number; //原始单号
            $inhi_data['inhi_original_state'] = $wor_data['wor_state']; //原始单状态
            $inhi_data['inhi_original_operation'] = '工单审核通过'; //操作
            $inhi_data['inhi_operation_state'] = 15; //操作状态：15工单审核通过
            addInformationHint($user_info, $inhi_data, 2);

            DB::commit();
            // 审核修改回收金额-》高献昌   wogo_goo_type
            $work_goodresult = DB::table('work_good')
                ->where('wogo_state', '<>', 2)
                ->where('wogo_wor_id', $request['wor_id'])
                ->select('wogo_goo_id', 'wogo_state', 'wogo_goo_inventory', 'wogo_ware_id', 'wogo_goo_price', 'wogo_waon_class', 'wogo_goo_amount', 'wogo_is_recycle')
                ->get()
                ->toArray();

            $isrk = 1; //判断是否有入库商品
            foreach ($work_goodresult as $k => $v) {
                if (substr($v->wogo_goo_price, 0, 1) == '-') {
                    $v->wogo_goo_price = substr($v->wogo_goo_price, 1);
                }
                $sjense_in_price = $v->wogo_goo_price / 100; //审核价格
                if ($v->wogo_state == '4') { //换货
                    $enterres = DB::table('enters_sells_saves')
                        ->where('ense_order_number', $find_wor->wor_order_number)
                        ->where('ense_goo_id', $v->wogo_goo_id)
                        ->where('ense_goo_warehouse', $v->wogo_ware_id)
                        ->where('ense_out_in', '2')
                        ->where('ense_type', '12')
                        ->select('ense_id', 'ense_out_price', 'ense_in_price')
                        ->first();
                    $ense_save['ense_out_price'] = $sjense_in_price;
                    $ense_save['ense_out_amount'] = $sjense_in_price * $v->wogo_goo_amount;
                    DB::table('enters_sells_saves')
                        ->where('ense_id', $enterres->ense_id)
                        ->update($ense_save);
                    $isrk = 2;
                } elseif ($v->wogo_state == '3') { //回收
                    $enterres = DB::table('enters_sells_saves')
                        ->where('ense_order_number', $find_wor->wor_order_number)
                        ->where('ense_goo_id', $v->wogo_goo_id)
                        ->where('ense_goo_warehouse', $v->wogo_ware_id)
                        ->where('ense_out_in', '2')
                        ->where('ense_type', '4')
                        ->select('ense_id', 'ense_out_price', 'ense_in_price')
                        ->first();
                    $ense_save['ense_in_price'] = $sjense_in_price;
                    $ense_save['ense_in_amount'] = $sjense_in_price * $v->wogo_goo_amount;
                    DB::table('enters_sells_saves')
                        ->where('ense_id', $enterres->ense_id)
                        ->update($ense_save);
                    $isrk = 2;
                }
                if ($isrk == 2) {
                    // 审核价格与之前不一样
                    if ($sjense_in_price != $enterres->ense_in_price) {
                        $datetime = date('Y-m-d H:i:s');
                        $enterresult = DB::table('enters_sells_saves')
                            ->where('ense_goo_id', $v->wogo_goo_id)
                            ->where('ense_goo_warehouse', $v->wogo_ware_id)
                            ->where(function ($query) use ($datetime) {
                                $query->where('ense_time', '<=', $datetime);
                            })
                            ->orderBy('ense_id', 'desc')
                            ->select('ense_id', 'ense_end_inventory', 'ense_end_price', 'ense_end_amount')
                            ->first();
                        if ($sjense_in_price > $enterres->ense_in_price) {
                            $gopr_price = ($sjense_in_price - $enterres->ense_in_price) * $v->wogo_goo_amount;
                            $ense_edit_data['ense_end_amount'] = $enterresult->ense_end_amount + $gopr_price;
                        } else {
                            $gopr_price = ($enterres->ense_in_price - $sjense_in_price) * $v->wogo_goo_amount;
                            $ense_edit_data['ense_end_amount'] = $enterresult->ense_end_amount - $gopr_price;
                        }
                        if ($enterresult->ense_end_inventory == '0') {
                            $ense_edit_data['ense_end_price'] = '0';
                        } else {
                            $ense_edit_data['ense_end_price'] = $ense_edit_data['ense_end_amount'] / $enterresult->ense_end_inventory;
                        }
                        $ense_eidt_res = DB::table('enters_sells_saves')
                            ->where('ense_id', $enterresult->ense_id)
                            ->update($ense_edit_data);
                    }
                }
            }

            Common::addLog($user_info, getRealIp($request), '工单列表', '通过', $find_wor->wor_number . '通过成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'通过成功']);
        } else {
            deleteImage($new_img_delete);
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'通过失败']);
        }
    }

    // 更改工单信息，审核通过【门店基础版】
    private function shopUpdatePass($user_info, $verify_data, $request)
    {
        // 查询信息
        $find_wor = DB::table('work_order as wor')
            ->leftjoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wor.wor_id')
            ->where('wor_id', $request['wor_id'])
            ->select('wor_id', 'wor_number', 'wor_service_state', 'wor_order_id', 'wocl_client_id', 'wor_collection_price', 'wor_order_number', 'wor_service_shop_id', 'wor_is_recycle', 'wor_service_type', 'wor_plus_minus', 'wor_collection_bill', 'wocl_collect_state', 'wocl_name', 'wocl_channel_unit', 'wor_service_sepr_id', 'wocl_join_wor_id', 'wocl_wor_type', 'wocl_join_ord_id', 'wor_actual_price', 'wor_service_adm_id', 'wor_type', 'wor_create_id', 'wocl_assign_price', 'wocl_plus_minus', 'wor_recycle_price', 'wor_ware_id', 'wocl_rescue_service_price', 'wor_remark', 'wocl_sd_virtual_type', 'wocl_shit_id', 'wor_audit_times')
            ->first();
        // wor_service_state 服务状态：1待接单2已接单3预约4出发5抵达6完成待审核7完成已驳回8完成通过
        if ($find_wor->wor_service_state == 8) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'该工单已审核通过，请勿重复审核！']);
        }
        if ($find_wor->wor_service_state != 6) {
            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;
        $shop_versions = $user_info->shop_versions;

        // 第一次审核
        if ($find_wor->wor_audit_times == 0) {
            $request['recycle_state'] = isset($request['recycle_state']) ? $request['recycle_state'] : 1;
            // recycle_state 是否回收1是2不回收
            if ($request['recycle_state'] == 1) {
                if (!isset($request['jur_id'])) {
                    $request['jur_id'] = 0;
                }
                if (empty($request['goo_data'])) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'请选择回收商品！'];
                }
                // 判断是否有旧货回收单id
                if ($request['jur_id']) {
                    // jur_state 查询旧货回收状态 1 未回收 2已回收
                    $find_jur_state = DB::table('junk_recycle')
                        ->where('jur_id', $request['jur_id'])
                        ->value('jur_state');
                    if ($find_jur_state != 1) {
                        return ['code'=>500, 'msg'=>'error', 'data'=>'当前工单的回收单不是未回收状态！'];
                    }
                }
            }
            // 处理旧货回收商品的方法
            $junk_return = $this->junkRecycle($user_info, $shop_id, $verify_data, $request, $find_wor);
            if ($junk_return['code'] == 500) {
                return $junk_return;
            }

            // 处理退换回收商品
            if (!empty($request['rec_id'])) {
                $recycle_return = $this->salesReturn($user_info, $verify_data, $request, $find_wor);
                if ($recycle_return['code'] == 500) {
                    return $recycle_return;
                }
            }

            if ($request['wor_service_type'] != 4) {
                // 通过之前判断是否合格，退货、旧货商品是否回收
                $esel_return = $this->estimateEligibility(
                    $user_info,
                    $request['wor_id'],
                    $find_wor->wor_service_type,
                    $find_wor->wor_is_recycle
                );
                if ($esel_return['code'] === 500) {
                    return response()->json($esel_return);
                }
            }
        }

        // 救援单类型，查询服务项目的订单金额
        $sepr_order_money = 0; //服务项目的订单金额
        if ($find_wor->wocl_wor_type == 4) {
            $sepr_order_money = $request['sepr_order_money'] * 100;
        } elseif ($find_wor->wor_service_type == 7) {
            $sepr_order_money = $request['sepr_order_money'] * 100;
        }

        // 查询出工单商品
        $work_good = DB::table('work_good')
            ->where('wogo_state', '<>', 2)
            ->where('wogo_wor_id', $request['wor_id'])
            ->select('wogo_id', 'wogo_goo_id', 'wogo_goo_amount', 'wogo_goo_inventory', 'wogo_goo_price', 'wogo_collection_price', 'wogo_state', 'wogo_recycle_price', 'wogo_recycle_quantity', 'wogo_ware_id', 'wogo_waon_class', 'wogo_assign_price', 'wogo_orgo_id')
            ->get()->toArray();
        $jur_work_good = DB::table('work_good')
            ->where('wogo_state', '=', 3)
            ->where('wogo_wor_id', $request['wor_id'])
            ->select('wogo_id', 'wogo_goo_id', 'wogo_goo_amount', 'wogo_goo_inventory', 'wogo_goo_price', 'wogo_collection_price', 'wogo_state', 'wogo_recycle_price', 'wogo_recycle_quantity', 'wogo_ware_id', 'wogo_waon_class', 'wogo_assign_price', 'wogo_orgo_id')
            ->get()->toArray();
        $total_price = $sepr_order_money; //总的金额
        $before_price = 0;
        $before_collection_price = 0;
        $total_collection_price = 0;
        $reduce_total_price  = 0; //回收的总金额，工单订单需要减少的金额

        $voucher_sell_total_price  = 0; //销售总额，换货单，用友系统使用
        $voucher_refund_total_price  = 0; //退货总额，换货单，用友系统使用
        $voucher_cost  = 0; //凭证成本，上传用友系统
        $refund_voucher_cost  = 0; //换货单，换回商品成本，凭证成本，上传用友系统
        $total_vouchar_cost = 0;

        if (!empty($work_good)) {
            foreach ($work_good as $key => $value) {
                if ($value->wogo_state == 1) {
                    // 商品id
                    $goo_id[$key] = $value->wogo_goo_id;
                    // 商品数量
                    $goo_number[$key] = $value->wogo_goo_amount;
                    // 商品价格
                    $goo_price[$key] = $value->wogo_goo_price;
                    // 之前商品总价格
                    $before_price += $value->wogo_goo_price * $value->wogo_goo_amount;
                    // 之前商品代收总价格
                    $before_collection_price += $value->wogo_collection_price;

                    // 销售总额，换货单，用友系统使用
                    $voucher_sell_total_price += $request['goo_price'][$key] * $value->wogo_goo_amount;

                    // 工单商品总价
                    $total_price += $request['goo_price'][$key] * $value->wogo_goo_amount * 100;
                    // 工单商品代收总价
                    $total_collection_price += $request['goo_collection_price'][$key] * 100;
                    // 库存扣除方式1.良品 2.优先
                    $goo_inventory[$key] = $value->wogo_goo_inventory;
                    // 商品id所对应的商品数量
                    $subtract[$value->wogo_goo_id] = $value->wogo_goo_amount;
                    // 商品id所对应的出库方式
                    $goo_repertory[$value->wogo_goo_id] = $value->wogo_goo_inventory;
                } elseif ($value->wogo_state == 4) {
                    $before_price -= $value->wogo_goo_price * $value->wogo_goo_amount;
                    $total_price -= $value->wogo_goo_price * $value->wogo_goo_amount;
                    // 退货总额，换货单，用友系统使用
                    $voucher_refund_total_price += $value->wogo_goo_price * $value->wogo_goo_amount;
                } elseif ($value->wogo_state == 6) {
                    // 工单商品总价
                    $total_price += $request['goo_price'][$key] * $value->wogo_goo_amount * 100;
                    // 工单商品代收总价
                    $total_collection_price += $request['goo_collection_price'][$key] * 100;
                }
                $wogo_goo_id_amount[$value->wogo_id] = $value->wogo_goo_amount;

                // 计算凭证成本
                // 商品状态1.正常 2.删除3.回收的商品4.换货商品5.赠品商品6.备用电池7.临时商品8.旧货商品
                if (in_array($value->wogo_state, [1, 5, 8])) {
                    $find_end_price = DB::table('enters_sells_saves')
                        ->where('ense_goo_id', $value->wogo_goo_id)
                        ->where('ense_goo_warehouse', $value->wogo_ware_id)
                        ->where('ense_goo_waretype', $value->wogo_waon_class)
                        ->where('ense_order_number', $find_wor->wor_order_number)
                        ->orderBy('ense_id', 'desc')
                        ->value('ense_end_price');
                    $find_end_price = sprintf('%.2f', $find_end_price);
                    if ($find_end_price) {
                        $voucher_cost += $find_end_price * $value->wogo_goo_amount;
                    } else {
                        $voucher_cost = 0;
                    }
                } elseif ($value->wogo_state == 4) {
                    // 查询当时的商品对应的成本
                    $find_end_price = DB::table('enters_sells_saves')
                        ->where('ense_goo_id', $value->wogo_goo_id)
                        ->where('ense_goo_warehouse', $value->wogo_ware_id)
                        ->where('ense_goo_waretype', $value->wogo_waon_class)
                        ->where('ense_order_number', $find_wor->wor_order_number)
                        ->orderBy('ense_id', 'desc')
                        ->value('ense_end_price');
                    $find_end_price = sprintf('%.2f', $find_end_price);
                    if ($find_end_price) {
                        $refund_voucher_cost += $find_end_price * $value->wogo_goo_amount;
                    } else {
                        $refund_voucher_cost = 0;
                    }
                }
                $total_vouchar_cost = $voucher_cost - $refund_voucher_cost;
            }
            $goo_work_goods = array_column($work_good, null, 'wogo_goo_id');
            // 编辑工单商品表数据
            $sql = 'UPDATE `faster_work_good` SET ';
            $actual_price_sql = '';
            $collection_price_sql = '';
            $update_time_sql = '';
            $ids = '';
            $junk_recycle = [];
            $goo_exchange_price  = [];
            if (!is_array($request['wogo_id'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'wogo_id 必传']);
            }
            foreach ($request['wogo_id'] as $key => $value) {
                if (!is_numeric($value) || !is_numeric($request['goo_price'][$key]) || !is_numeric($request['goo_collection_price'][$key])) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'商品参数类型错误1'];
                }
                if (isset($request['wogo_state'][$key]) && $request['wogo_state'][$key] != 5) {
                    $edit_wogo_data['wogo_goo_price'] = $request['goo_price'][$key] * 100;
                    $edit_wogo_data['wogo_collection_price'] = $request['goo_collection_price'][$key] * 100;
                    $edit_wogo_data['wogo_update_time'] = date('Y-m-d H:i:s');
                    $wogo_res = DB::table('work_good')
                        ->where('wogo_id', $value)
                        ->where('wogo_wor_id', $request['wor_id'])
                        ->update($edit_wogo_data);
                    if (!$wogo_res) {
                        return ['code'=>500, 'msg'=>'error', 'data'=>'审核失败3！'];
                    }
                    unset($edit_wogo_data);
                }

                // 旧货回收商品价格
                if (isset($request['wogo_state'][$key]) && $request['wogo_state'][$key] == 3) {
                    // 审核输入的回收金额，进销存金额使用
                    $goo_exchange_price[$value] = $request['goo_price'][$key] * 100; //进销存金额
                    $goo_exchange_amount[$value] = $wogo_goo_id_amount[$value]; //进销存数量
                    $junk_recycle[] = $value; //旧货回收商品id
                    $reduce_total_price += $request['goo_price'][$key] * 100 * $wogo_goo_id_amount[$value];
                }

                if (isset($request['wogo_state'][$key]) && $request['wogo_state'][$key] == 8) {
                    $goo_exchange_price[$value] = $request['goo_price'][$key] * 100; //进销存金额
                    $goo_exchange_amount[$value] = $wogo_goo_id_amount[$value]; //进销存数量
                    $junk_recycle[] = $value; //旧货回收商品id
                    $reduce_total_price -= $request['goo_price'][$key] * 100 * $wogo_goo_id_amount[$value];
                }
            }
            if (!empty($jur_work_good) && $find_wor->wor_audit_times == 0) {
                foreach ($jur_work_good as $jurkey => $jurval) {
                    // 审核输入的回收金额，进销存金额使用
                    $goo_exchange_price[$jurval->wogo_id] = $jurval->wogo_recycle_price;
                    $goo_exchange_amount[$jurval->wogo_id] = $wogo_goo_id_amount[$jurval->wogo_id]; //进销存数量
                    $junk_recycle[] = $jurval->wogo_id; //旧货回收商品id
                    $reduce_total_price += $jurval->wogo_recycle_price * $wogo_goo_id_amount[$jurval->wogo_id];
                }
            }
            $wogo_res = true;
        } else {
            $wogo_res = true;
        }
        // 如果是外派工单并且是派单方审核
        if ($find_wor->wocl_wor_type == 2 && $find_wor->wocl_join_wor_id == 0) { //2外派工单
            $wor_data['wor_service_state'] = 8; //完成通过
            $request->offsetSet('wor_actual_price', $find_wor->wor_actual_price / 100);
        } elseif ($find_wor->wocl_wor_type == 1) {//1系统工单
            $wor_data['wor_service_state'] = 8; //完成通过
        } elseif ($find_wor->wocl_wor_type == 5) {//门店派单
            $wor_data['wor_service_state'] = 8; //完成通过
        }
        $virtual_goo_price = 0; //虚拟加盟店订单金额
        // 编辑订单商品表数据
        if (!empty($work_good) && $find_wor->wocl_wor_type == 1) {
            $sql = 'UPDATE `faster_order_goods` SET ';
            $actual_price_sql = '';
            $collection_price_sql = '';
            $update_time_sql = '';
            $ids = '';
            if (!is_array($request['wogo_orgo_id'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'wogo_orgo_id 必传']);
            }
            foreach ($request['wogo_orgo_id'] as $key => $value) {
                if (!is_numeric($value) || !is_numeric($request['goo_price'][$key]) || !is_numeric($request['goo_collection_price'][$key])) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'商品参数类型错误'];
                }

                if (isset($request['wogo_state'][$key]) && $request['wogo_state'][$key] != 5) {
                    $edit_wogo_data['orgo_goo_price'] = $request['goo_price'][$key] * 100;
                    $edit_wogo_data['orgo_collection_price'] = $request['goo_collection_price'][$key] * 100;
                    $edit_wogo_data['orgo_update_time'] = date('Y-m-d H:i:s');
                    $orgo_res = DB::table('order_goods')
                        ->where('orgo_id', $value)
                        ->where('orgo_ord_id', $find_wor->wor_order_id)
                        ->update($edit_wogo_data);
                    if (!$orgo_res) {
                        DB::rollBack();
                        return ['code'=>500, 'msg'=>'error', 'data'=>'审核失败！'];
                    }
                    unset($edit_wogo_data);
                } else {
                    $orgo_res = true;
                }
            }
        } elseif (!empty($work_good) && $find_wor->wocl_wor_type == 4) {
            $sql = 'UPDATE `faster_order_goods` SET ';
            $actual_price_sql = '';
            $collection_price_sql = '';
            $update_time_sql = '';
            $ids = '';
            $junk_goo_price = 0;
            $old_junk_goo_price = 0;
            if (!is_array($request['wogo_orgo_id'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'wogo_orgo_id 必传']);
            }
            foreach ($request['wogo_orgo_id'] as $key => $value) {
                if (!is_numeric($value) || !is_numeric($request['orgo_goo_price'][$key]) || !is_numeric($request['goo_collection_price'][$key])) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'商品参数类型错误'];
                }

                // 更改商品价格
                $actual_price_sql = $actual_price_sql . ' WHEN ' . $value;
                $actual_price_sql = $actual_price_sql . ' THEN ' . $request['orgo_goo_price'][$key] * 100;

                // 更改商品代收价格
                $collection_price_sql = $collection_price_sql . ' WHEN ' . $value;
                $collection_price_sql = $collection_price_sql . ' THEN ' . $request['goo_collection_price'][$key] * 100;

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

                if ($request['wogo_state'][$key] != 3) {
                    $virtual_goo_price += $request['orgo_goo_price'][$key] * 100 * $wogo_goo_id_amount[$request['wogo_id'][$key]];
                } else {
                    $virtual_goo_price -= $request['orgo_goo_price'][$key] * 100 * $wogo_goo_id_amount[$request['wogo_id'][$key]];
                    // 计算原来的旧货金额
                    $old_junk_goo_price += $request['orgo_goo_price'][$key] * 100 * $wogo_goo_id_amount[$request['wogo_id'][$key]];
                }
            }
            $sql = $sql . ' `orgo_goo_price` = CASE `orgo_id`' . $actual_price_sql . ' END,'; //商品售价
            $sql = $sql . ' `orgo_collection_price` = CASE `orgo_id`' . $collection_price_sql . ' END,'; //商品代收金额
            $sql = $sql . ' `orgo_update_time`=  CASE `orgo_id` ' . $update_time_sql . ' END';
            $sql = $sql . ' WHERE `orgo_ord_id` = ' . $find_wor->wor_order_id . ' AND `orgo_id` IN (' . trim($ids, ',') . ')';
            $orgo_res = DB::update($sql);
            $virtual_goo_price += $sepr_order_money;

            if (!empty($request['virtual_goo_id'])) {
                foreach ($request['virtual_goo_id'] as $key => $value) {
                    $junk_goo_price += $request['virtual_goo_price'][$key] * 100 * $request['virtual_goo_quantity'][$key];
                    $goods_data = DB::table('goods')
                        ->where('goo_id', $value)
                        ->first(['goo_name', 'goo_goods_encode', 'goo_class']);
                    if ($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)) {
                            $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)) {
                            $goods_data->goo_name = $gosa_another_name;
                        }
                    }
                    $virtual_wor[$key]['wogo_wor_id'] = $request['wor_id'];
                    $virtual_wor[$key]['wogo_goo_id'] = $value;
                    $virtual_wor[$key]['wogo_waon_class'] = 3;
                    $virtual_wor[$key]['wogo_is_recycle'] = 2;
                    $virtual_wor[$key]['wogo_goo_name'] = $goods_data->goo_name;
                    $virtual_wor[$key]['wogo_goo_goods_encode'] = $goods_data->goo_goods_encode;
                    $virtual_wor[$key]['wogo_goo_type'] = 4;
                    $virtual_wor[$key]['wogo_state'] = 3;
                    $virtual_wor[$key]['wogo_goo_price'] = $request['virtual_goo_price'][$key] * 100;
                    $virtual_wor[$key]['wogo_goo_amount'] = $request['virtual_goo_quantity'][$key];
                    $virtual_wor[$key]['wogo_recycle_quantity'] = $request['virtual_goo_quantity'][$key];
                    $virtual_wor[$key]['wogo_actual_recycle_number'] = $request['virtual_goo_quantity'][$key];

                    $virtual_order[$key]['orgo_ord_id'] = $find_wor->wor_order_id;
                    $virtual_order[$key]['orgo_order_number'] = $find_wor->wor_order_number;
                    $virtual_order[$key]['orgo_waon_class'] = 3;
                    $virtual_order[$key]['orgo_goo_id'] = $value;
                    $virtual_order[$key]['orgo_goo_name'] = $goods_data->goo_name;
                    $virtual_order[$key]['orgo_goo_goods_encode'] = $goods_data->goo_goods_encode;
                    $virtual_order[$key]['orgo_goo_type'] = 4;
                    $virtual_order[$key]['orgo_goo_inventory'] = 1;
                    $virtual_order[$key]['orgo_is_recycle'] = 2;
                    $virtual_order[$key]['orgo_state'] = 3;
                    $virtual_order[$key]['orgo_goo_price'] = $request['virtual_goo_price'][$key] * 100;
                    $virtual_order[$key]['orgo_goo_quantity'] = $request['virtual_goo_quantity'][$key];
                    $virtual_order[$key]['orgo_recycle_quantity'] = $request['virtual_goo_quantity'][$key];
                }
                DB::table('order_goods')->insert($virtual_order);
                DB::table('work_good')->insert($virtual_wor);
            }
        } else {
            $orgo_res = true;
        }

        // 查询订单商品是否全部派完
        $find_orgo_id = DB::table('order_goods')
            ->where('orgo_ord_id', $find_wor->wor_order_id)
            ->where('orgo_can_assign_quantity', '>', 0)
            ->value('orgo_id');
        if ($find_orgo_id) {
            $ord_wor_state = '';
        } else {
            // 没有可以派单的商品了，订单状态改为完成状态
            $ord_edit_data['ord_wor_state'] = 4; //订单的工单状态1未派工单2服务中3售后中4已完成
            $ord_wor_state = ', ord_wor_state = 4 '; //订单的工单状态1未派工单2服务中3售后中4已完成
        }

        $jur_price = 0;
        // 修改旧货回收价格
        if (!empty($junk_recycle)) {
            $jur_amount =  DB::table('work_good')
                ->where('wogo_wor_id', $request['wor_id'])
                ->where('wogo_state', 3)
                ->whereIn('wogo_id', $junk_recycle)
                ->get(['wogo_actual_recycle_number', 'wogo_goo_id', 'wogo_ware_id', 'wogo_id', 'wogo_orgo_id']);
            $jur_id =  DB::table('junk_recycle')
                ->where('jur_wor_id', $request['wor_id'])
                ->value('jur_id');
            foreach ($jur_amount as $key => $value) {
                $jur_price  += $goo_exchange_price[$value->wogo_id] * $value->wogo_actual_recycle_number;
                $junk_goods_update = DB::table('junk_goods')
                    ->where('jugo_jur_id', $jur_id)
                    ->where('jugo_wogo_id', $value->wogo_id)
                    ->update(['jugo_goo_price' => $goo_exchange_price[$value->wogo_id], 'jugo_update_time' => date('Y-m-d H:i:s')]);
                if ($junk_goods_update || $junk_goods_update === 0) {
                } else {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'通过失败'];
                }
                //更新返回影响行数为0的问题，可能是并发的问题，参考下面的文章，暂时先用这种方式解决 https://blog.csdn.net/weixin_41750790/article/details/85335206
                $res2 = DB::table('work_good')
                    ->where('wogo_wor_id', $find_wor->wor_id)
                    ->where('wogo_id', $value->wogo_id)
                    ->update(['wogo_goo_price' => $goo_exchange_price[$value->wogo_id], 'wogo_update_time' => date('Y-m-d H:i:s')]);
                if ($res2 || $res2 === 0) {
                } else {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'通过失败'];
                }

                $res3 = DB::table('order_goods')
                    ->where('orgo_ord_id', $find_wor->wor_order_id)
                    ->where('orgo_id', $value->wogo_orgo_id)
                    ->update(['orgo_goo_price' => $goo_exchange_price[$value->wogo_id], 'orgo_update_time' => date('Y-m-d H:i:s')]);

                if ($res3 || $res3 === 0) {
                } else {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'通过失败'];
                }
                $goo_state_update = true;
            }
            // 判断是否有该工单
            $jur_wor_id =  DB::table('junk_recycle')
                ->where('jur_wor_id', $request['wor_id'])
                ->value('jur_wor_id');
            if ($jur_wor_id) {
                $jur_price_res =  DB::table('junk_recycle')
                    ->where('jur_wor_id', $request['wor_id'])
                    ->update(['jur_price' => $jur_price, 'jur_check_state' => 2, 'jur_update_time' => date('Y-m-d H:i:s')]);
            } else {
                $jur_price_res = true;
            }
        } else {
            $jur_price_res = true;
            $goo_state_update = true;
            $ord_res = true;
        }

        // 获取到当前工单的订单信息
        $ord_info = DB::table('order')
            ->where('ord_id', $find_wor->wor_order_id)
            ->first(['ord_type', 'ord_client_id', 'ord_state', 'ord_remark', 'ord_actual_price', 'ord_payment_way', 'ord_order_price', 'ord_collection_price', 'ord_plus_minus', 'ord_other_system_number', 'ord_service_type', 'ord_create_time']);

        // 计算订单总的金额，订单中已经有了服务项目金额所以计算的时候要减去
        $total_price = $total_price - $sepr_order_money;
        // 现在的代收价格减去之前代收价格
        $diff_collection_price = $total_collection_price - $before_collection_price;
        // 计算新的订单代收总金额
        // $new_collection_price = $ord_info->ord_collection_price + $diff_collection_price;
        $new_collection_price = $request['wocl_rescue_collection_price'] * 100 + $total_collection_price;
        // 现在的价格减去之前价格 减去回收价格
        if ($ord_info->ord_state == 2) {
            // 订单已经结算，订单的金额不再减去回收的金额
            $diff_price = $total_price - $before_price;
        } else {
            $diff_price = $total_price - $before_price - $reduce_total_price;
        }

        // 计算新的订单结算总金额
        if ($ord_info->ord_plus_minus == 1) {
            // 新的结算总金额 = 订单原来的结算金额 + 现在的金额
            $new_actual_price = $ord_info->ord_actual_price + $diff_price;
        } else {
            $new_actual_price = $diff_price - $ord_info->ord_actual_price;
        }
        // 新的订单金额正负值
        if ($new_actual_price >= 0 && $request['wor_service_type'] != 4) {
            $ord_plus_minus = 1;
        } else {
            $ord_plus_minus = 2;
        }

        // 查询订单客户信息表
        $cli_info = DB::table('order_client')
            ->where('orcl_ord_id', $find_wor->wor_order_id)
            ->first(['orcl_acc_subject_id', 'orcl_channel_unit', 'orcl_name', 'orcl_collect_state']);

        // 应收账款显示客户名称
        $wocl_client_name = $find_wor->wocl_channel_unit ? $find_wor->wocl_channel_unit : $find_wor->wocl_name;
        if ($find_wor->wor_type == 5 && $shop_versions == 1) {
            $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
            $parent_shop_id = DB::table('shop')
                ->where('shop_id', $shop_id)
                ->value('shop_parent_id');
            $wocl_client_name = DB::table('shop')
                ->where('shop_id', $parent_shop_id)
                ->value('shop_store_name');
        }

        $goo_info = collect(DB::table('order_goods')
            ->where('orgo_ord_id', $find_wor->wor_order_id)
            ->get(['orgo_goo_id', 'orgo_goo_price', 'orgo_collection_price']))
            ->keyBy('orgo_goo_id')
            ->toArray();
        // 服务名称
        if ($find_wor->wocl_wor_type == 4) {
            $shop_info = DB::table('virtual_shop')
                ->where('vish_id', $find_wor->wor_service_shop_id)
                ->first(['vish_store_name as shop_store_name']);
            $shop_info->shop_type = 4;
        } else {
            $shop_info = DB::table('shop')
                ->where('shop_id', $find_wor->wor_service_shop_id)
                ->first(['shop_store_name', 'shop_type']);
        }
        // 如果订单类型是退货单 金额为负数，金额类型为负数的
        $plus_minus = 1;
        if ($request['wor_service_type'] == 4 || $find_wor->wor_plus_minus == 2) {
            $plus_minus = 2;
        }

        // 计算应收账款的金额，前面计算订单金额时减去了，计算应收账款时在加回来
        // $total_price = $total_price + $sepr_order_money;
        $now_order_total_price = $total_price + $sepr_order_money; //订单总金额
        $total_price = $total_price + $sepr_order_money - $reduce_total_price; //结算金额
        // 应收账款的金额 现在的价格 减去回收价格
        // 根据工单金额的正负判断
        if (empty($work_good)) {
            $now_wor_price = $total_price;
            $now_order_price = $now_order_total_price;
        } else {
            $now_wor_price = $total_price;
            $now_order_price = $now_order_total_price;
        }
        $image_change_state = 1; //工单审核图片更改状态：1未上传新图2重新传图
        $old_img_delete = []; //原来的被替换的图片需要删除
        $new_img_delete = []; //新上传的图片，提交失败时删除
        // 如果是虚拟加盟店
        if ($find_wor->wocl_wor_type == 4) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'虚拟加盟店审核失败'];
        } else {
            // 不是虚拟加盟店的上传图片处理
            if (!empty($request['imgs64'])) {
                // 根据图片上传模板判断上传图片
                $find_image_template = DB::table('shop_image_template')
                    ->where('shit_id', $find_wor->wocl_shit_id)
                    ->value('shit_template_set');
                $find_image_template = json_decode($find_image_template, true);
                $upload_file = json_decode(json_encode($request['imgs64']), true);

                // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
                $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
                $imup_data = [];
                foreach ($find_image_template as $key => $value) {
                    // 判断必传图片是否上传 must_state 为1是门店设置的必传图片
                    if ($value['must_state'] == 1 && empty($upload_file[$key])) {
                        return ['code'=>500, 'data'=>'请上传 ' . $value['show_word'] . ' 图片', 'msg'=>'error'];
                    }
                }
                $new_key = 0;
                foreach ($upload_file as $key => $value) {
                    if (!empty($value)) {
                        // 判断是否有新图片上传
                        if (strpos($value, 'data:image') === 0) {
                            // 有新图片上传，将原来的图片改为删除状态
                            $imup_edit['imup_delete'] = 2;
                            $imup_edit['imup_update_time'] = date('Y-m-d H:i:s');
                            $edit_res = DB::table('image_upload')
                                ->where('imup_wor_id', $request['wor_id'])
                                ->where('imup_delete', 1)
                                ->where('imup_image_name', $find_image_template[$key]['show_word'])
                                ->update($imup_edit);
                            unset($imup_edit);
                            if (!$edit_res) {
                                return ['code'=>500, 'data'=>'图片上传失败', 'msg'=>'error'];
                            }
                            // 调用全局函数 上传图片
                            $image_path = uploadBase64ImgFolder($shop_id, $value, 2);
                            $imup_data[$new_key]['imup_path'] = $image_path;
                            $imup_data[$new_key]['imup_cid'] = $user_info->adm_cid;
                            $imup_data[$new_key]['imup_shop_id'] = $user_info->adm_shop_id;
                            $imup_data[$new_key]['imup_superior_shop_id'] = $shop_id;
                            $imup_data[$new_key]['imup_ord_id'] = $find_wor->wor_order_id;
                            $imup_data[$new_key]['imup_wor_id'] = $request['wor_id'];
                            $imup_data[$new_key]['imup_image_name'] = $find_image_template[$key]['show_word'];
                            $new_key++;
                            $new_img_delete[] = $image_path; //新上传的图片路径
                        }
                    }
                }
                if ($imup_data) {
                    $imup_res = DB::table('image_upload')->insert($imup_data);
                    if (!$imup_res) {
                        return ['code'=>500, 'data'=>'图片上传失败', 'msg'=>'error'];
                    }
                }
            }
        }
        $party = $find_wor->wocl_wor_type; //1系统工单 2外派工单 3速电派单 4 虚拟加盟店

        // 应收账款的金额正负值
        if ($now_wor_price > 0) {
            // 如果是退货单不一定是负数  虚拟加盟店  加盟店
            if ($request['wor_service_type'] == 4) { //订单类型：4退货单
                // 退货单 外派工单 虚拟加盟店
                $wor_plus_minus = $party == 2 || $party == 4 ? 1 : 2; //工单总金额正负：1正值2负值
            } else {
                $wor_plus_minus = $party == 2 || $party == 4 ? 2 : 1;
            }
        } else {
            if ($request['wor_service_type'] == 4) {
                $wor_plus_minus = $party == 2 || $party == 4 ? 2 : 1;
            } else {
                $wor_plus_minus = $party == 2 || $party == 4 ? 1 : 2;
            }
        }
        // 更改工单信息
        $wor_data['wor_actual_price'] = $now_wor_price; //工单结算金额(单位:分)
        $wor_data['wor_collection_price'] = $new_collection_price;
        $wor_data['wor_service_type'] = $request['wor_service_type'];   //服务类型
        $wor_data['wor_service_sepr_id'] = $request['wor_service_sepr_id'];   //服务项目
        if ($find_wor->wocl_wor_type == 3) {
            $wor_data['wor_pass'] = 11;  //审核状态1.待审核 2.合格 3.不合格 11.等待速电审核
        } elseif ($find_wor->wocl_wor_type == 5 && $shop_versions == 1) {
            $wor_data['wor_pass'] = 12;  //审核状态1.待审核 2.合格 3.不合格 12.等待城市运营中心审核
        } else {
            $wor_data['wor_pass'] = 2;
        }

        $wor_data['wor_state'] = 10;    //状态1.新订单 2未派单 3待接单/已派单 4.未出发/已接单 5.预约/已预约 6.出发/已出发  7.抵达/抵达 8.待审核/完成待审核 9驳回/完成已驳回 10完成/完成已通过 11终止
        $wor_data['wor_remark'] = $request['remark'] ? $request['remark'] : ''; //工单备注
        $wor_data['wor_plus_minus'] = $wor_plus_minus; //金额正负：1正值2负值
        $wor_data['wor_recycle_price'] = $reduce_total_price; //回收金额
        $wor_data['wor_update_time'] = date('Y-m-d H:i:s');
        $wor_res = DB::table('work_order')
            ->where('wor_id', $request['wor_id'])
            ->update($wor_data);
        if ($find_wor->wocl_wor_type == 5 && $shop_versions != 1) {
            $shop_update['wor_pass'] = 2;
            $shop_update_res = DB::table('work_order')
                ->where('wor_order_id', $find_wor->wocl_join_ord_id)
                ->update($shop_update);
        }
        // 工单客户信息
        $wocl_data['wocl_name'] = $request['wocl_name'];    //姓名
        $wocl_data['wocl_car_num'] = $request['wocl_car_num'];  //车牌号
        $wocl_data['wocl_province'] = $request['wocl_province'] ? $request['wocl_province'] : '';  //省
        $wocl_data['wocl_city'] = $request['wocl_city'] ? $request['wocl_city'] : '';  //市
        $wocl_data['wocl_county'] = $request['wocl_county'] ? $request['wocl_county'] : '';  //县
        $wocl_data['wocl_address'] = $request['wocl_address'];  //地址
        $wocl_data['wocl_rescue_collection_price'] = $request['wocl_rescue_collection_price'] * 100;  //代收金额
        $wocl_data['wocl_update_time'] = date('Y-m-d H:i:s');  //时间
        $wocl_data['wocl_join_audit_adm_id'] = $user_info->adm_id;
        $wocl_data['wocl_rescue_service_price'] = $request['sepr_order_money'] * 100;
        $wocl_id = DB::table('work_client')
            ->where('wocl_wor_id', $find_wor->wor_id)
            ->update($wocl_data);
        $wocl_rescue_collection_price = $request['wocl_rescue_collection_price'] * 100;
        $orcl_rescue_service_price = $request['sepr_order_money'] * 100;
        DB::table('order_client')
            ->where('orcl_ord_id', $find_wor->wor_order_id)
            ->update(['orcl_rescue_collection_price' => $wocl_rescue_collection_price, 'orcl_rescue_service_price' => $orcl_rescue_service_price]);

        // 1不是总店审核的外派   2是
        $genre = 1;
        // 如果是总店审核不修改总店的订单价格
        if ($find_wor->wocl_wor_type == 2 && $find_wor->wocl_join_wor_id == 0) {
            // 查询订单商品是否全部派完
            $find_orgo_id = DB::table('order_goods')
                ->where('orgo_ord_id', $find_wor->wocl_join_ord_id)
                ->where('orgo_can_assign_quantity', '>', 0)
                ->value('orgo_id');
            if ($find_orgo_id) {
                $ord_wor_state = '';
            } else {
                // 没有可以派单的商品了，订单状态改为完成状态
                $ord_edit_data['ord_wor_state'] = 4; //订单的工单状态1未派工单2服务中3售后中4已完成
                $ord_wor_state = ', ord_wor_state = 4 '; //订单的工单状态1未派工单2服务中3售后中4已完成
            }
            $ord_edit_data['ord_update_time'] = date('Y-m-d H:i:s');
            $ord_res = DB::table('order')
                ->where('ord_id', $find_wor->wor_order_id)
                ->update($ord_edit_data);
            $join_ord_res = DB::table('order')
                ->where('ord_id', $find_wor->wocl_join_ord_id)
                ->update($ord_edit_data);
            $genre = 2;
            $wor_update['wor_update_time'] = date('Y-m-d H:i:s');
            $wor_update['wor_service_state'] = 8;

            $join_wor_id = DB::table('work_order')
                ->where('wor_order_id', $find_wor->wocl_join_ord_id)
                ->value('wor_id');
            // 修改加盟店审核状态
            $join_in_wor = DB::table('work_order')
                ->where('wor_id', $join_wor_id)
                ->update($wor_update);
            // 生成操作记录
            $edit_record = orderLog($user_info, 0, $join_wor_id, '总店审核通过工单');
        } elseif ($find_wor->wocl_wor_type == 1) { //1系统工单 2外派工单 3速电派单
            // 更新订单表数据
            $ord_edit_data['ord_actual_price'] = $now_wor_price;
            $ord_edit_data['ord_order_price'] = $now_order_price;
            $ord_edit_data['ord_collection_price'] = $new_collection_price;
            $ord_edit_data['ord_plus_minus'] = $wor_plus_minus;
            $ord_edit_data['ord_order_plus_minus'] = $wor_plus_minus;
            $ord_edit_data['ord_update_time'] = date('Y-m-d H:i:s');
            $ord_res = DB::table('order')
                ->where('ord_id', $find_wor->wor_order_id)
                ->update($ord_edit_data);
            $join_in_wor = true;
        } else {
            // 如果是外派工单
            if ($find_wor->wocl_wor_type == 2 && isset($ord_edit_data['ord_wor_state'])) {
                unset($ord_edit_data['ord_wor_state']);
            }

            if ($find_wor->wocl_wor_type != 4) {
                // 更新订单表数据
                $ord_edit_data['ord_actual_price'] = $now_wor_price;
                $ord_edit_data['ord_order_price'] = $now_order_price;
                $ord_edit_data['ord_plus_minus'] = $wor_plus_minus;
            } elseif ($find_wor->wocl_wor_type == 4) {
                $ord_actual_price = $virtual_goo_price - $junk_goo_price;
                $ord_info->ord_actual_price = $ord_actual_price;
                $virtual_ord_plus_minus = 1;
                if ($ord_actual_price < 0) {
                    $virtual_ord_plus_minus = 2;
                }
                $ord_plus_minus = $virtual_ord_plus_minus;
                // 订单金额应该是不减回收的金额
                $virtual_goo_price = $old_junk_goo_price + $virtual_goo_price;
                $ord_edit_data['ord_actual_price'] = $ord_actual_price; //减回收金额
                $ord_edit_data['ord_order_price'] = $virtual_goo_price;     //不减回收金额
                $ord_edit_data['ord_plus_minus'] = $virtual_ord_plus_minus; //新正负值
            }
            $ord_edit_data['ord_collection_price'] = $new_collection_price;
            $ord_edit_data['ord_update_time'] = date('Y-m-d H:i:s');
            $ord_res = DB::table('order')
                ->where('ord_id', $find_wor->wor_order_id)
                ->update($ord_edit_data);

            $join_in_wor = true;
        }
        // ord_payment_way 结算方式1.账期 2.现结 3微信 4支付宝
        // 计算出 工单代收金额/应收金额
        $wor_coll_price = 0;
        $wor_price = 0;
        if (!empty($work_good)) {
            // 查询出工单商品
            $work_good = DB::table('work_good')
                ->where('wogo_state', 1)
                ->where('wogo_wor_id', $request['wor_id'])
                ->select('wogo_goo_id', 'wogo_goo_amount', 'wogo_goo_inventory', 'wogo_goo_price', 'wogo_collection_price')
                ->get()
                ->toArray();
            foreach ($work_good as $key => $value) {
                $wor_coll_price += $value->wogo_collection_price; //代收金额
            }
        }

        // 如果是外派工单  加盟店审核
        if ($find_wor->wocl_wor_type == 2 && $find_wor->wocl_join_wor_id != 0) {
            unset($wor_data['wor_pass']);
            unset($wor_data['wor_state']);
            $join_wor_res = true;
            $wocl_data['wocl_join_audit'] = 2;  // 1未审核 2已审核
            $join_wocl_id = DB::table('work_client')
                ->where('wocl_wor_id', $find_wor->wocl_join_wor_id)
                ->update($wocl_data);

            $join_order_id = DB::table('work_order')
                ->where('wor_id', $find_wor->wocl_join_wor_id)
                ->value('wor_order_id');

            // 生成操作记录
            $edit_record = orderLog($user_info, 0, $request['wor_id'], '审核通过工单');
            if ($wor_res && $ord_res && $wogo_res && $wocl_id && $edit_record  && $orgo_res && $goo_state_update && $join_wocl_id && $join_wor_res && $join_in_wor) {
                return ['code'=>200, 'msg'=>'success', 'data'=>'通过成功'];
            } else {
                return ['code'=>500, 'msg'=>'error', 'data'=>'通过失败'];
            }
            // 如果是速电派单
        } elseif ($find_wor->wocl_wor_type == 3) {
            if ($image_change_state == 2) {
                $log_hint = '改图审核通过工单';
            } else {
                $log_hint = '审核通过工单';
            }
            // 生成操作记录
            $edit_record = orderLog($user_info, 0, $request['wor_id'], $log_hint);
            if ($wor_res && $ord_res && $wogo_res && $wocl_id && $edit_record  && $orgo_res && $goo_state_update && $join_in_wor) {
                if (config('apisystem.SYNC_STATE')) {
                    // 如果是速电派单
                    if ($ord_info->ord_type == 3) {
                        $lat = DB::table('lat')
                            ->where('lat_aid', $find_wor->wor_service_adm_id)
                            ->first(['lat_lat', 'lat_lon']);
                        // 查询工单的技师完成时间
                        $orlo_time = DB::table('order_log')
                            ->where('orlo_shop_id', $user_info->adm_shop_id)
                            ->where('orlo_wor_id', $request['wor_id'])
                            ->where('orlo_content', '完成')
                            ->value('orlo_time');

                        $adm_data = DB::table('admin')
                            ->where('adm_id', $find_wor->wor_service_adm_id)
                            ->first(['adm_name', 'adm_phone']);
                        $param['serial_number'] = $ord_info->ord_other_system_number;
                        $param['state'] = 5;
                        $param['ip'] = $param['ip'] = getRealIp($request);
                        $param['line'] = $lat->lat_lat . ',' . $lat->lat_lon;
                        $param['install_name'] = $adm_data->adm_name;
                        $param['install_phone'] = $adm_data->adm_phone;
                        $param['app_achieve_time'] = $orlo_time; //APP完成提交时间
                        $param['time'] = date('Y-m-d H:i:s');
                        $server = config('apisystem.server_name') . '/';
                        $find_image_upload = DB::table('image_upload')
                            ->where('imup_wor_id', $request['wor_id'])
                            ->where('imup_delete', 1)
                            ->select('imup_path', 'imup_image_name')
                            ->get()->toArray();
                        $find_image_upload = json_decode(json_encode($find_image_upload), true);
                        foreach ($find_image_upload as $key => $value) {
                            if ($value['imup_path']) {
                                $find_image_upload[$key]['imup_path'] = $server . $value['imup_path'];
                            }
                        }
                        $param['filePic'] = $find_image_upload; //速电模板图片
                        $param['image_change_state'] = $image_change_state; //工单审核图片更改状态：1未上传新图2重新传图
                        $param['token'] = config('apisystem.sd_token');
                        $url = config('apisystem.sd_server_name') . '/index.php/Supply/installLine';
                        $doPost_res = Common::doPost($param, $url);
                        $doPost_res = json_decode($doPost_res);
                        if ($doPost_res->code != 200) {
                            deleteImage($new_img_delete);
                            return ['code'=>500, 'msg'=>'error', 'data'=>'失败'];
                        }
                        // 上传数据到凭证列表
                        if (config('apiu8cloud.CODE_STARTS') && in_array($user_info->adm_shop_id, config('apiu8cloud.u8cloud_shop'))) {
                            // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
                            $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
                            // 生成凭证单据
                            $vore_data = WorkOrder::voucherReceipts($user_info, $shop_id, 2, $request['wor_id'], $find_wor->wor_number, $find_wor->wor_order_id, $find_wor->wor_order_number, $now_wor_price, $find_wor->wor_recycle_price, $find_wor->wor_collection_price, $total_vouchar_cost, $find_wor->wor_service_type, $find_wor->wor_type, $find_wor->wocl_client_id, $wocl_client_name);
                            if (!$vore_data) {
                                deleteImage($new_img_delete);
                                return ['code'=>500, 'msg'=>'error', 'data'=>'生成凭证单失败'];
                            }
                        }
                    }
                }
                return ['code'=>200, 'msg'=>'success', 'data'=>'通过成功'];
            } else {
                deleteImage($new_img_delete);
                return ['code'=>500, 'msg'=>'error', 'data'=>'通过失败'];
            }
            // 如果是外派工单  总店审核
        } elseif ($find_wor->wocl_wor_type == 2 && $find_wor->wocl_join_wor_id == 0) {
            // 救援单没有商品的情况，这变量就不存在
            if (!isset($subtract)) {
                $subtract = [];
            }
            // 加盟店应收账款
            $join_rece_res = WorkOrder::joinReceivable($request->all(), $user_info, $find_wor, $wor_coll_price, $find_wor->wocl_assign_price, $subtract, $goo_info, $wor_plus_minus);
            $join_wor_res = true;
            $join_wocl_id = true;
        // 门店版城市运营中心派单 门店审核
        } elseif ($find_wor->wocl_wor_type == 5 && $shop_versions == 1) {
            // 工单修改为完成状态
            $update_parwor['wor_update_time'] = date('Y-m-d H:i:s');
            $update_parwor['wor_service_state'] = 6; //修改服务状态为已完成待审核
            $update_parwor['wor_state'] = 8; //修改状态为已完成
            $update_parwor['wor_pass'] = 1; //改为待审核状态
            $sel_paretworid = DB::table('work_client')
                ->where('wocl_join_ord_id', $find_wor->wor_order_id)
                ->value('wocl_wor_id');
            $wocl_data['wocl_join_audit'] = 2;  // 1未审核 2已审核
            $wocl_data['wocl_join_audit'] = 2;  // 1未审核 2已审核
            if ($sel_paretworid) {
                $join_wocl_id = DB::table('work_client')
                    ->where('wocl_wor_id', $sel_paretworid)
                    ->update($wocl_data);
                $save_state = DB::table('work_order')
                    ->where('wor_id', $sel_paretworid)
                    ->update($update_parwor);
            }
            $join_wor_res = true;
            $join_rece_res = true;
        } else {
            $join_wor_res = true;
            $join_wocl_id = true;
            $join_rece_res = true;
        }
        // wocl_collect_state技师代收1是2否  代收金额为0   结算方式为现结
        if ($find_wor->wocl_collect_state == 1 && $find_wor->wor_collection_price == 0 && $ord_info->ord_payment_way == 2) {
            // 生成结款明细
            $acset_id = AccountingSettlement::add(
                $user_info, // [用户信息]
                1, // [单据类型1订单结算2订单账单3工单账单11订单退款12工单代收]
                $find_wor->wor_order_id, // [与单据类型对应的id]
                $find_wor->wor_order_number, // [与单据类型对应的单号]
                $ord_info->ord_type, // [买家类型1门店零售2来往单位]
                $find_wor->wocl_client_id, // [会员/客户id]
                $wocl_client_name, // [来往单位名称]
                $find_wor->wocl_acti_id, // [会计科目id]
                1, // [类型1收入2支出]
                $total_price, // [实际金额](此次的实收金额)
                $total_price, // [合计金额](此次的应收金额)
                0, // [欠收金额](此次结款后还应收金额)
                0, // [抹零金额]
                $request['remark'] ? $request['remark'] : '' //[备注]
            );

            // 3.订单应收
            $ord_bill = ReceivableBill::create(
                $user_info, //用户信息
                1, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $find_wor->wor_order_id, //原始id(订单id)
                $find_wor->wor_order_number, //应收账款单号/原始号(订单编号)
                $ord_info->ord_type, //客户类型：1.门店零售 2.来往单位
                $ord_info->ord_client_id, //会员id/来往单位id
                $wocl_client_name, //来往单位名称
                $genre == 1 ? $total_price : $ord_info->ord_actual_price, //结算金额(应收金额)
                '', //结款时间
                $cli_info->orcl_acc_subject_id, //会计科目id
                $ord_info->ord_state == 1 ? 0 : $total_price, //实际金额(应收金额)
                0, //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                $ord_info->ord_remark,  //备注
                $ord_info->ord_state == 1 ? 0 : $total_price,  //已收金额
                '', //截止时间
                $wor_plus_minus, //金额正负1正   2负值
                1, //显示类型：1订单收款
                1, //是否合并代收：1是2否
                $ord_info->ord_create_time
            );
            // 记录日志
            $log_data['ord_bill'] = $ord_bill;
            $log_data['user_info'] = $user_info;
            $log_data['request'] = $request;
            $log_data['wor_order_number'] = $find_wor->wor_order_number;
            $log_data['wocl_client_name'] = $wocl_client_name;
            $log_data['total_price'] = $total_price;
            $log_data['ord_info'] = $ord_info;
            $log_data['find_wor'] = $find_wor;
            $log_data['wor_plus_minus'] = $wor_plus_minus;
            Common::write_record_log($log_data, 'work_order_log.txt', 'updatePass-ReceivableBill');
            unset($log_data);
            // 生成操作记录
            $edit_record = orderLog($user_info, 0, $request['wor_id'], '审核通过工单');
            if ($wor_res && $ord_res && $wogo_res && $wocl_id && $edit_record && $orgo_res && $goo_state_update && $ord_bill && $acset_id && $join_wor_res && $join_wocl_id && $join_rece_res && $join_in_wor) {
                // 添加新增订单信息的提示
                $inhi_data['inhi_original_adm_id'] = $find_wor->wor_create_id; //原始单号创建人
                $inhi_data['inhi_original_id'] = $request['wor_id']; //原始单id
                $inhi_data['inhi_original_number'] = $find_wor->wor_number; //原始单号
                $inhi_data['inhi_original_state'] = $wor_data['wor_state']; //原始单状态
                $inhi_data['inhi_original_operation'] = '工单审核通过'; //操作
                $inhi_data['inhi_operation_state'] = 15; //操作状态：15工单审核通过
                addInformationHint($user_info, $inhi_data, 2);
                return ['code'=>200, 'msg'=>'success', 'data'=>'通过成功'];
            } else {
                return ['code'=>500, 'msg'=>'error', 'data'=>'通过失败'];
            }
        }
        $request_voucher['find_wocl'] = ''; //用友接口上传凭证使用
        if ($find_wor->wocl_collect_state == 1 || $wor_coll_price > 0) {
            // ord_payment_way 2现结，订单结算方式为现结的，可以生成代收的应收账款
            // 计算出订单 代收金额/应收金额
            // 救援单没有商品的情况，这变量就不存在
            if (!isset($subtract)) {
                $subtract = [];
            } else {
                $ord_coll_price = 0;
                foreach ($subtract as $key => $value) {
                    // $ord_coll_price += $goo_info[$key]->orgo_collection_price * $value; //代收金额
                    $ord_coll_price += $goo_info[$key]->orgo_collection_price; //代收金额
                }
            }

            // 让技师收款，就要在生成结款明细 wocl_collect_state 技师收钱：0未选择1是2否
            $find_wocl = DB::table('work_client')
                ->where('wocl_wor_id', $request['wor_id'])
                ->first(['wocl_client_id', 'wocl_channel_unit', 'wocl_name', 'wocl_acti_id', 'wocl_collect_state']);
            $request_voucher['find_wocl'] = $find_wocl;
            $request_voucher['wor_coll_price'] = $wor_coll_price;
            // 1. 订单代收
            $ord_coll_bill = ReceivableBill::create(
                $user_info, //用户信息
                3, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $find_wor->wor_order_id, //原始id(订单id)
                $find_wor->wor_order_number, //应收账款单号/原始号(订单编号)
                $ord_info->ord_type, //客户类型：1.会员零售 2.来往单位 3.加盟店 4会员零售(工单代收）
                $ord_info->ord_client_id, //会员id/来往单位id
                $wocl_client_name, //来往单位名称
                $new_collection_price, //结算金额(代收金额)
                '', //结款时间
                $cli_info->orcl_acc_subject_id, //会计科目id
                $find_wocl->wocl_collect_state == 1 ? $new_collection_price : 0, //实际金额(未结算:0，已结算：代收金额)
                0, //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                $ord_info->ord_remark,  //备注
                0,  //已收金额
                '', //截止时间
                2, //金额正负1正   2负值
                2, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
                1, //是否合并代收：1是2否
                $ord_info->ord_create_time
            );
            // 记录日志
            $log_data['ord_coll_bill'] = $ord_coll_bill;
            $log_data['user_info'] = $user_info;
            $log_data['request'] = $request;
            $log_data['wor_order_number'] = $find_wor->wor_order_number;
            $log_data['wocl_client_name'] = $wocl_client_name;
            $log_data['ord_info'] = $ord_info;
            $log_data['find_wor'] = $find_wor;
            Common::write_record_log($log_data, 'work_order_log.txt', 'updatePass-ReceivableBill-create订单代收');
            unset($log_data);
            // 虚拟加盟店
            if ($find_wor->wocl_wor_type == 4) {
                $client_type = 7;
            } else {
                $client_type = $ord_info->ord_type;
            }

            // 2 工单代收，生成工单代收应收账款，判断是否让技师收款
            $recr_id = ReceivableBill::create(
                $user_info, //用户信息
                4, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $find_wor->wor_id, //原始id(工单id)
                $find_wor->wor_number, //应收账款单号/原始号(工单编号)
                $find_wor->wocl_wor_type == 2 ? 3 : $client_type, //客户类型：1.门店零售 2.来往单位 3.加盟店 4会员零售(工单代收）
                $find_wor->wocl_wor_type == 2 || $find_wor->wocl_wor_type == 4 ? $find_wor->wor_service_shop_id : $ord_info->ord_client_id, //会员id/来往单位id
                $find_wor->wocl_wor_type == 2 || $find_wor->wocl_wor_type == 4 ? $shop_info->shop_store_name : $wocl_client_name, //来往单位名称
                // $wor_coll_price, //结算金额
                $new_collection_price, //结算金额
                '', //结款时间
                $find_wocl->wocl_acti_id, //会计科目id
                // $find_wocl->wocl_collect_state == 1 ? $wor_coll_price : 0, //实际金额
                $find_wocl->wocl_collect_state == 1 ? $new_collection_price : 0, //实际金额
                0, //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                $request['remark'] ? $request['remark'] : '',  //备注
                0,  //已收金额
                '', //截止时间
                1, //金额正负:1正2负值
                3, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
                2, //是否合并代收：1是2否
                $ord_info->ord_create_time,
                $find_wocl->wocl_collect_state //技师是否收钱：0未选择1是2否
            );
            // 记录日志
            $log_data['recr_id'] = $recr_id;
            $log_data['user_info'] = $user_info;
            $log_data['request'] = $request;
            $log_data['wor_order_number'] = $find_wor->wor_number;
            $log_data['wocl_client_name'] = $find_wor->wocl_wor_type == 2 || $find_wor->wocl_wor_type == 4 ? $shop_info->shop_store_name : $wocl_client_name;
            $log_data['ord_info'] = $ord_info;
            $log_data['find_wor'] = $find_wor;
            Common::write_record_log($log_data, 'work_order_log.txt', 'updatePass-ReceivableBill-create工单代收');
            unset($log_data);

            // 判断是否生成结款明细，让技师收款，就生成结款明细
            if ($find_wocl->wocl_collect_state == 1) {
                // 生成结款明细
                $acset_id = AccountingSettlement::add(
                    $user_info, // [用户信息]
                    12, // [单据类型1订单结算2订单账单3工单账单11订单退款12工单代收]
                    $find_wor->wor_id, // [与单据类型对应的id]
                    $find_wor->wor_number, // [与单据类型对应的单号]
                    $ord_info->ord_type, // [买家类型1门店零售2来往单位]
                    $find_wocl->wocl_client_id, // [会员/客户id]
                    $wocl_client_name, // [来往单位名称]
                    $find_wocl->wocl_acti_id, // [会计科目id]
                    1, // [类型1收入2支出]
                    $new_collection_price, // [实际金额](此次的实收金额)
                    $new_collection_price, // [合计金额](此次的应收金额)
                    0, // [欠收金额](此次结款后还应收金额)
                    0, // [抹零金额]
                    $request['remark'] ? $request['remark'] : '' //[备注]
                );
            } else {
                $acset_id = true;
            }
        } else {
            $ord_coll_bill = true;
            $recr_id = true;
            $acset_id = true;
        }
        // 判断是否应该生成应收账款、结款明细
        // 订单状态为未结算时，可以生成应收账款、结款明细
        if ($ord_info->ord_state == 1) {
            // 3.订单应收
            $ord_bill = ReceivableBill::create(
                $user_info, //用户信息
                3, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $find_wor->wor_order_id, //原始id(订单id)
                $find_wor->wor_order_number, //应收账款单号/原始号(订单编号)
                $ord_info->ord_type, //客户类型：1.门店零售 2.来往单位
                $ord_info->ord_client_id, //会员id/来往单位id
                $wocl_client_name, //来往单位名称
                $genre == 1 && $find_wor->wocl_wor_type != 4 ? abs($now_wor_price) : abs($ord_info->ord_actual_price), //结算金额(应收金额)
                // $genre == 1 ? $find_wor->wocl_assign_price : $ord_info->ord_actual_price, //结算金额(应收金额)
                '', //结款时间
                $cli_info->orcl_acc_subject_id, //会计科目id
                $ord_info->ord_state == 1 ? 0 : $find_wor->wocl_assign_price, //实际金额(应收金额)
                0, //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                $ord_info->ord_remark,  //备注
                $ord_info->ord_state == 1 ? 0 : $find_wor->wocl_assign_price,  //已收金额
                '', //截止时间
                $ord_plus_minus, //金额正负1正   2负值
                $find_wor->wor_service_type == 4 ? 10 : 1, //显示类型：1订单收款 10订单退款
                1, //是否合并代收：1是2否
                $ord_info->ord_create_time
            );
            // 记录日志
            $log_data['ord_bill'] = $ord_bill;
            $log_data['user_info'] = $user_info;
            $log_data['request'] = $request;
            $log_data['wor_order_number'] = $find_wor->wor_order_number;
            $log_data['wocl_client_name'] = $wocl_client_name;
            $log_data['ord_info'] = $ord_info;
            $log_data['find_wor'] = $find_wor;
            $log_data['ord_plus_minus'] = $ord_plus_minus;
            Common::write_record_log($log_data, 'work_order_log.txt', 'updatePass-ReceivableBill-create订单应收');
            unset($log_data);
            // 4.工单应收  工单的销售金额不生成应收账款，加盟店的生成
            if ($shop_info->shop_type == 3 && $find_wor->wocl_wor_type == 2) {
                $wor_bill = ReceivableBill::create(
                    $user_info, //用户信息
                    4, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                    0, //应收账款id
                    $find_wor->wor_id, //原始id(工单id)
                    $find_wor->wor_number, //应收账款单号/原始号(工单编号)
                    3, //客户类型：1.门店零售 2.来往单位3.外派门店（加盟店或总店）
                    $find_wor->wor_service_shop_id, //派单门店id
                    $shop_info->shop_store_name, //派单门店名称
                    $find_wor->wocl_assign_price, //结算金额
                    '', //结款时间
                    $cli_info->orcl_acc_subject_id, //会计科目id
                    $ord_info->ord_state == 1 ? 0 : $find_wor->wocl_assign_price, //实际金额
                    0,  //抹零金额
                    1,  //状态：1.未核销 2.已核销
                    1,  //应收账单id是否是自己 1.不是 2.是
                    $request['remark'] ? $request['remark'] : '',  //备注
                    $ord_info->ord_state == 1 ? 0 : $find_wor->wocl_assign_price,  //已收金额
                    '', //截止时间
                    2, //金额正负1正   2负值
                    4, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
                    1, //是否合并代收：1是2否
                    $ord_info->ord_create_time
                );
            // 虚拟加盟店
            } elseif ($find_wor->wocl_wor_type == 4) {
                $wor_bill = ReceivableBill::create(
                    $user_info, //用户信息
                    4, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                    0, //应收账款id
                    $find_wor->wor_id, //原始id(工单id)
                    $find_wor->wor_number, //应收账款单号/原始号(工单编号)
                    7, //客户类型：1.门店零售 2.来往单位3.外派门店（加盟店或总店）
                    $find_wor->wor_service_shop_id, //派单门店id
                    $shop_info->shop_store_name, //派单门店名称
                    abs($now_wor_price), //结算金额
                    '', //结款时间
                    $cli_info->orcl_acc_subject_id, //会计科目id
                    $ord_info->ord_state == 1 ? 0 : abs($now_wor_price), //实际金额
                    0,  //抹零金额
                    1,  //状态：1.未核销 2.已核销
                    1,  //应收账单id是否是自己 1.不是 2.是
                    $request['remark'] ? $request['remark'] : '',  //备注
                    $ord_info->ord_state == 1 ? 0 : abs($now_wor_price),  //已收金额
                    '', //截止时间
                    $wor_plus_minus, //金额正负1正   2负值
                    4, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
                    1, //是否合并代收：1是2否
                    $ord_info->ord_create_time
                );
            } else {
                $wor_bill = true;
            }
            $goo_state_update = true;
        } else {
            // 订单状态为已结算状态，不生成应收账款
            $wor_bill = true;
            $ord_bill = true;
            $goo_state_update = true;
        }

        // 生成操作记录
        $edit_record = orderLog($user_info, 0, $request['wor_id'], '审核通过工单');

        // 添加备注
        if (!empty($request['remark'])) {
            orderRemark($user_info, $find_wor->wor_order_id, $request['wor_id'], $request['remark'], '工单列表-审核');
        }

        if ($wor_res && $ord_res && $wogo_res && $wocl_id && $edit_record && $ord_bill && $ord_coll_bill && $recr_id && $acset_id && $wor_bill && $goo_state_update && $join_rece_res && $join_in_wor) {
            // 上传数据到凭证列表
            if (config('apiu8cloud.CODE_STARTS') && in_array($user_info->adm_shop_id, config('apiu8cloud.u8cloud_shop'))) {
                // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
                $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
                // 生成凭证单据
                if ($request['wor_service_type'] == '3') { //订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单 7救援单
                    if ($total_vouchar_cost != '0') {
                        $vore_data = WorkOrder::voucherReceipts($user_info, $shop_id, 2, $request['wor_id'], $find_wor->wor_number, $find_wor->wor_order_id, $find_wor->wor_order_number, $now_wor_price, $reduce_total_price, $find_wor->wor_collection_price, $total_vouchar_cost, $find_wor->wor_service_type, $find_wor->wor_type, $find_wor->wocl_client_id, $wocl_client_name);
                        if (!$vore_data) {
                            deleteImage($new_img_delete);
                            return ['code'=>500, 'msg'=>'error', 'data'=>'生成凭证单失败'];
                        }
                    }
                } else {
                    $vore_data = WorkOrder::voucherReceipts($user_info, $shop_id, 2, $request['wor_id'], $find_wor->wor_number, $find_wor->wor_order_id, $find_wor->wor_order_number, $now_wor_price, $reduce_total_price, $find_wor->wor_collection_price, $total_vouchar_cost, $find_wor->wor_service_type, $find_wor->wor_type, $find_wor->wocl_client_id, $wocl_client_name);
                    if (!$vore_data) {
                        deleteImage($new_img_delete);
                        return ['code'=>500, 'msg'=>'error', 'data'=>'生成凭证单失败'];
                    }
                }
            }
            // 增加审核次数
            $order_wor_updatetimes = DB::table('work_order')
                ->where('wor_id', $find_wor->wor_id)
                ->value('wor_audit_times');
            $order_wor_updatetimes += 1;
            $work_order_update['wor_audit_times'] = $order_wor_updatetimes;
            $order_wor_upres = DB::table('work_order')
                ->where('wor_id', $find_wor->wor_id)
                ->update($work_order_update);

            // 添加新增订单信息的提示
            $inhi_data['inhi_original_adm_id'] = $find_wor->wor_create_id; //原始单号创建人
            $inhi_data['inhi_original_id'] = $request['wor_id']; //原始单id
            $inhi_data['inhi_original_number'] = $find_wor->wor_number; //原始单号
            $inhi_data['inhi_original_state'] = $wor_data['wor_state']; //原始单状态
            $inhi_data['inhi_original_operation'] = '工单审核通过'; //操作
            $inhi_data['inhi_operation_state'] = 15; //操作状态：15工单审核通过
            addInformationHint($user_info, $inhi_data, 2);

            // 审核修改回收金额-》高献昌   wogo_goo_type
            $work_goodresult = DB::table('work_good')
                ->where('wogo_state', '<>', 2)
                ->where('wogo_wor_id', $request['wor_id'])
                ->select('wogo_goo_id', 'wogo_state', 'wogo_goo_inventory', 'wogo_ware_id', 'wogo_goo_price', 'wogo_waon_class', 'wogo_goo_amount', 'wogo_is_recycle')
                ->get()->toArray();

            $isrk = 1; //判断是否有入库商品
            foreach ($work_goodresult as $k => $v) {
                if (substr($v->wogo_goo_price, 0, 1) == '-') {
                    $v->wogo_goo_price = substr($v->wogo_goo_price, 1);
                }
                $sjense_in_price = $v->wogo_goo_price / 100; //审核价格
                // 换货
                if ($v->wogo_state == '4') {
                    $enterres = DB::table('enters_sells_saves')
                        ->where('ense_order_number', $find_wor->wor_order_number)
                        ->where('ense_goo_id', $v->wogo_goo_id)
                        ->where('ense_goo_warehouse', $v->wogo_ware_id)
                        ->where('ense_out_in', '2')
                        ->where('ense_type', '12')
                        ->select('ense_id', 'ense_out_price', 'ense_in_price')
                        ->first();
                    $ense_save['ense_out_price'] = $sjense_in_price;
                    $ense_save['ense_out_amount'] = $sjense_in_price * $v->wogo_goo_amount;
                    DB::table('enters_sells_saves')
                        ->where('ense_id', $enterres->ense_id)
                        ->update($ense_save);
                    $isrk = 2;
                // 回收
                } elseif ($v->wogo_state == '3') {
                    $enterres = DB::table('enters_sells_saves')
                        ->where('ense_order_number', $find_wor->wor_order_number)
                        ->where('ense_goo_id', $v->wogo_goo_id)
                        ->where('ense_goo_warehouse', $v->wogo_ware_id)
                        ->where('ense_out_in', '2')
                        ->where('ense_type', '4')
                        ->select('ense_id', 'ense_out_price', 'ense_in_price')
                        ->first();
                    $ense_save['ense_in_price'] = $sjense_in_price;
                    $ense_save['ense_in_amount'] = $sjense_in_price * $v->wogo_goo_amount;
                    DB::table('enters_sells_saves')
                        ->where('ense_id', $enterres->ense_id)
                        ->update($ense_save);
                    $isrk = 2;
                }
                if ($isrk == 2) {
                    // 审核价格与之前不一样
                    if ($sjense_in_price != $enterres->ense_in_price) {
                        $datetime = date('Y-m-d H:i:s');
                        $enterresult = DB::table('enters_sells_saves')
                            ->where('ense_goo_id', $v->wogo_goo_id)
                            ->where('ense_goo_warehouse', $v->wogo_ware_id)
                            ->where(function ($query) use ($datetime) {
                                $query->where('ense_time', '<=', $datetime);
                            })
                            ->orderBy('ense_id', 'desc')
                            ->select('ense_id', 'ense_end_inventory', 'ense_end_price', 'ense_end_amount')
                            ->first();
                        if ($sjense_in_price > $enterres->ense_in_price) {
                            $gopr_price = ($sjense_in_price - $enterres->ense_in_price) * $v->wogo_goo_amount;
                            $ense_edit_data['ense_end_amount'] = $enterresult->ense_end_amount + $gopr_price;
                        } else {
                            $gopr_price = ($enterres->ense_in_price - $sjense_in_price) * $v->wogo_goo_amount;
                            $ense_edit_data['ense_end_amount'] = $enterresult->ense_end_amount - $gopr_price;
                        }
                        if ($enterresult->ense_end_inventory == '0') {
                            $ense_edit_data['ense_end_price'] = '0';
                        } else {
                            $ense_edit_data['ense_end_price'] = $ense_edit_data['ense_end_amount'] / $enterresult->ense_end_inventory;
                        }
                        $ense_eidt_res = DB::table('enters_sells_saves')
                            ->where('ense_id', $enterresult->ense_id)
                            ->update($ense_edit_data);
                    }
                }
            }
            return ['code'=>200, 'msg'=>'success', 'data'=>'通过成功'];
        } else {
            deleteImage($new_img_delete);
            return ['code'=>500, 'msg'=>'error', 'data'=>'通过失败'];
        }
    }

    // 工单审核-旧货回收处理，门店基础版
    private function junkRecycle(
        $user_info,
        $shop_id,
        $verify_data,
        $request,
        $find_wor
    ) {
        $error_message = $verify_data->junkRecycleValidator($request);
        if ($error_message) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message];
        }

        // recycle_state是否回收1是2不回收
        if ($request['recycle_state'] == 2) {
            // 工单审核时，没有回收旧货商品处理
            if ($request['jur_id']) {
                // 如果工单审核时选择不回收商品，APP提交的旧货回收单改为不回收状态
                $update_recycle['jur_state'] = 3; //回收状态 1.未回收 2.已回收 3不回收
                $update_recycle['jur_update_time'] = date("Y-m-d H:i:s"); //更新时间
                $junk_res = DB::table('junk_recycle')
                    ->where('jur_id', $request['jur_id'])
                    ->update($update_recycle);
            } else {
                $junk_res = true;
            }
            if ($junk_res) {
                return ['code'=>200, 'msg'=>'success', 'data'=>'不回收成功'];
            } else {
                return ['code'=>500, 'msg'=>'error', 'data'=>'不回收失败'];
            }
        }

        // 工单审核时，回收旧货商品处理
        if ($request['jur_id']) {
            // 获取回收单数据
            $find_junk = DB::table('junk_recycle')
                ->where('jur_id', $request['jur_id'])
                ->select('jur_number')
                ->first();
            $request['jur_number'] = $find_junk->jur_number;
        }

        if (empty($request['jur_id'])) { //有回收商品，没有回收id
            // 添加回收单
            $recycle_number = 'JH' . rand(100, 999) . date('mdHis') . rand(100000, 999999); // 回收单号
            $request['jur_number'] = $recycle_number;
            // 回收单表
            $recycle['jur_cid'] = $user_info->adm_cid; //公司id
            $recycle['jur_shop_id'] = $user_info->adm_shop_id; //门店id
            $recycle['jur_superior_shop_id'] = $shop_id; //所属总店id
            $recycle['jur_date'] = date("Y-m-d"); //日期
            $recycle['jur_number'] = $recycle_number; //回收单号
            $recycle['jur_wor_id'] = $request['wor_id']; //工单id
            $recycle['jur_wor_number'] = $find_wor->wor_number; //工单号
            $recycle['jur_ord_id'] = $find_wor->wor_order_id; //订单id
            $recycle['jur_ord_order_number'] = $find_wor->wor_order_number; //订单号
            $recycle['jur_source'] = 2; //旧货来源1.旧货收购 2.订单回收
            $recycle['jur_is_mobile'] = 2; //1.移动端添加 2.pc端添加
            $recycle['jur_state'] = 2; //回收状态 1.未回收 2.已回收 3不回收
            $recycle['jur_add_type'] = 3; //新增回收状态1回收入库2审核3已审核
            $recycle['jur_type'] = $find_wor->wor_type; //买家类型 1.门店零售 2.来往单位'
            $recycle['jur_ware_id'] = $request['jur_ware_id'];
            $recycle['jur_waon_class'] = $request['jur_waon_class'];
            $recycle['jur_service_adm_id'] = $find_wor->wor_service_adm_id; //服务技师id
            $recycle['jur_create_adm_id'] = $user_info->adm_id; //创建人id
            $request['jur_id'] = $recycle_id = DB::table('junk_recycle')->insertGetId($recycle);

            // 回收单客户表 根据工单id查询出该工单的客户信息
            $work_client = DB::table('work_client')
                ->where('wocl_wor_id', $request['wor_id'])
                ->first(['wocl_channel_unit', 'wocl_name', 'wocl_phone', 'wocl_client_id']);
            $jur_client['jucl_jur_id'] = $recycle_id; //旧货回收单id
            $jur_client['jucl_channel_unit'] = $work_client->wocl_channel_unit; //渠道单位
            $jur_client['jucl_name'] = $work_client->wocl_name; //客户姓名
            $jur_client['jucl_phone'] = $work_client->wocl_phone; //联系电话
            $jur_client['jucl_client_id'] = $work_client->wocl_client_id; //渠道单位/客户id
            $add_client = DB::table('junk_client')->insertGetId($jur_client);
            if (!$recycle_id || !$add_client) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'旧货商品回收失败！'];
            }
        } else {
            // 1 删除原来收回单id对应的商品数据
            $del_goods = DB::table('junk_goods')
                ->where('jugo_jur_id', $request['jur_id'])
                ->delete();
            if (!$del_goods) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'旧货商品回收失败！'];
            }
        }
        // 获取回收单数据
        $find_junk = DB::table('junk_recycle as jure')
            ->leftJoin('admin as adm', 'adm.adm_id', '=', 'jure.jur_create_adm_id')
            ->where('jur_id', $request['jur_id'])
            ->select('adm_name as jur_create_adm_name', 'jur_number', 'jur_date', 'jur_source', 'jur_amount', 'jur_price', 'jur_wor_id', 'jur_create_adm_id', 'jur_ware_id', 'jur_remark', 'jur_state', 'jur_is_mobile', 'jur_ord_id', 'jur_ord_order_number', 'jur_wor_number', 'jur_service_adm_id', 'jur_type', 'jur_waon_class')
            ->first();
        $request['jur_source'] = $find_junk->jur_source;
        $request['jur_is_mobile'] = $find_junk->jur_is_mobile;
        $request['jur_ord_id'] = $find_wor->wor_order_id;
        $request['jur_ord_order_number'] = $find_wor->wor_order_number;
        // 获取到当前工单的订单信息
        $request['ord_wor_state'] = DB::table('order')
            ->where('ord_id', $find_wor->wor_order_id)
            ->value('ord_wor_state');
        // 查询仓库类型
        $ware_type = DB::table('warehouse')
            ->where('ware_id', $request['jur_ware_id'])
            ->value('ware_type');
        // 旧货回收
        $junk_return = JunkRecycling::junkRecycle(
            $user_info, //用户信息
            $request, //前端传过来的数据
            $find_junk, //旧货回收单的数据
            $ware_type //类型：1固定仓2技师库3移动仓
        );
        // 记录日志
        $log_data['function'] = '旧货回收';
        $log_data['user_info'] = $user_info;
        $log_data['jur_number'] = $request['jur_number'];
        $log_data['request'] = $request;
        Common::write_record_log($log_data, 'pc/RecyclingController.txt', 'recycle');
        return $junk_return;
    }

    /**
     * [salesReturn 工单审核-退回商品处理]
     * @param  [type] $user_info   [用户信息]
     * @param  [type] $verify_data [验证器]
     * @param  [type] $request     [提交数据]
     * @param  [type] $find_wor    [工单数据]
     * @return [type]              [description]
     */
    private function salesReturn(
        $user_info,
        $verify_data,
        $request,
        $find_wor
    ) {
        // 获取回收单数据
        $find_recede = DB::table('recede_recycle as re')
            ->leftjoin('admin as a', 'a.adm_id', '=', 're.rec_create_adm_id')
            ->leftjoin('recede_client as recl', 'recl.recl_rec_id', '=', 're.rec_id')
            ->where('rec_id', $request['rec_id'])
            ->select('rec_number', 'rec_ord_id', 'rec_ord_order_number', 'rec_create_time', 'rec_state', 'rec_amount', 'rec_remark', 'rec_date', 'rec_price', 'rec_mobile_ware_id', 'rec_source_type', 'rec_ware_id', 'adm_name as rec_create_adm_name', 'rec_waon_class', 'rec_id', 'rec_type', 'recl_client_id', 'recl_channel_unit', 'recl_name')
            ->first();
        if (empty($find_recede)) {
            return ['code'=>200, 'msg'=>'success', 'data'=>'退回商品处理成功'];
        }
        // rec_source_type 来源类型1. 售后退货 2. 工单退货(换货单) 3 页面新增 4 (工单号)退货单 5技师退回 6技师拒单 7技师终止 8(订单号)退货单
        if ($find_recede->rec_source_type == 8) {
            // 根据原始单id,查询到订单id
            $find_order = DB::table('order')
                ->where('ord_id', $find_recede->rec_ord_id)
                ->select('ord_id as wor_order_id', 'ord_order_number as wor_order_number', 'ord_type', 'ord_client_id', 'ord_collection_price', 'ord_service_type as wor_service_type', 'ord_actual_price')
                ->first();
        } else {
            // 根据原始单id,查询到订单id
            $find_order = DB::table('work_order')
                ->where('wor_id', $find_recede->rec_ord_id)
                ->select('wor_order_id', 'wor_order_number', 'wor_service_type')
                ->first();
        }
        // 查询仓库类型 类型：1固定仓2技师库3移动仓
        $rec_ware_type = DB::table('warehouse')
            ->where('ware_id', $find_recede->rec_ware_id)
            ->value('ware_type');
        // 商品json数据
        $goo_data = json_decode($request['rego_data'], true);
        if (empty($request['goo_data'])) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'请选择退货入库回收商品！'];
        }

        // 来源类型5技师退回
        if ($find_recede->rec_source_type == 5) {
            // 减少技师库的库存数量
            $recede_return_data = ReturnWarehousing::technicianReduceStock(
                $user_info, //用户信息
                $find_recede, //退换入库数据
                $request //前端传过来的数据
            );
            if ($recede_return_data['code'] == 500) {
                return $recede_return_data;
            }
        }

        // 退货单入库
        $recede_return_data = ReturnWarehousing::returnOrder(
            $user_info, //用户信息
            $find_recede, //退换入库数据
            $request, //前端传过来的数据
            $goo_data,
            $find_order,
            $rec_ware_type
        );
        // 记录日志
        $log_data['user_info'] = $user_info;
        $log_data['rec_number'] = $request['rec_number'];
        $log_data['rec_type'] = '技师退回';
        $log_data['request'] = $request;
        Common::write_record_log($log_data, 'pc/RecedeRecycleController.txt', 'recycle');
        if ($recede_return_data['code'] == 200) {
            return $recede_return_data;
        } else {
            return $recede_return_data;
        }
    }

    // 工单反审核
    public function cancelAudit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkOrderController;
        $error_message = $verify_data->cancelAuditValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 查询信息
        $find_wor = DB::table('work_order as wor')
            ->leftjoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wor.wor_id')
            ->where('wor_id', $request['wor_id'])
            ->select('wor_id', 'wor_number', 'wor_order_id', 'wocl_client_id', 'wor_service_type', 'wor_collection_price', 'wor_order_number', 'wor_state', 'wor_create_id', 'wor_account_state', 'wor_wobi_id', 'wocl_wor_type', 'wor_ware_id')
            ->first();

        if ($find_wor->wor_state != 10) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'该工单不是完成通过状态']);
        }

        if ($find_wor->wor_account_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'该工单已结款，不能反审核！']);
        }
        if (!empty($find_wor->wor_wobi_id)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'此工单已经生成账单，不能进行反审核操作！']);
        }
        // 判断此工单作数订单是否生成账单
        $find_order  = DB::table('order')
            ->where('ord_id', $find_wor->wor_order_id)
            ->where('ord_order_number', $find_wor->wor_order_number)
            ->select('ord_orbi_id', 'ord_state')
            ->first();
        if (!empty($find_order->ord_orbi_id)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'此工单所属订单已经生成账单，不能进行反审核操作！']);
        }
        if ($find_order->ord_state != 1) {
            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;

        // 判断生成的结款明细是否已核对
        $acset_type = 3; //工单账单
        $find_wor_acset  = DB::table('accounting_settlement')
            ->where('acset_adm_cid', $user_info->adm_cid)
            ->where('acset_superior_shop_id', $shop_id)
            ->where('acset_type', $acset_type)
            ->where('acset_original_id', $find_wor->wor_id)
            ->where('acset_original_number', $find_wor->wor_number)
            ->select('acset_state', 'acset_id')
            ->first();
        if (!empty($find_wor_acset) && $find_wor_acset->acset_state == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单代收的结款明细已经核对，不能进行反审核操作！']);
        }
        $acset_type = 9; //订单代收
        $find_ord_acset_collect  = DB::table('accounting_settlement')
            ->where('acset_adm_cid', $user_info->adm_cid)
            ->where('acset_superior_shop_id', $shop_id)
            ->where('acset_type', $acset_type)
            ->where('acset_original_id', $find_wor->wor_order_id)
            ->where('acset_original_number', $find_wor->wor_order_number)
            ->select('acset_state', 'acset_id')
            ->first();
        if (!empty($find_ord_acset_collect) && $find_ord_acset_collect->acset_state == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单代收的结款明细已经核对，不能进行反审核操作！']);
        }
        $acset_type = 1; //订单结算
        $find_ord_acset  = DB::table('accounting_settlement')
            ->where('acset_adm_cid', $user_info->adm_cid)
            ->where('acset_superior_shop_id', $shop_id)
            ->where('acset_type', $acset_type)
            ->where('acset_original_id', $find_wor->wor_order_id)
            ->where('acset_original_number', $find_wor->wor_order_number)
            ->select('acset_state', 'acset_id')
            ->first();
        if (!empty($find_ord_acset) && $find_ord_acset->acset_state == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单的结款明细已经核对，不能进行反审核操作！']);
        }
        $acset_type = 11; //订单退款
        $find_ord_acset_refund  = DB::table('accounting_settlement')
            ->where('acset_adm_cid', $user_info->adm_cid)
            ->where('acset_superior_shop_id', $shop_id)
            ->where('acset_type', $acset_type)
            ->where('acset_original_id', $find_wor->wor_order_id)
            ->where('acset_original_number', $find_wor->wor_order_number)
            ->select('acset_state', 'acset_id')
            ->first();
        if (!empty($find_ord_acset_refund) && $find_ord_acset_refund->acset_state == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单的结款明细已经核对，不能进行反审核操作！']);
        }

        $acset_type = 12; //工单代收
        $find_ord_acset_dai  = DB::table('accounting_settlement')
            ->where('acset_adm_cid', $user_info->adm_cid)
            ->where('acset_superior_shop_id', $shop_id)
            ->where('acset_type', $acset_type)
            ->where('acset_original_id', $find_wor->wor_id)
            ->where('acset_original_number', $find_wor->wor_number)
            ->select('acset_state', 'acset_id')
            ->first();
        if (!empty($find_ord_acset_dai) && $find_ord_acset_dai->acset_state == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单的结款明细已经核对，不能进行反审核操作！']);
        }

        DB::beginTransaction();

        $wor_data['wor_pass'] = 1; //审核：1.待审核 2.合格 3.不合格
        $wor_data['wor_state'] = 8; //待审核/完成待审核
        $wor_data['wor_service_state'] = 6; //6完成待审核
        $wor_data['wor_update_time'] = date('Y-m-d H:i:s');
        $wor_res = DB::table('work_order')
            ->where('wor_id', $request['wor_id'])
            ->update($wor_data);

        $ord_edit_data['ord_wor_state'] = 2; //订单的工单状态1未派工单2服务中3售后中4已完成5无工单
        $ord_edit_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_res = DB::table('order')
            ->where('ord_id', $find_wor->wor_order_id)
            ->update($ord_edit_data);

        // 删除已经生成的订单应收账款
        $rece_order_del = DB::table('receivable_credit')
            ->where('recr_cid', $user_info->adm_cid)
            ->where('recr_shop_superior_id', $shop_id)
            ->where('recr_original_id', $find_wor->wor_order_id)
            ->where('recr_original_number', $find_wor->wor_order_number)
            ->delete();
        // 删除已经生成的工单的应收账款
        $rece_wor_del = DB::table('receivable_credit')
            ->where('recr_cid', $user_info->adm_cid)
            ->where('recr_shop_superior_id', $shop_id)
            ->where('recr_original_id', $find_wor->wor_id)
            ->where('recr_original_number', $find_wor->wor_number)
            ->delete();

        if (!empty($find_ord_acset)) {
            $ord_acset_del = DB::table('accounting_settlement')
                ->where('acset_id', $find_ord_acset->acset_id)->delete();
        } else {
            $ord_acset_del = true;
        }
        if (!empty($find_ord_acset_collect)) {
            $ord_acset_collect_del = DB::table('accounting_settlement')
                ->where('acset_id', $find_ord_acset_collect->acset_id)->delete();
        } else {
            $ord_acset_collect_del = true;
        }

        if (!empty($find_wor_acset)) {
            $wor_acset_del = DB::table('accounting_settlement')
                ->where('acset_id', $find_wor_acset->acset_id)->delete();
        } else {
            $wor_acset_del = true;
        }
        if (!empty($find_ord_acset_refund)) {
            $ord_acset_refund_del = DB::table('accounting_settlement')
                ->where('acset_id', $find_ord_acset_refund->acset_id)->delete();
        } else {
            $ord_acset_refund_del = true;
        }

        if (!empty($find_ord_acset_dai)) {
            $ord_acset_refund_del = DB::table('accounting_settlement')
                ->where('acset_id', $find_ord_acset_dai->acset_id)->delete();
        } else {
            $ord_acset_refund_del = true;
        }

        // 生成操作记录
        $log_record = orderLog($user_info, 0, $request['wor_id'], '工单反审核');

        $find_goods_data = DB::table('work_good')
            ->where('wogo_wor_id', $request['wor_id'])
            ->where('wogo_state', 3)
            ->select('wogo_ware_id', 'wogo_waon_class', 'wogo_goo_id', 'wogo_goo_price', 'wogo_goo_amount')
            ->get()->toArray();
        $goo_ids = array_column($find_goods_data, 'wogo_goo_id');

        if ($wor_res && $rece_order_del && $ord_acset_del && $ord_acset_collect_del && $wor_acset_del  && $ord_acset_refund_del && $log_record) {
            // 判断门店是否使用用友u8财务系统，凭证作废
            if (config('apiu8cloud.CODE_STARTS') && in_array($user_info->adm_shop_id, config('apiu8cloud.u8cloud_shop'))) {
                // 判断当前凭证号是否上传到U8
                $find_vore_data = DB::table('voucher_receipts')
                    ->where('vore_cid', $user_info->adm_cid)
                    ->where('vore_superior_shop_id', $shop_id)
                    ->where('vore_shop_id', $user_info->adm_shop_id)
                    ->where('vore_wor_id', $find_wor->wor_id)
                    ->where('vore_wor_number', $find_wor->wor_number)
                    ->select('vore_state', 'vore_id', 'vore_ord_id', 'vore_ord_number')
                    ->first();
                if (!empty($find_vore_data)) {
                    if ($find_vore_data->vore_state == 1) {
                        // 删除凭证借贷表数据
                        $del_volo_data = DB::table('voucher_loan')
                            ->where('volo_shop_id', $user_info->adm_shop_id)
                            ->where('volo_vore_id', $find_vore_data->vore_id)
                            ->delete();
                        // 根据工单id,删除凭证表相关数据
                        $del_vore_data = DB::table('voucher_receipts')
                            ->where('vore_wor_id', $find_wor->wor_id)
                            ->where('vore_wor_number', $find_wor->wor_number)
                            ->where('vore_state', 1)
                            ->delete();
                        // 删除订单相关
                        $del_volo_data = DB::table('voucher_loan')
                            ->where('volo_shop_id', $user_info->adm_shop_id)
                            ->where('volo_vore_id', $find_vore_data->vore_id)
                            ->delete();
                        // 根据工单id,删除凭证表相关数据
                        $del_vore_data = DB::table('voucher_receipts')
                            ->where('vore_ord_id', $find_wor->wor_order_id)
                            ->where('vore_ord_number', $find_wor->wor_order_number)
                            ->where('vore_state', 1)
                            ->delete();
                    } else {
                        DB::rollBack();
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'该凭证已同步到U8,无法反审核操作']);
                    }
                }
            }

            // 添加新增订单信息的提示
            $inhi_data['inhi_original_adm_id'] = $find_wor->wor_create_id; //原始单号创建人
            $inhi_data['inhi_original_id'] = $find_wor->wor_id; //原始单id
            $inhi_data['inhi_original_number'] = $find_wor->wor_number; //原始单号
            $inhi_data['inhi_original_state'] = $wor_data['wor_state']; //原始单状态
            $inhi_data['inhi_original_operation'] = '工单反审核'; //操作
            $inhi_data['inhi_operation_state'] = 16; //操作状态：16工单反审核
            addInformationHint($user_info, $inhi_data, 2);

            DB::commit();
            Common::addLog($user_info, getRealIp($request), '工单列表', '反审核', $find_wor->wor_number . '成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'反审核成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'反审核失败']);
        }
    }

    // 驳回
    public function reject(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkOrderController;
        $error_message = $verify_data->rejectValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 查询信息
        $find_wor = DB::table('work_order')
            ->where('wor_id', $request['wor_id'])
            ->first();
        // wor_service_state 服务状态：1待接单2已接单3预约4出发5抵达6完成待审核7完成已驳回8完成通过
        if ($find_wor->wor_service_state != 6) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单服务未完成，无法审核驳回']);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        DB::beginTransaction();
        //修改为未完成状态
        $wor_data['wor_pass'] = 3;
        $wor_data['wor_state'] = 9;
        $wor_data['wor_remark'] = $request['remark'];
        $wor_data['wor_actual_recycle_number'] = 0;
        $wor_data['wor_service_state'] = 5;
        $wor_data['wor_update_time'] = date('Y-m-d H:i:s');
        $wor_res = DB::table('work_order')
            ->where('wor_id', $request['wor_id'])
            ->update($wor_data);

        // 6.更改技师最新位置表
        $lat_data['lat_ord_state'] = 4;
        $lat_data['lat_ord_id'] = $find_wor->wor_order_id;
        $lat_data['lat_time'] = date('Y-m-d H:i:s');
        $lat_res = DB::table('lat')
            ->where(['lat_aid' => $find_wor->wor_service_adm_id])
            ->update($lat_data);

        // 5.评价总表 新增/修改数据(总服务单数)
        $is_service_adm = DB::table('evaluate_sum')
            ->where(['evsu_service_adm_id' => $find_wor->wor_service_adm_id])
            ->first();
        if ($is_service_adm) {
            $evaluate_sum = DB::table('evaluate_sum')
                ->where(['evsu_service_adm_id' => $find_wor->wor_service_adm_id])
                ->decrement('evsu_serve_all');
        } else {
            $evaluate_sum = true;
        }

        //工单商品信息
        $work_good = DB::table('work_good')
            ->where('wogo_wor_id', $request['wor_id'])
            ->get()->toArray();
        $work_good = json_decode(json_encode($work_good), true);
        foreach ($work_good as $key => $value) {
            // 换货单的时候，商品退换回收数量
            $rego_recycle_number[$value['wogo_goo_id']] = $value['wogo_actual_recycle_number'];
            //如果有回收商品
            if ($value['wogo_is_recycle'] == 1 && !empty($value['wogo_actual_recycle_number'])) {
                $wogo_is_recycle = 1;
            } else {
                $wogo_is_recycle = 2;
            }
        }

        if ($wogo_is_recycle == 1) {
            //驳回删除旧货回收表里的数据
            $junk_del = DB::table('junk_recycle as jr')
                ->leftjoin('junk_goods as jg', 'jg.jugo_jur_id', '=', 'jr.jur_id')
                ->leftjoin('junk_client as jc', 'jc.jucl_jur_id', '=', 'jr.jur_id')
                ->where('jr.jur_wor_id', $request['wor_id'])
                ->where('jr.jur_state', 1) //1.未回收 2.已回收
                ->delete();
            $wogo_id = DB::table('work_good')
                ->where('wogo_wor_id', $request['wor_id'])
                ->where('wogo_is_recycle', 1)
                ->where('wogo_state', 3)
                ->value('wogo_id');
            if (!empty($wogo_id)) {
                $work_good_del = DB::table('work_good')
                    ->where('wogo_wor_id', $request['wor_id'])
                    ->where('wogo_is_recycle', 1)
                    ->where('wogo_state', 3)
                    ->delete();
            } else {
                $work_good_del = true;
            }
        } else {
            $junk_del = true;
            $work_good_del = true;
        }

        // 4.工单位置连接表：给客户发送的正常状态链接改为完成状态  如果是销售单的话不需要改
        if ($find_wor->wor_service_type == 1) {
            $find_loc = DB::table('location_link')
                ->where([
                    'loc_wor_id' => $request['wor_id'],
                    'loc_state' => 3
                ])
                ->value('loc_id');
            if (!$find_loc) {
                $save_link = true;
            } else {
                $link_state['loc_update_time'] = date('Y-m-d H:i:s');
                $link_state['loc_state'] = 1;
                $save_link = DB::table('location_link')
                    ->where(['loc_wor_id' => $request['wor_id']])
                    ->update($link_state);
            }
        } else {
            $save_link = true;
        }

        //统计工单商品表信息
        $goo_all_fine = 0;
        $goo_all_priority = 0;
        $goo_all_quantity = 0;
        foreach ($work_good as $key => $value) {
            // 商品id
            $goo_id[$key] = $value['wogo_goo_id'];
            $goo_number[$key] = $value['wogo_goo_amount'];
            $goo_inventory[$key] = $value['wogo_goo_inventory'];
            // 商品id所对应的商品数量
            $subtract[$value['wogo_goo_id']] = $value['wogo_goo_amount'];
            // 商品id所对应的出库方式
            $goo_repertory[$value['wogo_goo_id']] = $value['wogo_goo_inventory'];
            // 商品总量
            $goo_all_quantity += $value['wogo_goo_amount'];

            if ($value['wogo_goo_inventory'] == 1) {
                $goo_all_fine += $value['wogo_goo_amount']; //1.良品
            } else {
                $goo_all_priority += $value['wogo_goo_amount']; //2.优先
            }
        }
        // 查询出技师的移动仓
        $ware_id = DB::table('warehouse')
            ->where('ware_type', 2)
            ->where('ware_leader_id', $find_wor->wor_service_adm_id)
            ->value('ware_id');
        // 7.订单类型为退货单 加库存到技师的移动仓 其余减库存
        if ($find_wor->wor_service_type == 4) {

            //判断此仓库是否有此商品
            $warehouse_goods = DB::table('warehouse_goods')
                ->whereIn('wago_goo_id', $goo_id)
                ->where('wago_ware_id', $ware_id)
                ->get(['wago_goo_id', 'wago_stock_number', 'wago_priority_stock_number'])
                ->toArray();
            if (!empty($warehouse_goods)) {
                // 加技师移动仓的库存
                $sql = 'UPDATE `faster_warehouse_goods` SET ';
                $stock_fine_sql = '';
                $stock_priority_sql = '';
                $time_sql = '';
                $ids = '';
                foreach ($goo_id as $key => $value) {
                    // 要更改的商品库存数量
                    if ($goo_repertory[$value] == 1) {
                        // 良品
                        $stock_fine_sql = $stock_fine_sql . ' WHEN ' . $value . ' THEN `wago_stock_number` - ' . $subtract[$value];
                        $stock_priority_sql = $stock_priority_sql . ' WHEN ' . $value . ' THEN `wago_priority_stock_number` - 0';
                    } else {
                        // 优先
                        $stock_priority_sql = $stock_priority_sql . ' WHEN ' . $value . ' THEN `wago_priority_stock_number` - ' . $subtract[$value];
                        $stock_fine_sql = $stock_fine_sql . ' WHEN ' . $value . ' THEN `wago_stock_number` - 0';
                    }
                    // 更改时间
                    $time_sql = $time_sql . ' WHEN ' . $value . ' THEN "' . date('Y-m-d H:i:s') . '"';

                    $ids = $ids . $value . ',';
                    // 删除已更改的商品数据
                    unset($subtract[$value]);
                }
                $sql = $sql . ' `wago_stock_number`=  CASE `wago_goo_id` ' . $stock_fine_sql . ' END,';
                $sql = $sql . ' `wago_priority_stock_number`=  CASE `wago_goo_id` ' . $stock_priority_sql . ' END,';
                $sql = $sql . ' `wago_update_time`=  CASE `wago_goo_id` ' . $time_sql . ' END'; //修改时间
                $sql = $sql . ' WHERE `wago_ware_id` = ' . $ware_id . ' AND `wago_goo_id` IN (' . trim($ids, ',') . ')';

                $save_warehouse_t = DB::update($sql);
            }

            // 加库存总数量
            $subtract_all_t = DB::update('UPDATE `faster_warehouse` SET `ware_all_stock`=`ware_all_stock`-' . $goo_all_fine . ' ,`ware_priority_all_stock`=`ware_priority_all_stock` - ' . $goo_all_priority . ' WHERE `ware_id`=?', [$ware_id]);
        } else {
            $save_warehouse_t = true;
            $subtract_all_t = true;
        }
        if ($find_wor->wor_service_type == 3) {
            // 订单类型为换货单，订单商品减库存，换货商品加库存
            $return_data = Warehouse::rejectExchangeGoods(
                $user_info,
                $ware_id,
                $request['wor_id'],
                $request['wor_number'],
                $rego_recycle_number
            );
            $subtract_all = true;
            $save_warehouse = true;
        } else {
            $warehouse_goods = DB::table('warehouse_goods')
                ->whereIn('wago_goo_id', $goo_id)
                ->where('wago_ware_id', $ware_id)
                ->get(['wago_goo_id', 'wago_stock_number', 'wago_priority_stock_number'])
                ->toArray();
            // 7.2 修改仓库商品表的信息
            $sql = 'UPDATE `faster_warehouse_goods` SET ';
            $stock_fine_sql = '';
            $stock_priority_sql = '';
            $time_sql = '';
            $ids = '';
            foreach ($warehouse_goods as $key => $value) {
                // 要更改的商品库存数量
                if ($goo_repertory[$value->wago_goo_id] == 1) {
                    // 良品
                    $subtract_data = $value->wago_stock_number + $subtract[$value->wago_goo_id];
                    // 更改良品商品库存数量
                    $stock_fine_sql = $stock_fine_sql . ' WHEN ' . $value->wago_goo_id;
                    $stock_fine_sql = $stock_fine_sql . ' THEN ' . $subtract_data;


                    $stock_priority_sql = $stock_priority_sql . ' WHEN ' . $value->wago_goo_id;
                    $stock_priority_sql = $stock_priority_sql . ' THEN ' . $value->wago_priority_stock_number;
                } else {
                    // 优先
                    $subtract_data = $value->wago_priority_stock_number + $subtract[$value->wago_goo_id];

                    // 更改优先商品库存数量
                    $stock_priority_sql = $stock_priority_sql . ' WHEN ' . $value->wago_goo_id;
                    $stock_priority_sql = $stock_priority_sql . ' THEN ' . $subtract_data;

                    $stock_fine_sql = $stock_fine_sql . ' WHEN ' . $value->wago_goo_id;
                    $stock_fine_sql = $stock_fine_sql . ' THEN ' . $value->wago_stock_number;
                }
                // 更改时间
                $time_sql = $time_sql . ' WHEN ' . $value->wago_goo_id . ' THEN "' . date('Y-m-d H:i:s') . '"';
                $ids = $ids . $value->wago_goo_id . ',';
            }

            $sql = $sql . ' `wago_stock_number`=  CASE `wago_goo_id` ' . $stock_fine_sql . ' END,'; //修改回收数量
            $sql = $sql . ' `wago_priority_stock_number`=  CASE `wago_goo_id` ' . $stock_priority_sql . ' END,'; //修改回收数量
            $sql = $sql . ' `wago_update_time`=  CASE `wago_goo_id` ' . $time_sql . ' END'; //修改时间
            $sql = $sql . ' WHERE `wago_ware_id` = ' . $ware_id . ' AND `wago_goo_id` IN (' . trim($ids, ',') . ')';
            $save_warehouse = DB::update($sql);   // 仓库商品表

            // 7.3 减总库存量
            $subtract_all = DB::update('UPDATE `faster_warehouse` SET `ware_all_stock`=`ware_all_stock`+' . $goo_all_fine . ' ,`ware_priority_all_stock`=`ware_priority_all_stock`+ ' . $goo_all_priority . ' WHERE `ware_id`=?', [$ware_id]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 驳回
        $reject_Record = orderLog($user_info, 0, $request['wor_id'], '工单审核驳回');
        // $res= $wor_res .'='. $reject_Record.'='. $subtract_all .'='.  $save_link .'='.  $junk_del .'='.  $work_good_del.'='. $evaluate_sum .'='.  $lat_res .'='. $save_warehouse_t .'='.  $subtract_all_t;
        if ($wor_res && $reject_Record && $subtract_all && $save_link && $junk_del && $work_good_del && $evaluate_sum && $lat_res && $save_warehouse_t && $subtract_all_t) {
            Common::addLog($user_info, getRealIp($request), '工单列表', '驳回', $find_wor->wor_number . '驳回成功');
            DB::commit();
            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->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        //会员零售
        if ($request['unit_type'] == 1) {
            $wor_type = 1;
        }
        //来往单位
        if ($request['unit_type'] == 2) {
            $wor_type = 2;
        }
        $wocl_wor_type = '';
        //虚拟加盟店
        if ($request['unit_type'] == 4) {
            $wocl_wor_type = 4;
        }

        //加盟店
        if ($request['unit_type'] == 5) {
            $wocl_wor_type = 2;
        }

        $search_data = $request->all();
        $data = DB::table('work_order as o')
            ->leftJoin('admin as c', 'c.adm_id', '=', 'o.wor_create_id')
            ->leftJoin('work_client as w', 'w.wocl_wor_id', '=', 'o.wor_id')
            ->where('wor_cid', $user_info->adm_cid)
            ->where('wor_superior_shop_id', $shop_id)
            ->whereIn('wor_state', [10, 14])
            ->where('wor_account_state', 1) //未结算
            ->where(function ($query) use ($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                    $query->whereBetween('wor_create_time', [$search_data['start_time'], $search_data['end_time'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['start_time'])) {
                        $query->where('wor_create_time', '>=', $search_data['start_time']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['end_time'])) {
                            $query->where('wor_create_time', '<=', $search_data['end_time'] . ' 23:59:59');
                        }
                    }
                }
            }) //起止日期
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wobi_id'])) {
                    // 编辑
                    $query->where('wor_wobi_id', $search_data['wobi_id']);
                } else {
                    // 新增
                    $query->where('wor_wobi_id', 0);
                }
            }) //判断是编辑还是新增
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wor_service_shop_id'])) {
                    $query->where('wor_service_shop_id', $search_data['wor_service_shop_id']);
                }
            }) //加盟店
            ->where(function ($query) use ($wocl_wor_type) {
                if (!empty($wocl_wor_type)) {
                    $query->where('wocl_wor_type', $wocl_wor_type);
                }
            }) //加盟店
            ->where(function ($query) use ($search_data) {
                if (isset($search_data['wobi_type']) && in_array($search_data['wobi_type'], [1, 2, 3]) && !empty($search_data['ord_client_id'])) {
                    $query->where('wor_type', $search_data['wobi_type'])
                        ->where('wocl_client_id', $search_data['ord_client_id']);
                } elseif (!empty($search_data['ord_client_id'])) {
                    if ($search_data['wobi_type'] == 4) {
                        $query->where('wocl_wor_type', $search_data['wobi_type'])
                            ->where('wocl_client_id', $search_data['ord_client_id']);
                    } elseif ($search_data['wobi_type'] == 5) {
                        $query->where('wocl_wor_type', 2)
                            ->where('wocl_client_id', $search_data['ord_client_id']);
                    }
                }
            }) //客户id/会员id
            ->orderBy('wor_id', 'desc')
            ->select('wor_id', 'wor_create_time as wor_achieve_time', 'wor_create_id', 'wor_number', 'wor_actual_price', 'adm_name', 'wor_collection_price')
            ->get();
        if (empty($data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'没有可生成的账单']);
        } else {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }
    }

    // 加盟店搜索
    public function searchShop(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();
        $data = DB::table('shop')
            ->where('shop_cid', $user_info->adm_cid)
            ->where('shop_superior_id', $shop_id)
            ->where('shop_type', 3)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('shop_store_name', $search_data['search_data']);
                }
            }) //加盟店名称
            ->orderBy('shop_id', 'desc')
            ->get(['shop_id', 'shop_store_name']);
        if (empty($data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无加盟店']);
        } else {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }
    }

    // 生成账单
    public function createBill(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkOrderController;
        $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 = 'GZ' . 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['wor_id']);
        $add_data['orbi_start_time'] = $request['start_time'];
        $add_data['orbi_end_time'] = $request['end_time'];
        $add_data['orbi_state'] = 3; //待审核
        $add_data['orbi_type'] = $request['wobi_type']; //类型：1门店零售 2渠道单位 3速电账单 4虚拟加盟店 5加盟店

        // 获取客户单位信息
        if ($request['wobi_type'] == 1) {
            // 会员
            $channel = DB::table('member')
                ->where('mem_id', $request['wor_service_shop_id'])
                ->value('mem_name');
        } elseif ($request['wobi_type'] == 2) {
            // 客户单位
            $channel = DB::table('channel_unit')
                ->where('chun_id', $request['wor_service_shop_id'])
                ->value('chun_unit_name');
        } elseif ($request['wobi_type'] == 3) {
            $channel = '速电网单';
        } elseif ($request['wobi_type'] == 4) {
            // 获取来往单位名称
            $vish = DB::table('virtual_shop')
                ->where('vish_id', $request['wor_service_shop_id'])
                ->first(['vish_store_name', 'vish_chun_id']);
            $channel = $vish->vish_store_name;
            $add_data['orbi_channel_unit'] = $vish->vish_chun_id; //客户单位
        } elseif ($request['wobi_type'] == 5) {
            // 获取来往单位名称
            $channel = DB::table('shop')
                ->where('shop_id', $request['wor_service_shop_id'])
                ->value('shop_store_name');
        }
        $add_data['orbi_client_id'] = $request['wor_service_shop_id']; //渠道/客户id/加盟店id
        $add_data['orbi_create_type'] = 3; //工单
        // 获取商品总量  合计金额
        $work_order_info = DB::table('work_order')
            ->whereIn('wor_id', $request['wor_id'])
            ->select('wor_goo_amount', 'wor_actual_price', 'wor_collection_price', 'wor_service_type', 'wor_plus_minus', 'wor_number', 'wor_wobi_id')
            ->get();
        $add_data['orbi_goods_sum'] = 0; // 商品总量
        $add_data['orbi_collection_price'] = 0; // 代收金额
        $goo_price = 0; // 计算金额
        $wor_number_one = [];
        foreach ($work_order_info as $key => $value) {
            if (!empty($value->wor_wobi_id)) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$value->wor_number . '工单已经生成账单,无法生成账单']);
            }
            $add_data['orbi_collection_price'] += $value->wor_collection_price; //代收金额
            if ($request['merge'] == 1 && $value->wor_collection_price > 0) {
                $wor_number_one[] = $value->wor_number;
            }
            $add_data['orbi_goods_sum'] += $value->wor_goo_amount;
            $goo_price += $value->wor_actual_price;
        }

        $add_data['orbi_merge_state'] = $request['merge']; //是否合并代收：1是2否
        if ($add_data['orbi_merge_state'] == 2) {
            // 没有选择合并代收金额，实收金额就是结算金额,代收金额就是0
            $add_data['orbi_collection_price'] = 0;
        } else {
            $goo_price += $add_data['orbi_collection_price']; //实收金额
        }

        if ($goo_price < 0) { //账单结算金额的正负数
            $add_data['orbi_plus_minus'] = 2; //负数
        } else {
            $add_data['orbi_plus_minus'] = 1; //正数
        }
        $add_data['orbi_total_price'] = abs($goo_price); //合计金额
        $add_data['orbi_bill_price'] = abs($goo_price); //结算金额
        $add_data['orbi_actual_price'] = abs($goo_price); //结算金额

        DB::beginTransaction();
        $wobi_id = DB::table('order_bill')->insertGetId($add_data);

        // 有代收金额的在工单表里新增代收金额的数据
        foreach ($request['wor_id'] as $key => $value) {
            $work_order = DB::table('work_order')->where('wor_id', $value)->first(); //工单表
            // 代收金额不为0时 就是有代收的工单 有代收金额的工单id 所对应的工单数据 新增一条一模一样的数据
            if ($work_order->wor_collection_price != 0) {
                //工单客户表
                $work_client = DB::table('work_client')->where('wocl_wor_id', $value)->first();
                //工单商品表
                $work_good = DB::table('work_good')
                    ->where('wogo_wor_id', $value)
                    ->select('wogo_wor_id', 'wogo_goo_id', 'wogo_is_recycle', 'wogo_goo_name', 'wogo_goo_goods_encode', 'wogo_state', 'wogo_goo_price', 'wogo_collection_price', 'wogo_goo_amount', 'wogo_goo_inventory', 'wogo_goo_exchange', 'wogo_actual_recycle_number', 'wogo_remark')
                    ->get();
                $work_good = json_decode(json_encode($work_good), true);


                // 工单表
                $wor_number = Common::workRule($user_info);

                $wor_data['wor_cid'] = $work_order->wor_cid; //所属企业id
                $wor_data['wor_superior_shop_id'] = $work_order->wor_superior_shop_id; //所属总店id
                $wor_data['wor_shop_id'] = $work_order->wor_shop_id; //所属门店id
                $wor_data['wor_create_id'] = $work_order->wor_create_id; //派单人
                $wor_data['wor_number'] = $wor_number; //工单号
                $wor_data['wor_order_id'] = $work_order->wor_order_id; //订单id
                $wor_data['wor_order_number'] = $work_order->wor_order_number; //订单号
                $wor_data['wor_service_shop_id'] = $work_order->wor_service_shop_id; //服务门店id
                $wor_data['wor_service_sepr_id'] = $work_order->wor_service_sepr_id; //服务项目id
                $wor_data['wor_service_adm_id'] = $work_order->wor_service_adm_id; //服务技师id
                $wor_data['wor_service_type'] = $work_order->wor_service_type; //订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单
                $wor_data['wor_service_state'] = $work_order->wor_service_state; //服务状态：1待接单2已接单3预约4出发5抵达6完成待审核7完成已驳回8完成通过9终止
                $wor_data['wor_ware_id'] = $work_order->wor_ware_id; //移动仓id
                $wor_data['wor_state'] = $work_order->wor_state; //1.新订单 2未派单 3待接单/已派单 4.未出发/已接单 5.预约/已预约 6.出发/已出发  7.抵达/抵达 8.待审核/完成待审核 9驳回/完成已驳回 10完成/完成已通过 11终止
                $wor_data['wor_pass'] = $work_order->wor_pass; //审核：1.待审核 2.合格 3.不合格
                $wor_data['wor_type'] = $work_order->wor_type; //订单类型：1门店零售2渠道单位
                $wor_data['wor_appoint_time'] = $work_order->wor_appoint_time; //预约时间
                $wor_data['wor_achieve_time'] = $work_order->wor_achieve_time; //完成时间
                $wor_data['wor_recycle_number'] = $work_order->wor_recycle_number; //工单计划总的旧货回收数量
                $wor_data['wor_actual_recycle_number'] = $work_order->wor_actual_recycle_number; //工单实际的总旧货回收数量
                $wor_data['wor_actual_price'] = $work_order->wor_actual_price; //工单结算金额（单位：分）
                $wor_data['wor_collection_price'] = $work_order->wor_collection_price; //代收金额（单位：分）
                $wor_data['wor_is_recycle'] = $work_order->wor_is_recycle; //1.回收2.不回收
                $wor_data['wor_goo_amount'] = $work_order->wor_goo_amount; //总的商品数量
                $wor_data['wor_img'] = $work_order->wor_img; //提交的图片
                $wor_data['wor_delete'] = $work_order->wor_delete; //是否删除 1.正常工单 2.取消工单
                $wor_data['wor_remark'] = $work_order->wor_remark; //工单备注
                $wor_data['wor_code'] = $work_order->wor_code; //商品条形码
                $wor_data['wor_wobi_id'] = 0; //账单id
                $wor_data['wor_collection_bill'] = 2; //是否代收账单：1正常工单2代收账单
                $wor_id = DB::table('work_order')->insertGetId($wor_data); //工单表

                // 工单商品表
                foreach ($work_good as $key => $value) {
                    $work_good[$key]['wogo_wor_id'] = $wor_id; //工单id
                }
                $add_goods = DB::table('work_good')->insert($work_good);

                // 工单客户表
                $cli_data['wocl_wor_id'] = $wor_id; //工单id
                $cli_data['wocl_client_id'] = $work_client->wocl_client_id; //渠道单位/客户id
                $cli_data['wocl_channel_unit'] = $work_client->wocl_channel_unit; //渠道单位
                $cli_data['wocl_name'] = $work_client->wocl_name; //姓名
                $cli_data['wocl_phone'] = $work_client->wocl_phone; //联系电话
                $cli_data['wocl_car_num'] = $work_client->wocl_car_num; //车牌号
                $cli_data['wocl_address'] = $work_client->wocl_address; //地址
                $cli_data['wocl_longitude'] = $work_client->wocl_longitude; //经度
                $cli_data['wocl_latitude'] = $work_client->wocl_latitude; //纬度
                $cli_data['wocl_chin_type'] = $work_client->wocl_chin_type; //铺货类型：1是铺货 2不是铺货
                $add_client = DB::table('work_client')->insert($cli_data);

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

        // 2.修改工单表 账单id
        $sql = 'UPDATE `faster_work_order` SET ';
        $wor_wobi_id = ''; //账单id
        $update_time = ''; //调货时间
        $wor_state = ''; //工单状态
        $wor_id = "";

        foreach ($request['wor_id'] as $key => $value) {
            // 更改账单id
            $wor_wobi_id = $wor_wobi_id . ' WHEN ' . $value;
            $wor_wobi_id = $wor_wobi_id . ' THEN ' . $wobi_id;
            // 更改结算状态
            $wor_state = $wor_state . ' WHEN ' . $value;
            $wor_state = $wor_state . ' THEN 2';
            // 更改时间
            $update_time = $update_time . ' WHEN ' . $value;
            $update_time = $update_time . ' THEN "' . date('Y-m-d H:i:s') . '"';
            //要更改的工单id
            $wor_id = $wor_id . $value . ',';
        }
        $sql = $sql . ' `wor_wobi_id`= CASE `wor_id` ' . $wor_wobi_id . ' END,';
        $sql = $sql . ' `wor_account_state`= CASE `wor_id` ' . $wor_state . ' END,';
        $sql = $sql . ' `wor_update_time`= CASE `wor_id` ' . $update_time . ' END';
        $sql = $sql . ' WHERE `wor_id` IN (' . trim($wor_id, ',') . ')';
        $save_worke_order = DB::update($sql);

        // 应收账单表新增数据
        // if($request['wobi_type'] == 2){
        //     $analyze = Common::updateAnalyze(
        //         $user_info, //用户信息
        //         $request['wobi_client_id'], //客户单位id
        //         1, //单量
        //         $request['wobi_bill_price'] * 100, //应收账款结算金额
        //         1  //类型1.编辑+ 2.编辑-
        //     );
        // }else{
        //     $analyze = true;
        // }
        if (!empty($wor_number_one)) {
            $recr_edit_data['recr_leisurely_type'] = 1;
            $recr_edit_data['recr_update_time'] = date('Y-m-d H:i:s');
            $update_recr = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $shop_id)
                ->where('recr_type', 4)
                ->where('recr_account_type', 3)
                ->whereIn('recr_original_number', $wor_number_one)
                ->update($recr_edit_data);
        } else {
            $update_recr = true;
        }
        if ($wobi_id && $save_worke_order && $update_recr) {
            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 print(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkOrderController;
        $error_message = $verify_data->infoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 工单数据
        $work_data = DB::table('work_order as a')
            ->leftJoin('work_client as b', 'b.wocl_wor_id', '=', 'a.wor_id')
            ->leftJoin('warehouse as c', 'c.ware_id', '=', 'a.wor_ware_id')
            ->leftJoin('order as d', 'd.ord_id', '=', 'a.wor_order_id')
            ->leftJoin('print_number as prnu', 'prnu.prnu_original_id', '=', 'a.wor_id')
            // ->leftJoin('channel_info as chin', 'chin.chin_chun_id', '=', 'd.ord_client_id')
            ->where('wor_id', $request['wor_id'])
            ->select('wor_id', 'wor_number', 'wor_service_sepr_id', 'wor_service_adm_id', 'wor_code', 'wor_img', 'wor_create_id', 'wor_service_type', 'wor_service_state', 'wor_state', 'wor_type', 'wor_goo_amount', 'wor_remark', 'wor_pass', 'wor_create_time', 'wocl_channel_unit', 'wocl_name', 'wocl_phone', 'wocl_car_num', 'wocl_address', 'ware_name', 'wor_shop_id', 'wor_service_shop_id', 'ord_payment_way', 'ord_state', 'ord_client_id', 'ord_type', 'wor_actual_price', 'wor_collection_price', 'prnu_print_num', 'ware_freight_space', 'wocl_province', 'wocl_city', 'wocl_county', 'wocl_rescue_service_price', 'wocl_rescue_collection_price', 'wocl_assign_price', 'wocl_plus_minus', 'wor_plus_minus', 'wocl_car_vehicle_type', 'wocl_wor_type', 'wor_order_id', 'wor_order_number')
            ->first();

        $data['wor_actual_prices'] = num_to_rmb($work_data->wor_actual_price / 100);
        $work_data->prnu_print_num = empty($work_data->prnu_print_num) ? 0 : $work_data->prnu_print_num;

        // 订单类型如果是客户单位的话 追加客户等级
        if ($work_data->ord_type == 2) {
            $work_data->chin_level = DB::table('channel_info')
                ->where('chin_chun_id', $work_data->ord_client_id)
                ->value('chin_level');
            $chun_data = DB::table('channel_unit')
                ->where('chun_id', $work_data->ord_client_id)
                ->select('chun_adm_id', 'chun_province', 'chun_city', 'chun_county', 'chun_address', 'chun_name', 'chun_phone', 'chun_unit_name')
                ->first();
            $work_data->chun_adm_id = $chun_data->chun_adm_id;
            // 查询客户单位名称
            $work_data->wocl_channel_unit = $chun_data->chun_unit_name;
        } elseif ($work_data->ord_type == 3) {
            $work_data->wocl_channel_unit = '速电快保';
            $work_data->chin_level = "";
            $work_data->chun_adm_id = "";
            $chun_data = [];
        } else {
            $work_data->chin_level = "";
            $work_data->chun_adm_id = "";
            $chun_data = [];
        }

        // 获取采购商(仓库负责人)/创建人
        $adm_id = [
            $work_data->wor_create_id,
            $work_data->wor_service_adm_id,
            $work_data->chun_adm_id
        ];
        $find_admin = DB::table('admin')->whereIn('adm_id', $adm_id)->get(['adm_id', 'adm_name', 'adm_phone']);
        foreach ($find_admin as $key => $value) {
            if ($work_data->wor_create_id == $value->adm_id) {
                $work_data->wor_create_name = $value->adm_name;
            }
            if ($work_data->wor_service_adm_id == $value->adm_id) {
                $work_data->wor_service_adm_name = $value->adm_name;
            }
            if ($work_data->chun_adm_id == $value->adm_id) {
                $work_data->chun_adm_name = $value->adm_name;
                $work_data->chun_adm_phone = $value->adm_phone;
            }
        }
        // 查询服务项目名称
        $sepr_data = DB::table('service_project')
            ->where('sepr_id', $work_data->wor_service_sepr_id)
            ->select('sepr_name', 'sepr_order_money')
            ->first();
        $work_data->wor_service_sepr_name = $sepr_data->sepr_name;
        $work_data->sepr_order_money = $sepr_data->sepr_order_money;

        $work_data->vish_service_shop_name = ''; //虚拟加盟店名称
        // 查询虚拟加盟店服务门店名称
        if ($work_data->wocl_wor_type == 4) {
            $work_data->vish_service_shop_name = DB::table('virtual_shop')
                ->where('vish_id', $work_data->wor_service_shop_id)
                ->value('vish_store_name');
        }

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

        // 获取工单商品数据
        $work_goods = DB::table('work_good as wogo')
            ->leftjoin('goods as goo', 'goo.goo_id', '=', 'wogo.wogo_goo_id')
            ->where('wogo_wor_id', $request['wor_id'])
            ->where('wogo_state', '!=', 2)
            ->select('wogo_goo_id', 'wogo_goo_name', 'wogo_goo_goods_encode', 'wogo_goo_price', 'wogo_state', 'wogo_goo_amount', 'wogo_is_recycle', 'wogo_actual_recycle_number', 'wogo_remark', 'wogo_id', 'wogo_collection_price', 'wogo_recycle_price', 'wogo_recycle_quantity', 'wogo_tem_goo_name as tem_goo_name', 'wogo_assign_price', 'wogo_ware_id', 'goo_unit', 'goo_brse_id', 'goo_bra_name', 'goo_class', 'wogo_orgo_id')
            ->get()->toArray();
        $work_goods = json_decode(json_encode($work_goods), true);
        $work_goods_data = array_column($work_goods, null, 'wogo_orgo_id');
        // 查询系列数据
        $goo_brse_id = array_column($work_goods, 'goo_brse_id');
        $brse_data = DB::table('brand_serie')
            ->whereIn('brse_id', $goo_brse_id)
            ->pluck('brse_name', 'brse_id')
            ->toArray();
        // 查询订单商品仓位数据
        $orgo_id = array_column($work_goods, 'wogo_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_delete', 1)
            ->where('orgf_shop_id', $user_info->adm_shop_id)
            ->where('orgf_ord_id', $work_data->wor_order_id)
            ->whereIn('orgf_orgo_id', $orgo_id)
            ->where('orgf_order_number', $work_data->wor_order_number)
            ->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();
        $new_new_goo_datas = [];
        $find_rego_data = DB::table('recede_recycle')
            ->where(function ($query) use ($work_data) {
                $query->where('rec_ord_order_number', $work_data->wor_order_number)
                    ->orwhere('rec_ord_order_number', $work_data->wor_number);
            })
            ->where(function ($query) use ($work_data) {
                $query->where('rec_ord_id', $work_data->wor_order_id)
                    ->orwhere('rec_ord_id', $work_data->wor_id);
            })
            ->select('rec_id', 'rec_amount', 'rec_source_type')
            ->orderBy('rec_id', 'desc')
            ->first();

        if (!empty($find_rego_data)) {
            if ($find_rego_data->rec_source_type == 5) { //技师退回
                $find_rego_data_res = false;
            } else {
                $find_rego_data_res = true;
            }
        } else {
            $find_rego_data_res = true;
        }
        if ($find_orgf_data && $find_rego_data_res && $user_info->shop_versions == 2) {
            foreach ($find_orgf_data as $key => $value) {
                if (isset($work_goods_data[$value->orgf_orgo_id])) {
                    $wogo_orgf = $work_goods_data[$value->orgf_orgo_id];
                    // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                        if (!empty($wogo_orgf['goo_brse_id'])) {
                            if ($wogo_orgf['goo_class'] == 2) {
                                $wogo_orgf['wogo_goo_name'] = $brse_data[$wogo_orgf['goo_brse_id']] . ' ' . $wogo_orgf['wogo_goo_name'];
                                unset($wogo_orgf['goo_brse_id']);
                            } else {
                                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                    $wogo_orgf['wogo_goo_name'] = $brse_data[$wogo_orgf['goo_brse_id']] . ' ' . $wogo_orgf['wogo_goo_name'];
                                    unset($wogo_orgf['goo_brse_id']);
                                }
                            }
                        }
                    }
                    // 显示品牌名称
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                        if ($wogo_orgf['goo_class'] == 2) {
                            $wogo_orgf['wogo_goo_name'] = $wogo_orgf['goo_bra_name'] . ' ' . $wogo_orgf['wogo_goo_name'];
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $wogo_orgf['wogo_goo_name'] = $wogo_orgf['goo_bra_name'] . ' ' . $wogo_orgf['wogo_goo_name'];
                            }
                        }
                    }
                    $new_goo_data['wogo_goo_id'] = $wogo_orgf['wogo_goo_id'];
                    $new_goo_data['wogo_goo_name'] = $wogo_orgf['wogo_goo_name']; //商品名称
                    $new_goo_data['wogo_goo_goods_encode'] = $wogo_orgf['wogo_goo_goods_encode']; //检索编码
                    $new_goo_data['wogo_goo_price'] = $wogo_orgf['wogo_goo_price']; //商品数量
                    $new_goo_data['wogo_state'] = $wogo_orgf['wogo_state'];
                    $new_goo_data['wogo_goo_amount'] = $value->orgf_goo_quantity;
                    $new_goo_data['wogo_is_recycle'] = $wogo_orgf['wogo_is_recycle'];
                    $new_goo_data['wogo_actual_recycle_number'] = $wogo_orgf['wogo_actual_recycle_number'];
                    $new_goo_data['wogo_remark'] = $wogo_orgf['wogo_remark'];
                    $new_goo_data['wogo_id'] = $wogo_orgf['wogo_id'];
                    $new_goo_data['wogo_collection_price'] = $wogo_orgf['wogo_collection_price'];
                    $new_goo_data['wogo_recycle_price'] = $wogo_orgf['wogo_recycle_price'];
                    $new_goo_data['wogo_recycle_quantity'] = $wogo_orgf['wogo_recycle_quantity'];
                    $new_goo_data['tem_goo_name'] = $wogo_orgf['tem_goo_name'];
                    $new_goo_data['wogo_assign_price'] = $wogo_orgf['wogo_assign_price'];
                    $new_goo_data['goo_unit'] = $wogo_orgf['goo_unit'];
                    $new_goo_data['wogo_wafr_name'] = $value->wafr_name; //仓位
                    $new_goo_data['wogo_freight_space'] = DB::table('warehouse')
                        ->where('ware_id', $wogo_orgf['wogo_ware_id'])
                        ->value('ware_freight_space');
                    $new_new_goo_datas[] = $new_goo_data;
                    unset($new_goo_data);
                }
            }
        } else {
            foreach ($work_goods as $key => $value) {
                $work_goods[$key]['wogo_freight_space'] = DB::table('warehouse')
                    ->where('ware_id', $value['wogo_ware_id'])
                    ->value('ware_freight_space');
                $work_goods[$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) {
                            $work_goods[$key]['wogo_goo_name'] = $brse_data[$value['goo_brse_id']] . ' ' . $value['wogo_goo_name'];
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $work_goods[$key]['wogo_goo_name'] = $brse_data[$value['goo_brse_id']] . ' ' . $value['wogo_goo_name'];
                            }
                        }
                    }
                }
                // 显示品牌名称
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                    if ($value['goo_class'] == 2) {
                        $work_goods[$key]['wogo_goo_name'] = $value['goo_bra_name'] . ' ' . $work_goods[$key]['wogo_goo_name'];
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $work_goods[$key]['wogo_goo_name'] = $value['goo_bra_name'] . ' ' . $work_goods[$key]['wogo_goo_name'];
                        }
                    }
                }
                unset($work_goods[$key]['goo_class']);
                unset($work_goods[$key]['wogo_ware_id']);
                unset($work_goods[$key]['goo_brse_id']);
            }
            $new_new_goo_datas = $work_goods;
        }

        // 判断是否为加盟店账号,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 ($work_data->ord_type == 1) {
            $total_client_price = 0; //会员零售金额为0，不统计应收应付
        } else {
            $total_client_price = ReceivableCredit::queryClientPrice(
                $user_info,
                2, //打印类型：1订单打印2工单打印
                $work_data->wor_type, //客户类型
                $work_data->ord_client_id, //客户id
                $work_data->wocl_wor_type, //单据类型：1系统工单2外派工单3速电派单4虚拟加盟店
                $work_data->wor_service_shop_id //服务门店id，实体加盟店id/虚拟加盟店id
            );
        }

        // 获取公司缓存数据
        $cache_data = DB::table('print_cache')
            ->where('prca_create_adm_id', $user_info->adm_id)
            ->where('prca_superior_shop_id', $shop_id)
            ->where('prca_type', 2)
            ->first(['prca_com_name', 'prca_serve_provider', 'prca_serve_order']);

        $data['wor_data'] = $work_data;
        $data['work_goods'] = $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 printNumber(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkOrderController;
        $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', 2)
            ->where('prnu_original_id', $request['wor_id'])
            ->first(['prnu_id', 'prnu_print_num']);

        $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'] = 2;   //所属类型
        $prnu_data['prnu_original_id'] = $request['wor_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['wor_id'])
                ->update($prnu_data);
        } else {
            $prnu_data['prnu_print_num'] = 1;   //打印次数
            $prnu_res = DB::table('print_number')->insert($prnu_data);
        }

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

        // 保存缓存数据
        $prca_id = DB::table('print_cache')
            ->where('prca_create_adm_id', $user_info->adm_id)
            ->where('prca_superior_shop_id', $shop_id)
            ->where('prca_type', 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'] = 2;
        $prca_data['prca_update_time'] = date('Y-m-d H:i:s');
        if ($prca_id) {
            $prca_res = DB::table('print_cache')->where('prca_id', $prca_id)->update($prca_data);
        } else {
            $prca_data['prca_cid'] = $user_info->adm_cid;
            $prca_data['prca_shop_id'] = $user_info->adm_shop_id;
            $prca_data['prca_superior_shop_id'] = $shop_id;
            $prca_data['prca_create_adm_id'] = $user_info->adm_id;
            $prca_res = DB::table('print_cache')->insert($prca_data);
        }
        if ($prnu_res) {
            DB::commit();
            $wor_number = DB::table('work_order')->where('wor_id', $request['wor_id'])->value('wor_number');
            Common::addLog($user_info, getRealIp($request), '工单列表', '打印', $wor_number . '打印成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'打印成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'打印失败']);
        }
    }

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

        $data = DB::table('work_order as a')
            ->leftJoin('work_client as b', 'b.wocl_wor_id', '=', 'a.wor_id')
            ->leftJoin('work_good as c', 'c.wogo_wor_id', '=', 'a.wor_id')
            ->where('wor_cid', $user_info->adm_cid)
            ->where('wor_superior_shop_id', $shop_ids)
            ->where('wor_delete', 1)
            ->where('wor_collection_bill', 1) //是否代收账单：1正常工单2代收账单
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['adm_name'])) {
                    $query->where('b.adm_name', 'like', '%' . $search_data['adm_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //订单号
                if (!empty($search_data['wor_order_number'])) {
                    $query->where('wor_order_number', 'like', '%' . $search_data['wor_order_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //工单号
                if (!empty($search_data['wor_number'])) {
                    $query->where('wor_number', 'like', '%' . $search_data['wor_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //客户单位
                if (!empty($search_data['wocl_channel_unit'])) {
                    $query->where('wocl_channel_unit', 'like', '%' . $search_data['wocl_channel_unit'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //姓名
                if (!empty($search_data['wocl_name'])) {
                    $query->where('wocl_name', 'like', '%' . $search_data['wocl_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //联系电话
                if (!empty($search_data['wocl_phone'])) {
                    $query->where('wocl_phone', 'like', '%' . $search_data['wocl_phone'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //车牌号
                if (!empty($search_data['wocl_car_num'])) {
                    $query->where('wocl_car_num', 'like', '%' . $search_data['wocl_car_num'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //车型
                if (!empty($search_data['wocl_car_vehicle_type'])) {
                    $query->where('wocl_car_vehicle_type', 'like', '%' . $search_data['wocl_car_vehicle_type'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //订单类型1会员零售2客户单位3速电派单
                if (!empty($search_data['wor_type'])) {
                    $query->where('wor_type', $search_data['wor_type']);
                }
            })
            ->where(function ($query) use ($search_data) { //1.新订单 2未派单 3待接单/已派单 4.未出发/已接单 5.预约/已预约 6.出发/已出发  7.抵达/抵达 8.待审核/完成待审核 9驳回/完成已驳回 10完成/完成已通过 11终止 12锁定13.速电撤销回收
                if (!empty($search_data['wor_state'])) {
                    $query->where('wor_state', $search_data['wor_state']);
                }
            })
            ->where(function ($query) use ($search_data) { //服务技师id
                if (!empty($search_data['wor_service_adm_id'])) {
                    $query->where('wor_service_adm_id', $search_data['wor_service_adm_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //派单人
                if (!empty($search_data['wor_create_id'])) {
                    $query->where('wor_create_id', $search_data['wor_create_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //备注
                if (!empty($search_data['wor_remark'])) {
                    $query->where('wor_remark', 'like', '%' . $search_data['wor_remark'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //订单类型
                if (!empty($search_data['wor_service_type'])) {
                    $query->where('wor_service_type', $search_data['wor_service_type']);
                }
            })
            ->where(function ($query) use ($search_data) { //创建时间/派单时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                    $query->whereBetween('wor_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('wor_create_time', '>=', $search_data['create_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['create_time_end'])) {
                            $query->where('wor_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) { //1系统工单2外派工单
                if (!empty($search_data['wocl_wor_type']) && $search_data['wocl_wor_type'] == 1) {
                    $query->whereIn('wocl_wor_type', [1, 3]);
                } elseif (!empty($search_data['wocl_wor_type'])) {
                    $query->whereIn('wocl_wor_type', [2, 4]);
                }
            })
            ->where(function ($query) use ($search_data) { //1系统工单2外派工单
                if (!empty($search_data['join_type']) && $search_data['join_type'] == 1) {
                    $query->where('wocl_wor_type', 4);
                } elseif (!empty($search_data['join_type'])) {
                    $query->where('wocl_wor_type', 2);
                }
            })
            ->where(function ($query) use ($search_data) { //服务门店id
                if (!empty($search_data['wor_service_shop_id'])) {
                    $query->where('wor_service_shop_id', $search_data['wor_service_shop_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //实际金额区间搜索
                // 如果选择最小钱数并且选择最大钱数
                if (!empty($search_data['min_price']) && !empty($search_data['max_price'])) {
                    $query->whereBetween('wor_actual_price', [$search_data['min_price'], $search_data['max_price']]);
                } else {
                    // 如果选择最小钱数
                    if (!empty($search_data['min_price'])) {
                        $query->where('wor_actual_price', '>=', $search_data['min_price']);
                    } else {
                        // 如果选择最大钱数
                        if (!empty($search_data['max_price'])) {
                            $query->where('wor_actual_price', '<=', $search_data['max_price']);
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) { //金额正负值1正值2负值
                if (!empty($search_data['wor_plus_minus'])) {
                    $query->where('wor_plus_minus', $search_data['wor_plus_minus']);
                }
            })
            ->where(function ($query) use ($search_data) { //服务项目id
                if (!empty($search_data['wor_service_sepr_id'])) {
                    $query->where('wor_service_sepr_id', $search_data['wor_service_sepr_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //客户id/会员id
                if (!empty($search_data['wocl_client_id'])) {
                    $query->where('wocl_client_id', $search_data['wocl_client_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //仓库id
                if (!empty($search_data['wor_ware_id'])) {
                    $query->where('wor_ware_id', $search_data['wor_ware_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //商品检索编码
                if (!empty($search_data['goo_goods_encode'])) {
                    $query->where('wogo_goo_goods_encode', $search_data['goo_goods_encode']);
                }
            })
            ->select('wor_number', 'wor_order_number', 'wor_service_sepr_id', 'wocl_rescue_service_price', 'wor_service_adm_id', 'wor_service_type', 'wor_service_state', 'wor_pass', 'wor_type', 'wogo_goo_name', 'wogo_goo_goods_encode', 'wogo_goo_price', 'wogo_goo_amount', 'wor_goo_amount', 'wor_actual_price', 'wor_remark', 'wor_shop_id', 'wor_create_time', 'wocl_channel_unit', 'wocl_name', 'wocl_phone', 'wocl_car_num', 'wocl_address', 'wogo_state', 'wocl_client_id', 'wocl_wor_type')
            ->orderBy('wor_id', 'desc')
            ->get()->toArray();
        if (!empty($data)) {
            // 将对象转化为数组
            $data = json_decode(json_encode($data), true);
            $wocl_client_id = array_unique(array_column($data, 'wocl_client_id')); //选择的客户id，会员id/单位id
            // 查询客户单位
            $channel = DB::table('channel_unit')
                ->whereIn('chun_id', $wocl_client_id)
                ->where('chun_shop_id', $shop_ids)
                ->where('chun_state', '1')
                ->pluck('chun_unit_name', 'chun_id')
                ->toArray();
            // 查找账号id
            foreach ($data as $key => $value) {
                // 服务项目id
                if ($value['wor_service_sepr_id']) {
                    $sepr_id[] = $value['wor_service_sepr_id'];
                }
                // 服务技师id
                if (isset($value['wor_service_adm_id'])) {
                    $adm_id[] = $value['wor_service_adm_id'];
                } else {
                    $adm_id[] = $value['wor_service_adm_id'];
                }
                // 所属门店id
                if ($value['wor_shop_id']) {
                    $shop_id[] = $value['wor_shop_id'];
                }
            }
            $sepr_id = array_unique($sepr_id);
            // 查找服务项目id对应的名称
            $service_project = DB::table('service_project')
                ->whereIn('sepr_id', $sepr_id)
                ->pluck('sepr_name', 'sepr_id');
            $adm_id = array_unique($adm_id);
            // 查找账号id对应的账号姓名
            $admin = DB::table('admin')
                ->whereIn('adm_id', $adm_id)
                ->pluck('adm_name', 'adm_id');
            $shop_id = array_unique($shop_id);
            // 查找门店id对应的账号姓名
            $shop = DB::table('shop')
                ->whereIn('shop_id', $shop_id)
                ->pluck('shop_store_name', 'shop_id');
            foreach ($data as $key => $value) {
                // wor_service_type订单类型为退货单或wogo_state商品状态3回收的商品4换货商品
                if ($value['wor_service_type'] == 4 || $value['wogo_state'] == 3 || $value['wogo_state'] == 4) {
                    $data[$key]['wogo_goo_price'] = '-' . $value['wogo_goo_price'] / 100;
                } else {
                    $data[$key]['wogo_goo_price'] = $value['wogo_goo_price'] / 100;
                }
                $data[$key]['wor_actual_price'] = $value['wor_actual_price'] / 100; //结算金额
                if ($value['wocl_wor_type'] == 4) {
                    $data[$key]['wor_goo_amount'] = '-' . $value['wor_goo_amount'];
                }
                // 服务项目id
                if ($value['wor_service_sepr_id'] == '0') {
                    $data[$key]['wor_service_sepr_id'] = '';
                } else {
                    $data[$key]['wor_service_sepr_id'] = $service_project[$value['wor_service_sepr_id']];
                }
                $data[$key]['wocl_rescue_service_price'] = $value['wocl_rescue_service_price'] / 100; //服务项目金额
                // 服务技师id
                if (isset($admin[$value['wor_service_adm_id']])) {
                    $data[$key]['wor_service_adm_id'] = $admin[$value['wor_service_adm_id']];
                } else {
                    $data[$key]['wor_service_adm_id'] = '';
                }
                // 门店id
                $data[$key]['wor_shop_id'] = $shop[$value['wor_shop_id']];
                // 服务类型
                if ($value['wor_service_type'] == '1') {
                    $data[$key]['wor_service_type'] = '服务单';
                }
                if ($value['wor_service_type'] == '2') {
                    $data[$key]['wor_service_type'] = '销售单';
                }
                if ($value['wor_service_type'] == '3') {
                    $data[$key]['wor_service_type'] = '换货单';
                }
                if ($value['wor_service_type'] == '4') {
                    $data[$key]['wor_service_type'] = '退货单';
                }
                if ($value['wor_service_type'] == '5') {
                    $data[$key]['wor_service_type'] = '发货单';
                }
                if ($value['wor_service_type'] == '6') {
                    $data[$key]['wor_service_type'] = '结清单';
                }
                if ($value['wor_service_type'] == '7') {
                    $data[$key]['wor_service_type'] = '救援单';
                }
                // 服务状态
                if ($value['wor_service_state'] == '0') {
                    $data[$key]['wor_service_state'] = '';
                }
                if ($value['wor_service_state'] == '1') {
                    $data[$key]['wor_service_state'] = '待接单';
                }
                if ($value['wor_service_state'] == '2') {
                    $data[$key]['wor_service_state'] = '已接单';
                }
                if ($value['wor_service_state'] == '3') {
                    $data[$key]['wor_service_state'] = '预约';
                }
                if ($value['wor_service_state'] == '4') {
                    $data[$key]['wor_service_state'] = '出发';
                }
                if ($value['wor_service_state'] == '5') {
                    $data[$key]['wor_service_state'] = '抵达';
                }
                if ($value['wor_service_state'] == '6') {
                    $data[$key]['wor_service_state'] = '完成待审核';
                }
                if ($value['wor_service_state'] == '8') {
                    $data[$key]['wor_service_state'] = '完成通过';
                }
                if ($value['wor_service_state'] == '9') {
                    $data[$key]['wor_service_state'] = '终止';
                }
                if ($value['wor_service_state'] == '10') {
                    $data[$key]['wor_service_state'] = '锁定';
                }
                if ($value['wor_service_state'] == '11') {
                    $data[$key]['wor_service_state'] = '撤销';
                }
                // 审核状态
                if ($value['wor_pass'] == 1) {
                    $data[$key]['wor_pass'] = '待审核';
                }
                if ($value['wor_pass'] == 2) {
                    $data[$key]['wor_pass'] = '合格';
                }
                if ($value['wor_pass'] == 3) {
                    $data[$key]['wor_pass'] = '不合格';
                }
                if ($value['wor_pass'] == 4) {
                    $data[$key]['wor_pass'] = '系统锁定';
                }
                if ($value['wor_pass'] == 5) {
                    $data[$key]['wor_pass'] = '速电锁定';
                }
                if ($value['wor_pass'] == 6) {
                    $data[$key]['wor_pass'] = '第三方锁定';
                }
                if ($value['wor_pass'] == 7) {
                    $data[$key]['wor_pass'] = '等待速电审核';
                }
                if ($value['wor_pass'] == 8) {
                    $data[$key]['wor_pass'] = '等待加盟店审核';
                }
                if ($value['wor_pass'] == 9) {
                    $data[$key]['wor_pass'] = '等待总店审核';
                }
                if ($value['wor_pass'] == 10) {
                    $data[$key]['wor_pass'] = '审核改单';
                }
                if ($value['wor_pass'] == 11) {
                    $data[$key]['wor_pass'] = '等待速电审核';
                }
                // 订单类型
                if ($value['wor_type'] == 1) {
                    $data[$key]['wor_type'] = '会员零售';
                } elseif ($value['wor_type'] == 2) {
                    $data[$key]['wor_type'] = '客户单位';
                } elseif ($value['wor_type'] == 3) {
                    $data[$key]['wor_type'] = '速电派单';
                }
                // 客户单位名称
                if (isset($channel[$value['wocl_client_id']])) {
                    $data[$key]['wocl_client_id'] = $channel[$value['wocl_client_id']];
                } else {
                    if ($value['wocl_wor_type'] == 3) {
                        $data[$key]['wocl_client_id'] = '速电快保';
                    } else {
                        $data[$key]['wocl_client_id'] = $value['wocl_channel_unit'];
                    }
                }
                // 商品编号
                $data[$key]['wogo_goo_goods_encode'] = "\t" . $value['wogo_goo_goods_encode'];
                unset($data[$key]['wogo_state']);
                unset($data[$key]['wocl_wor_type']);
            }
        } 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(10000, 99999) . '.xls'; //
        // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
        $streamFilename = $pathName . '/' . $streamFileRand;

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

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

    // 行驶路线
    public function runningRoute(Request $request)
    {
        // 使用验证器 验证数据
        $verify_data = new VerifyWorkOrderController;
        $error_message = $verify_data->runningRouteValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>$error_message, 'data'=>'{}']);
        }
        // $wocl_wor = DB::table('work_client')
        //     ->where('wocl_wor_id',$request['wor_id'])
        //     ->first(['wocl_wor_type']);
        if ($request['wor_service_adm_id'] == 0) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'无技师无法查看路径']);
        }
        // 获取当前服务技师的公司id
        $adm_cid = DB::table('admin')
            ->where('adm_id', $request['wor_service_adm_id'])
            ->value('adm_cid');

        // 获取当前年月
        $now_time = substr(date("Ym"), -4);

        $table_name = DB::table('table_link')
            ->where([
                'tab_codeid' => '5000' . $adm_cid,
                'tab_yemo' => $now_time,
            ])
            ->value('tab_table_name');
        // 获取技师当前工单出发之后和抵达的经纬度
        $state = [3, 4]; //订单服务状态：1空闲2预约3出发4抵达5完成
        $locaion = DB::table($table_name . '_location')
            ->where([
                'loc_ord_id' => $request['wor_id'],
                'loc_adm_id' => $request['wor_service_adm_id'],
            ])
            ->where('loc_longitude', '>', 0)
            ->whereIn('loc_ord_state', $state)
            ->orderBy('loc_id', 'asc')
            ->select('loc_id', 'loc_longitude', 'loc_latitude', 'loc_speed', 'loc_bearing', 'loc_time')
            ->get();
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$locaion]);
    }

    // 催单
    public function reminder(Request $request)
    {
        // 使用验证器 验证数据
        $verify_data = new VerifyWorkOrderController;
        $error_message = $verify_data->reminderValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'data'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $old_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;

        $wore_data['wore_cid'] = $user_info->adm_cid;
        $wore_data['wore_superior_shop_id'] = $shop_id;
        $wore_data['wore_shop_id'] = $user_info->adm_shop_id;
        $wore_data['wore_wor_id'] = $request['wor_id'];
        $wore_data['wore_wor_number'] = $request['wor_number'];
        $wore_data['wore_service_adm_id'] = $request['wor_service_adm_id'];
        $wore_data['wore_reminder_time'] = date('Y-m-d H:i:s');

        DB::beginTransaction();

        // 判断该单号有没有催单,没有就新增,否则就加次数
        $wore_id = DB::table('work_reminder')
            ->where('wore_wor_id', $request['wor_id'])
            ->where('wore_wor_number', $request['wor_number'])
            ->value('wore_id');
        if ($wore_id) {
            $wore_res = DB::table('work_reminder')
                ->where('wore_id', $wore_id)
                ->increment('wore_reminder_count', 1);
        } else {
            $wore_res = DB::table('work_reminder')->insert($wore_data);
        }
        // 门店被催单
        $find_wor = DB::table('work_order as wo')
            ->leftJoin('order_client as oc', 'oc.orcl_ord_id', '=', 'wo.wor_order_id')
            ->leftJoin('work_client as wc', 'wo.wor_id', '=', 'wc.wocl_wor_id')
            ->where('wor_id', $request['wor_id'])
            ->select('wor_order_id', 'orcl_shipment_party', 'wocl_join_ord_id')
            ->first();
        // 城市运营中心催单门店 添加订单催单
        if ($find_wor->orcl_shipment_party == 5 && !empty($find_wor->wocl_join_ord_id)) {
            $find_shop_ord = DB::table('order')
                ->where('ord_id', $find_wor->wocl_join_ord_id)
                ->select('ord_state', 'ord_id', 'ord_cid', 'ord_shop_id', 'ord_order_number', 'ord_create_id', 'ord_superior_shop_id')
                ->first();
            $find_superior_shop_id = DB::table('shop')
                ->where('shop_id', $find_shop_ord->ord_shop_id)
                ->value('shop_superior_id');
            $user_info->adm_shop_superior_id = $find_superior_shop_id;
            $cityreminder_res = $this->cityreminder($find_shop_ord, $user_info);
            if ($cityreminder_res['code'] == 200) {
                DB::commit();
                Common::addLog($old_user_info, getRealIp($request), '工单列表', '催单', $request['wor_number'] . '催单成功');
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'催单成功']);
            } else {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'催单失败']);
            }
        }

        // 生成操作记录
        $log_res = orderLog($user_info, 0, $request['wor_id'], '催单');
        if ($wore_res && $log_res) {
            $adm_phone =  DB::table('admin')
                ->where('adm_id', $request['wor_service_adm_id'])
                ->value('adm_phone');
            $push_name['alias'][] = $adm_phone; //发送对象
            $result_push = pushMessage($push_name, '您有工单：' . $request['wor_number'] . ' 被催单', 2);
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '工单列表', '催单', $request['wor_number'] . '催单成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'催单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'催单失败']);
        }
    }

    // 催单【门店基础版】
    private function cityreminder($find_shop_ord, $user_info)
    {
        $orre_data['orre_cid'] = $find_shop_ord->ord_cid;
        $orre_data['orre_superior_shop_id'] = $find_shop_ord->ord_superior_shop_id;
        $orre_data['orre_shop_id'] = $find_shop_ord->ord_shop_id;
        $orre_data['orre_order_id'] = $find_shop_ord->ord_id;
        $orre_data['orre_order_number'] = $find_shop_ord->ord_order_number;
        $orre_data['orre_state'] = 1;
        $orre_data['orre_reminder_time'] = date('Y-m-d H:i:s');
        $orre_res = DB::table('order_reminder')->insert($orre_data);
        // 生成操作记录
        $log_res = orderLog($user_info, 0, $find_shop_ord->ord_id, '催单');
        if ($log_res && $orre_res) {
            //城市运营中心催单门店 信息的提示
            $user_info->adm_shop_id = $find_shop_ord->ord_shop_id;
            $inhi_data['inhi_original_adm_id'] = $find_shop_ord->ord_create_id; //原始单号创建人
            $inhi_data['inhi_original_id'] = $find_shop_ord->ord_id; //原始单id
            $inhi_data['inhi_original_number'] = $find_shop_ord->ord_order_number; //原始单号
            $inhi_data['inhi_original_state'] = $find_shop_ord->ord_state; //原始单状态
            $inhi_data['inhi_original_operation'] = '城市运营中心催单'; //操作
            $inhi_data['inhi_operation_state'] = 25; //操作状态：24城市运营中心催单
            addInformationHint($user_info, $inhi_data, 1);

            return ['code'=>200, 'msg'=>'success', 'data'=>'催单成功'];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>'催单失败'];
        }
    }

    // 总店改单加盟店审核通过
    public function changePass(Request $request)
    {
        // 使用验证器 验证数据
        $verify_data = new VerifyWorkOrderController;
        $error_message = $verify_data->changePassValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>$error_message, 'data'=>'{}']);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        if ($request['type'] == 1) {
            //要改成的商品
            $data['new_good_edit'] = DB::table('work_good_edit')
                ->where('wged_order_id', $request['ord_id'])
                ->get(['wged_goo_name', 'wged_goo_goods_encode', 'wged_goo_type', 'wged_state', 'wged_goo_price', 'wged_collection_price', 'wged_goo_amount', 'wged_goo_inventory']);
            $data['new_good_edit'] = json_decode(json_encode($data['new_good_edit']), true);
            if (!empty($data['new_good_edit'])) {
                //改单之前的商品
                $data['old_good_edit'] = DB::table('order_goods')
                    ->where('orgo_ord_id', $request['ord_id'])
                    ->get(['orgo_goo_name', 'orgo_goo_goods_encode', 'orgo_goo_type', 'orgo_state', 'orgo_goo_price', 'orgo_collection_price', 'orgo_goo_quantity', 'orgo_goo_inventory']);
            } else {
                $data['old_good_edit'] = [];
            }
            $data['new_client_edit'] = DB::table('work_client_edit')
                ->where('wced_order_id', $request['ord_id'])
                ->get(['wced_name', 'wced_phone', 'wced_car_num', 'wced_province', 'wced_city', 'wced_county', 'wced_address']);
            $data['new_client_edit'] = json_decode(json_encode($data['new_client_edit']), true);
            if (!empty($data['new_client_edit'])) {
                $data['old_client_edit'] = DB::table('order_client')
                    ->where('orcl_ord_id', $request['ord_id'])
                    ->get(['orcl_name', 'orcl_phone', 'orcl_car_num', 'orcl_province', 'orcl_city', 'orcl_county', 'orcl_address']);
            } else {
                $data['old_client_edit'] = [];
            }
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }

        // 查询工单信息
        $wor_data = DB::table('order as o')
            ->leftjoin('work_order as wo', 'o.ord_id', '=', 'wo.wor_order_id')
            ->where('ord_id', $request['ord_id'])
            ->select('wor_number', 'wor_create_id', 'wor_service_type', 'wor_service_sepr_id', 'wor_state', 'wor_service_state', 'wor_pass', 'wor_service_adm_id', 'wor_service_shop_id', 'wor_ware_id', 'wor_remark', 'wor_type', 'ord_state', 'ord_type', 'ord_other_system_number', 'wor_id', 'ord_cid', 'ord_superior_shop_id', 'ord_shop_id', 'ord_order_state', 'ord_id', 'ord_order_number')
            ->first();
        // 判断工单是否存在
        if (empty($wor_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'未找到此订单']);
        }
        // 结算状态1未结算2已结算3已核销4已收款
        if ($wor_data->ord_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已结算，无法审核！']);
        }
        DB::beginTransaction();
        //加盟店订单
        $join_wor_id = DB::table('order_client')
            ->where('orcl_ord_id', $request['ord_id'])
            ->value('orcl_join_wor_id');
        $wged_info = DB::table('work_client_edit')
            ->where('wced_wor_id', $join_wor_id)
            ->first();
        $wged_data = DB::table('work_good_edit')
            ->where('wged_wor_id', $join_wor_id)
            ->get();
        $wged_data = json_decode(json_encode($wged_data), true);
        $wged_info = json_decode(json_encode($wged_info), true);
        if (empty($wged_data) && empty($wged_info)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'数据错误']);
        }
        if (!empty($wged_info)) {
            $delete_eidt = DB::table('work_client_edit')
                ->where('wced_wor_id', $join_wor_id)
                ->delete();
        }
        if (!empty($wged_data)) {
            $delete_eidt = DB::table('work_good_edit')
                ->where('wged_wor_id', $join_wor_id)
                ->delete();
        }
        $join_order_data = DB::table('work_order')
            ->where('wor_id', $join_wor_id)
            ->first(['wor_order_id', 'wor_order_number']);

        if (!empty($wged_info)) {
            //订单数据
            $orcl_info['orcl_name']  = $wged_info['wced_name'];
            $orcl_info['orcl_phone']  = $wged_info['wced_phone'];
            $orcl_info['orcl_car_num']  = $wged_info['wced_car_num'];
            $orcl_info['orcl_province']  = $wged_info['wced_province'];
            $orcl_info['orcl_city']  = $wged_info['wced_city'];
            $orcl_info['orcl_county']  = $wged_info['wced_county'];
            $orcl_info['orcl_address']  = $wged_info['wced_address'];
            if (!empty($wged_info['wced_collect_state'])) {
                $orcl_info['orcl_collect_state'] = $wged_info['wced_collect_state'];
            }
            //加盟店订单
            $ord_client_res = DB::table('order_client')
                ->where('orcl_ord_id', $request['ord_id'])
                ->update($orcl_info);

            $wocl_info['wocl_name']  = $wged_info['wced_name'];
            $wocl_info['wocl_phone']  = $wged_info['wced_phone'];
            $wocl_info['wocl_car_num']  = $wged_info['wced_car_num'];
            $wocl_info['wocl_province']  = $wged_info['wced_province'];
            $wocl_info['wocl_city']  = $wged_info['wced_city'];
            $wocl_info['wocl_county']  = $wged_info['wced_county'];
            $wocl_info['wocl_address']  = $wged_info['wced_address'];
            if (!empty($wor_data->wor_id)) {
                //加盟店工单
                $work_client_res = DB::table('work_client')
                    ->where('wor_id', $wor_data->wor_id)
                    ->update($wocl_info);
            } else {
                $work_client_res = true;
            }

            // 总店订单
            $join_ord_client_res = DB::table('order_client')
                ->where('orcl_ord_id', $join_order_data->wor_order_id)
                ->update($orcl_info);

            // 总店工单
            $join_order_res = DB::table('work_client')
                ->where('wor_id', $join_wor_id)
                ->update($wocl_info);
        } else {
            $ord_client_res = true;
            $work_client_res = true;
            $join_ord_client_res = true;
            $join_order_res = true;
        }

        if (!empty($wged_data)) {
            $orgo = [];
            foreach ($wged_data as $key => $value) {
                //订单商品数据
                $orgo[$key]['orgo_ord_id'] = $request['ord_id'];
                $orgo[$key]['orgo_order_number'] = $wor_data->ord_order_number;
                $orgo[$key]['orgo_ware_id'] = $value['wged_ware_id'];
                $orgo[$key]['orgo_waon_class'] = $value['wged_waon_class'];
                $orgo[$key]['orgo_goo_id'] = $value['wged_goo_id'];
                $orgo[$key]['orgo_is_recycle'] = $value['wged_is_recycle'];
                $orgo[$key]['orgo_goo_name'] = $value['wged_goo_name'];
                $orgo[$key]['orgo_goo_goods_encode'] = $value['wged_goo_goods_encode'];
                $orgo[$key]['orgo_goo_type'] = $value['wged_goo_type'];
                $orgo[$key]['orgo_state'] = $value['wged_state'];
                $orgo[$key]['orgo_goo_inventory'] = $value['wged_goo_inventory'];
                $orgo[$key]['orgo_recycle_quantity'] = $value['wged_recycle_quantity'];

                //订单商品数据
                $join_orgo[$key]['orgo_ord_id'] = $join_order_data->wor_order_id;
                $join_orgo[$key]['orgo_order_number'] = $join_order_data->wor_order_number;
                $join_orgo[$key]['orgo_ware_id'] = $value['wged_ware_id'];
                $join_orgo[$key]['orgo_waon_class'] = $value['wged_waon_class'];
                $join_orgo[$key]['orgo_goo_id'] = $value['wged_goo_id'];
                $join_orgo[$key]['orgo_is_recycle'] = $value['wged_is_recycle'];
                $join_orgo[$key]['orgo_goo_name'] = $value['wged_goo_name'];
                $join_orgo[$key]['orgo_goo_goods_encode'] = $value['wged_goo_goods_encode'];
                $join_orgo[$key]['orgo_goo_type'] = $value['wged_goo_type'];
                $join_orgo[$key]['orgo_state'] = $value['wged_state'];
                $join_orgo[$key]['orgo_goo_inventory'] = $value['wged_goo_inventory'];
                $join_orgo[$key]['orgo_recycle_quantity'] = $value['wged_recycle_quantity'];

                //订单商品数据
                $wogo[$key]['wogo_wor_id'] = $join_wor_id;
                $wogo[$key]['wogo_ware_id'] = $value['wged_ware_id'];
                $wogo[$key]['wogo_waon_class'] = $value['wged_waon_class'];
                $wogo[$key]['wogo_goo_id'] = $value['wged_goo_id'];
                $wogo[$key]['wogo_is_recycle'] = $value['wged_is_recycle'];
                $wogo[$key]['wogo_goo_name'] = $value['wged_goo_name'];
                $wogo[$key]['wogo_goo_goods_encode'] = $value['wged_goo_goods_encode'];
                $wogo[$key]['wogo_goo_type'] = $value['wged_goo_type'];
                $wogo[$key]['wogo_state'] = $value['wged_state'];
                $wogo[$key]['wogo_goo_inventory'] = $value['wged_goo_inventory'];
                $wogo[$key]['wogo_recycle_quantity'] = $value['wged_recycle_quantity'];
            }
            //加盟店订单商品数据添加
            $orgo_delete = DB::table('order_goods')
                ->where('orgo_ord_id', $wor_data->ord_id)
                ->delete();
            $orgo_insert = DB::table('order_goods')
                ->where('orgo_ord_id', $wor_data->ord_id)
                ->insert($orgo);
            //总店审核
            $join_work_delete = DB::table('work_good')
                ->where('wogo_wor_id', $join_wor_id)
                ->delete();
            $join_work_insert = DB::table('work_good')
                ->where('wogo_wor_id', $join_wor_id)
                ->insert($wogo);
            //总店订单商品数据添加
            $join_orgo_delete = DB::table('order_goods')
                ->where('orgo_ord_id', $join_order_data->wor_order_id)
                ->delete();
            $join_orgo_insert = DB::table('order_goods')
                ->where('orgo_ord_id', $join_order_data->wor_order_id)
                ->insert($join_orgo);
        } else {
            $orgo_delete = true;
            $orgo_insert = true;
            $join_work_delete = true;
            $join_work_insert = true;
            $join_orgo_delete = true;
            $join_orgo_insert = true;
        }

        if (!empty($wged_info)) {
            //订单客户数据
            $orcl['orcl_name'] = $wged_info['wced_name'];
            $orcl['orcl_phone'] = $wged_info['wced_phone'];
            $orcl['orcl_province'] = $wged_info['wced_province'];
            $orcl['orcl_city'] = $wged_info['wced_city'];
            $orcl['orcl_county'] = $wged_info['wced_county'];
            $orcl['orcl_address'] = $wged_info['wced_address'];
            $orcl_update = DB::table('order_client')
                ->where('orcl_ord_id', $wor_data->ord_id)
                ->update($orcl);
        } else {
            $orcl_update = true;
        }

        // 如果没有工单信息说明只修改了订单
        if (empty($wor_data->wor_id)) {
            //取消锁定
            $lock_return = Common::publicOrderLock(2, 4, $request['ord_id']);

            if ($lock_return && $orgo_delete && $orgo_insert && $join_work_delete && $join_work_insert && $join_orgo_delete && $join_orgo_insert && $orcl_update && $delete_eidt && $ord_client_res && $work_client_res && $join_ord_client_res && $join_order_res) {
                orderLog($user_info, $wor_data->ord_id, 0, '加盟店审核通过');
                orderLog($user_info, 0, $join_order_data->wor_order_id, '加盟店审核通过');
                DB::commit();
                return response()->json(['code'=>200, 'msg'=>'error', 'data'=>'审核成功！']);
            } else {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'审核失败']);
            }
        }

        // 处理提交的商品数据
        $goo_all_price = 0; //商品总金额
        $goo_all_quantity = 0; //商品总数量
        $goo_all_collection = 0; //总的代收金额
        $recycle_number = 0; //工单计划总的旧货回收数量
        $recycle_price = 0; //工单计划总的旧货回收金额
        $wor_is_recycle = 2; //是否回收：1.回收2.不回收

        $del_wogo_id = [];
        $del_goo_id = [];
        $del_is_recycle = [];
        $del_goo_amount = [];
        $del_goo_inventory = [];
        $del_goo_price = [];
        $del_collection_price = [];
        $add_goo_id = [];
        $add_goo_inventory = [];
        $add_goo_is_recycle = [];
        $add_goo_price = [];
        $add_goo_amount = [];
        $add_goo_collection_price = [];
        $add_goo_name = [];
        $add_goo_goods_encode = [];
        $add_goo_data = [];

        foreach ($wged_data as $key => $value) {
            // 判断是否有删除的商品 wogo_state 商品状态1.正常 2.删除
            if ($value['wged_state'] == 2) {
                // 改单时删除的商品信息
                // $del_wogo_id[] = $value->wged_goo_id; //删除的商品工单主键id
                $del_goo_id[] = $value['wged_goo_id']; //删除的商品id
                $del_is_recycle[] = $value['wged_is_recycle']; //删除的商品是否回收
                $del_goo_amount[$value['wged_goo_id']] = $value['wged_goo_amount']; //删除的商品数量
                $del_goo_inventory[$value['wged_goo_id']] =  $value['wged_goo_inventory']; //删除的商品出库类型1.良品 2.优先
                $del_goo_price[$value['wged_goo_id']] = $value['wged_goo_price']; //删除的商品金额
                $del_collection_price[$value['wged_goo_id']] = $value['wged_collection_price']; //删除的商品代收金额
            } else {
                // 需要保存的商品数据，包括新添加的商品，更改的商品
                // 没有被删除的都计算到  工单结算金额内
                $goo_all_price += $value['wged_goo_price'] * $value['wged_goo_amount'];
                // 没有被删除的都计算到  总的商品数量内
                $goo_all_quantity += $value['wged_goo_amount'];
                // 没有被删除的都计算到  代收金额，代收金额不乘以数量
                $goo_all_collection += $value['wged_collection_price'];

                // 没有被删除的都计算到  工单计划总的旧货回收数量
                if ($value['wged_is_recycle'] == 1) {
                    // 回收商品
                    $wor_is_recycle = 1; //是否回收：1.回收2.不回收
                    $recycle_number += $value['wged_recycle_quantity']; //回收总数量
                    $recycle_price += $value['wged_recycle_quantity'] * $value['wged_recycle_price']; //回收总金额
                }

                // 组合发货单商品表数据
                $dego_goo_data[$key]['digo_wago_class'] = $value['wged_waon_class'];
                $dego_goo_data[$key]['digo_goo_id'] = $value['wged_goo_id'];
                $dego_goo_data[$key]['digo_goo_price'] = $value['wged_goo_price'] * 100;
                $dego_goo_data[$key]['digo_goo_quantity'] =
                    $value['wged_goo_amount'];
                $dego_goo_data[$key]['digo_is_recycle'] = $value['wged_is_recycle'];
                $dego_goo_data[$key]['digo_goo_inventory'] = $value['wged_goo_inventory'];
                $dego_goo_data[$key]['digo_goo_name'] = $value['wged_goo_name'];
                $dego_goo_data[$key]['digo_goo_goods_encode'] = $value['wged_goo_goods_encode'];
                $dego_goo_data[$key]['digo_goo_type'] = $value['wged_goo_type'];

                // 组合仓库商品改变的数据
                $ware_goo_id[$key] = $value['wged_goo_id']; //商品id
                $ware_goo_number[$value['wged_goo_id']] = $value['wged_goo_amount']; //商品数量
                $ware_goo_inventory[$value['wged_goo_id']] = $value['wged_goo_inventory']; //商品出库方式1.良品 2.优先
                $ware_goo_wago_class[$value['wged_goo_id']] = $value['wged_waon_class']; //商品仓库类别

                // 判断是否有新增的商品
                if ($value['wged_wogo_id'] == 0) {
                    // 工单商品主键id为0的，说明是新添加的商品
                    $add_goo_id[] = $value['wged_goo_id']; //新增商品的id
                    $add_goo_inventory[] = $value['wged_goo_inventory']; //商品出库方式1.良品 2优先
                    $add_goo_is_recycle[] = $value['wged_is_recycle']; //新增商品的是否回收
                    $add_goo_price[] = $value['wged_goo_price']; //新增商品的售价
                    $add_goo_amount[] = $value['wged_goo_amount']; //新增商品的数量
                    $add_goo_collection_price[] = $value['wged_collection_price']; //新增商品的代收金额
                    $add_goo_name[] = $value['wged_goo_name']; //新增商品名称
                    $add_goo_goods_encode[] = $value['wged_goo_goods_encode']; //新增商品的检索编码
                    $add_goo_type[] = $value['wged_goo_type']; //新增商品类型

                    $find_goods_data = DB::table('goods')
                        ->where('goo_id', $value['wged_goo_id'])
                        ->first(['goo_ampere_hour']);

                    $add_goo_data['waon_class'][$value['wged_goo_id']] = $value['wged_waon_class']; //新增仓库类别
                    $add_goo_data['recycle_price'][$value['wged_goo_id']] = $value['wged_recycle_price']; //新增回收金额
                    $add_goo_data['recycle_quantity'][$value['wged_goo_id']] = $value['wged_recycle_quantity']; //新增回收数量
                    $add_goo_data['goo_state'][$value['wged_goo_id']] = $value['wged_state']; //新增商品状态
                    $add_goo_data['goo_type'][$value['wged_goo_id']] = $value['wged_goo_type']; //新增商品类型
                    $add_goo_data['goo_name'][$value['wged_goo_id']] = $value['wged_goo_name']; //新增商品名称
                    $add_goo_data['goo_goods_encode'][$value['wged_goo_id']] = $value['wged_goo_goods_encode']; //新增商品的检索编码
                    $add_goo_data['goo_amount'][$value['wged_goo_id']] = $value['wged_goo_amount']; //新增商品的数量
                    $add_goo_data['goo_price'][$value['wged_goo_id']] = $value['wged_goo_price']; //新增商品的售价
                    $add_goo_data['goo_is_recycle'][$value['wged_goo_id']] = $value['wged_is_recycle']; //新增商品的是否回收
                    $add_goo_data['goo_inventory'][$value['wged_goo_id']] = $value['wged_goo_inventory']; //商品出库方式1.良品 2优先
                    $add_goo_data['goo_collection_price'][$value['wged_goo_id']] = $value['wged_collection_price']; //新增商品的代收金额
                    $add_goo_data['goo_ampere_hour'][$value['wged_goo_id']] = $find_goods_data->goo_ampere_hour; //新增的商品安时数
                }
            }
        }
        $workOrder = new workOrder;
        $dibi_return = $workOrder->editDispatchBill(
            $user_info, //用户信息
            $shop_id, //总店id
            $wor_data->wor_id, //工单id
            $wor_data, //工单数据
            $wged_info['wced_service_adm_id'], //改单的服务技师id
            $goo_all_quantity, //改单的商品总数量
            $dego_goo_data, //改单的发货单商品数据
            $ware_goo_id, //改单的商品id
            $ware_goo_number, //改单的商品数量：商品id=>商品数量
            $ware_goo_inventory, //改单的出库类型：商品id=>出库类型
            $ware_goo_wago_class, //改单的仓库类别：商品id=>仓库类别
            $add_goo_id, //改单添加的商品
            $add_goo_is_recycle, //改单添加的商品回收类型
            $add_goo_price, //改单添加的商品售价
            $add_goo_amount, //改单添加的商品数量
            $add_goo_inventory, //改单添加的商品出库类型
            $add_goo_name, //改单添加的商品名称
            $add_goo_goods_encode //改单添加的商品检索编码
        );
        if ($dibi_return['code'] == 500) {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'审核失败']);
        }

        //客户信息
        $ord_client = DB::table('order_client')
            ->where('orcl_ord_id', $wor_data->ord_id)
            ->first(['orcl_channel_unit', 'orcl_name', 'orcl_phone', 'orcl_id']);

        // 获取到当前工单的订单信息
        $ord_info = DB::table('order')
            ->where('ord_id', $wor_data->ord_id)
            ->first(['ord_client_id']);

        $request['wor_service_adm_id'] = $wged_info['wced_service_adm_id'];
        $request['wor_id'] = $wor_data->wor_id;
        $request['wor_service_sepr_id'] = $wor_data->wor_service_sepr_id;
        $request['wocl_collect_state'] = $wged_info['wced_collect_state'];

        // 2. 处理工单数据
        $wor_return = $workOrder->editWorkData(
            $user_info,
            $request,
            $wor_data,
            $ord_info,
            $ord_client,
            $del_wogo_id,
            $del_goo_id,
            $del_goo_price,
            $del_goo_amount,
            $add_goo_id,
            $add_goo_is_recycle,
            $add_goo_price,
            $add_goo_amount,
            $add_goo_collection_price,
            $add_goo_inventory,
            $goo_all_price,
            $recycle_number,
            $wor_is_recycle,
            $goo_all_quantity,
            $goo_all_collection,
            $add_goo_data
        );
        if ($wor_return['code'] == 500) {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'审核失败']);
        }
        // 解锁
        $lock_return = $this->editLockUnlock($user_info, $wor_data->wor_id, 1);
        if ($lock_return['code'] == 500) {
            return response()->json($lock_return);
        }
        if ($wged_res && $orcl_update && $delete_eidt && $orgo_delete && $orgo_insert && $join_work_delete && $join_work_insert && $join_orgo_delete && $join_orgo_insert && $ord_client_res && $work_client_res && $join_ord_client_res && $join_order_res) {
            orderLog($user_info, $wor_data->ord_id, 0, '加盟店审核通过');
            orderLog($user_info, 0, $wor_data->wor_id, '加盟店审核通过');
            Common::addLog($user_info, getRealIp($request), '订单列表', '审核', '审核通过总店改单请求' . $wor_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 changeReject(Request $request)
    {
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $verify_data = new VerifyWorkOrderController;
        $error_message = $verify_data->headChangePassValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>$error_message, 'data'=>'{}']);
        }

        $user_info = Common::getUserInfo($request['api_token']);
        $wor_id = DB::table('work_client_edit')
            ->where('wced_order_id', $request['ord_id'])
            ->value('wced_wor_id');
        if (!empty($wor_id)) {
            $wced_res = DB::table('work_client_edit')
                ->where('wced_order_id', $request['ord_id'])
                ->delete();
        } else {
            $wced_res = true;
        }

        $wor_id = DB::table('work_good_edit')
            ->where('wged_order_id', $request['ord_id'])
            ->value('wged_wor_id');
        if (!empty($wor_id)) {
            $wged_res = DB::table('work_good_edit')
                ->where('wged_order_id', $request['ord_id'])
                ->delete();
        } else {
            $wged_res = true;
        }
        // 解锁
        $lock_return = $this->editLockUnlock($user_info, $wor_id, 1);
        if ($lock_return['code'] == 500) {
            return response()->json($lock_return);
        }
        orderLog($user_info, $request['ord_id'], 0, '审核驳回');
        orderLog($user_info, 0, $wor_id, '审核驳回');

        if ($lock_return && $wced_res && $wged_res) {
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'error', 'data'=>'审核驳回成功！']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'审核驳回失败']);
        }
    }

    // 加盟店改单总店审核通过
    public function headChangePass(Request $request)
    {
        // 使用验证器 验证数据
        $verify_data = new VerifyWorkOrderController;
        $error_message = $verify_data->headChangePassValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>$error_message, 'data'=>'{}']);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if ($request['type'] == 1) {
            //要改成的商品
            $data['new_good_edit'] = DB::table('work_good_edit')
                ->where('wged_wor_id', $request['wor_id'])
                ->get(['wged_goo_name', 'wged_goo_goods_encode', 'wged_goo_type', 'wged_state', 'wged_goo_price', 'wged_collection_price', 'wged_goo_amount', 'wged_goo_inventory']);
            $data['new_good_edit'] = json_decode(json_encode($data['new_good_edit']), true);
            if (!empty($data['new_good_edit'])) {
                //改单之前的商品
                $data['old_good_edit'] = DB::table('work_good')
                    ->where('wogo_wor_id', $request['wor_id'])
                    ->get(['wogo_goo_name', 'wogo_goo_goods_encode', 'wogo_goo_type', 'wogo_state', 'wogo_goo_price', 'wogo_collection_price', 'wogo_goo_amount', 'wogo_goo_inventory']);
            } else {
                $data['old_good_edit'] = [];
            }
            $data['new_client_edit'] = DB::table('work_client_edit')
                ->where('wced_wor_id', $request['wor_id'])
                ->get(['wced_name', 'wced_phone', 'wced_car_num', 'wced_province', 'wced_city', 'wced_county', 'wced_address']);
            $data['new_client_edit'] = json_decode(json_encode($data['new_client_edit']), true);
            if (!empty($data['new_client_edit'])) {
                $data['old_client_edit'] = DB::table('work_client')
                    ->where('wocl_wor_id', $request['wor_id'])
                    ->get(['wocl_name', 'wocl_phone', 'wocl_car_num', 'wocl_province', 'wocl_city', 'wocl_county', 'wocl_address']);
            } else {
                $data['old_client_edit'] = [];
            }
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }

        // 查询工单信息
        $wor_data = DB::table('work_order as wo')
            ->leftjoin('order as o', 'o.ord_id', '=', 'wo.wor_order_id')
            ->where('wor_id', $request['wor_id'])
            ->select('wor_number', 'wor_create_id', 'wor_service_type', 'wor_service_sepr_id', 'wor_state', 'wor_service_state', 'wor_pass', 'wor_service_adm_id', 'wor_service_shop_id', 'wor_ware_id', 'wor_remark', 'wor_type', 'ord_state', 'ord_type', 'ord_other_system_number', 'wor_id', 'ord_cid', 'ord_superior_shop_id', 'ord_shop_id', 'ord_order_state', 'ord_id', 'ord_order_number')
            ->first();
        // 判断工单是否存在
        if (empty($wor_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'未找到此订单']);
        }
        DB::beginTransaction();
        //加盟店订单
        $join_ord_id = DB::table('work_client')
            ->where('wocl_wor_id', $request['wor_id'])
            ->value('wocl_join_ord_id');
        $wged_info = DB::table('work_client_edit')
            ->where('wced_wor_id', $request['wor_id'])
            ->first();
        $wged_data = DB::table('work_good_edit')
            ->where('wged_wor_id', $request['wor_id'])
            ->get();
        $wged_data = json_decode(json_encode($wged_data), true);
        $wged_info = json_decode(json_encode($wged_info), true);
        if (empty($wged_data) && empty($wged_info)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'数据错误']);
        }
        if (!empty($wged_info)) {
            $delete_eidt = DB::table('work_client_edit')
                ->where('wced_wor_id', $request['wor_id'])
                ->delete();
        }
        if (!empty($wged_data)) {
            $delete_eidt = DB::table('work_good_edit')
                ->where('wged_wor_id', $request['wor_id'])
                ->delete();
        }
        $join_order_data = DB::table('order')
            ->where('wor_id', $join_ord_id)
            ->first(['ord_id', 'ord_order_number']);

        if (!empty($wged_info)) {
            //订单数据
            $orcl_info['orcl_name']  = $wged_info['wced_name'];
            $orcl_info['orcl_phone']  = $wged_info['wced_phone'];
            $orcl_info['orcl_car_num']  = $wged_info['wced_car_num'];
            $orcl_info['orcl_province']  = $wged_info['wced_province'];
            $orcl_info['orcl_city']  = $wged_info['wced_city'];
            $orcl_info['orcl_county']  = $wged_info['wced_county'];
            $orcl_info['orcl_address']  = $wged_info['wced_address'];
            if (!empty($wged_info['wced_collect_state'])) {
                $orcl_info['orcl_collect_state'] = $wged_info['wced_collect_state'];
            }
            //总店订单
            $ord_client_res = DB::table('order_client')
                ->where('orcl_ord_id', $wor_data->ord_id)
                ->update($orcl_info);

            $wocl_info['wocl_name']  = $wged_info['wced_name'];
            $wocl_info['wocl_phone']  = $wged_info['wced_phone'];
            $wocl_info['wocl_car_num']  = $wged_info['wced_car_num'];
            $wocl_info['wocl_province']  = $wged_info['wced_province'];
            $wocl_info['wocl_city']  = $wged_info['wced_city'];
            $wocl_info['wocl_county']  = $wged_info['wced_county'];
            $wocl_info['wocl_address']  = $wged_info['wced_address'];
            $work_client_res = DB::table('work_client')
                ->where('wor_id', $wor_data->wor_id)
                ->update($wocl_info);

            // 加盟店订单
            $join_ord_client_res = DB::table('order_client')
                ->where('orcl_ord_id', $join_order_data->ord_id)
                ->update($orcl_info);

            $join_wor_id = DB::table('work_order')
                ->where('wor_order_id', $join_order_data->ord_id)
                ->value('wor_id');

            // 加盟店工单
            $join_order_res = DB::table('work_client')
                ->where('wocl_wor_id', $join_wor_id)
                ->update($wocl_info);
        } else {
            $ord_client_res = true;
            $work_client_res = true;
            $join_ord_client_res = true;
            $join_order_res = true;
        }

        if (!empty($wged_data)) {
            $orgo = [];
            foreach ($wged_data as $key => $value) {
                //订单商品数据
                $orgo[$key]['orgo_ord_id'] = $wor_data->ord_id;
                $orgo[$key]['orgo_order_number'] = $wor_data->ord_order_number;
                $orgo[$key]['orgo_ware_id'] = $value['wged_ware_id'];
                $orgo[$key]['orgo_waon_class'] = $value['wged_waon_class'];
                $orgo[$key]['orgo_goo_id'] = $value['wged_goo_id'];
                $orgo[$key]['orgo_is_recycle'] = $value['wged_is_recycle'];
                $orgo[$key]['orgo_goo_name'] = $value['wged_goo_name'];
                $orgo[$key]['orgo_goo_goods_encode'] = $value['wged_goo_goods_encode'];
                $orgo[$key]['orgo_goo_type'] = $value['wged_goo_type'];
                $orgo[$key]['orgo_state'] = $value['wged_state'];
                $orgo[$key]['orgo_goo_inventory'] = $value['wged_goo_inventory'];
                $orgo[$key]['orgo_recycle_quantity'] = $value['wged_recycle_quantity'];

                //订单商品数据
                $join_orgo[$key]['orgo_ord_id'] = $join_order_data->ord_id;
                $join_orgo[$key]['orgo_order_number'] = $join_order_data->ord_order_number;
                $join_orgo[$key]['orgo_ware_id'] = $value['wged_ware_id'];
                $join_orgo[$key]['orgo_waon_class'] = $value['wged_waon_class'];
                $join_orgo[$key]['orgo_goo_id'] = $value['wged_goo_id'];
                $join_orgo[$key]['orgo_is_recycle'] = $value['wged_is_recycle'];
                $join_orgo[$key]['orgo_goo_name'] = $value['wged_goo_name'];
                $join_orgo[$key]['orgo_goo_goods_encode'] = $value['wged_goo_goods_encode'];
                $join_orgo[$key]['orgo_goo_type'] = $value['wged_goo_type'];
                $join_orgo[$key]['orgo_state'] = $value['wged_state'];
                $join_orgo[$key]['orgo_goo_inventory'] = $value['wged_goo_inventory'];
                $join_orgo[$key]['orgo_recycle_quantity'] = $value['wged_recycle_quantity'];

                //订单商品数据
                $wogo[$key]['wogo_wor_id'] = $join_wor_id;
                $wogo[$key]['wogo_ware_id'] = $value['wged_ware_id'];
                $wogo[$key]['wogo_waon_class'] = $value['wged_waon_class'];
                $wogo[$key]['wogo_goo_id'] = $value['wged_goo_id'];
                $wogo[$key]['wogo_is_recycle'] = $value['wged_is_recycle'];
                $wogo[$key]['wogo_goo_name'] = $value['wged_goo_name'];
                $wogo[$key]['wogo_goo_goods_encode'] = $value['wged_goo_goods_encode'];
                $wogo[$key]['wogo_goo_type'] = $value['wged_goo_type'];
                $wogo[$key]['wogo_state'] = $value['wged_state'];
                $wogo[$key]['wogo_goo_inventory'] = $value['wged_goo_inventory'];
                $wogo[$key]['wogo_recycle_quantity'] = $value['wged_recycle_quantity'];
            }
            //总店订单商品数据添加
            $orgo_delete = DB::table('order_goods')
                ->where('orgo_ord_id', $wor_data->ord_id)
                ->delete();
            $orgo_insert = DB::table('order_goods')
                ->where('orgo_ord_id', $wor_data->ord_id)
                ->insert($orgo);
            //加盟店数据
            $join_work_delete = DB::table('work_good')
                ->where('wogo_wor_id', $join_wor_id)
                ->delete();
            $join_work_insert = DB::table('work_good')
                ->where('wogo_wor_id', $join_wor_id)
                ->insert($wogo);
            //加盟店订单商品数据添加
            $join_orgo_delete = DB::table('order_goods')
                ->where('orgo_ord_id', $join_order_data->ord_id)
                ->delete();
            $join_orgo_insert = DB::table('order_goods')
                ->where('orgo_ord_id', $join_order_data->ord_id)
                ->insert($join_orgo);
        } else {
            $orgo_delete = true;
            $orgo_insert = true;
            $join_work_delete = true;
            $join_work_insert = true;
            $join_orgo_delete = true;
            $join_orgo_insert = true;
        }

        // 处理提交的商品数据
        $goo_all_price = 0; //商品总金额
        $goo_all_quantity = 0; //商品总数量
        $goo_all_collection = 0; //总的代收金额
        $recycle_number = 0; //工单计划总的旧货回收数量
        $recycle_price = 0; //工单计划总的旧货回收金额
        $wor_is_recycle = 2; //是否回收：1.回收2.不回收

        $del_wogo_id = [];
        $del_goo_id = [];
        $del_is_recycle = [];
        $del_goo_amount = [];
        $del_goo_inventory = [];
        $del_goo_price = [];
        $del_collection_price = [];
        $add_goo_id = [];
        $add_goo_inventory = [];
        $add_goo_is_recycle = [];
        $add_goo_price = [];
        $add_goo_amount = [];
        $add_goo_collection_price = [];
        $add_goo_name = [];
        $add_goo_goods_encode = [];
        $add_goo_data = [];

        foreach ($wged_data as $key => $value) {
            // 判断是否有删除的商品 wogo_state 商品状态1.正常 2.删除
            if ($value['wged_state'] == 2) {
                // 改单时删除的商品信息
                // $del_wogo_id[] = $value->wged_goo_id; //删除的商品工单主键id
                $del_goo_id[] = $value['wged_goo_id']; //删除的商品id
                $del_is_recycle[] = $value['wged_is_recycle']; //删除的商品是否回收
                $del_goo_amount[$value['wged_goo_id']] = $value['wged_goo_amount']; //删除的商品数量
                $del_goo_inventory[$value['wged_goo_id']] =  $value['wged_goo_inventory']; //删除的商品出库类型1.良品 2.优先
                $del_goo_price[$value['wged_goo_id']] = $value['wged_goo_price']; //删除的商品金额
                $del_collection_price[$value['wged_goo_id']] = $value['wged_collection_price']; //删除的商品代收金额
            } else {
                // 需要保存的商品数据，包括新添加的商品，更改的商品
                // 没有被删除的都计算到  工单结算金额内
                $goo_all_price += $value['wged_goo_price'] * $value['wged_goo_amount'];
                // 没有被删除的都计算到  总的商品数量内
                $goo_all_quantity += $value['wged_goo_amount'];
                // 没有被删除的都计算到  代收金额，代收金额不乘以数量
                $goo_all_collection += $value['wged_collection_price'];

                // 没有被删除的都计算到  工单计划总的旧货回收数量
                if ($value['wged_is_recycle'] == 1) {
                    // 回收商品
                    $wor_is_recycle = 1; //是否回收：1.回收2.不回收
                    $recycle_number += $value['wged_recycle_quantity']; //回收总数量
                    $recycle_price += $value['wged_recycle_quantity'] * $value['wged_recycle_price']; //回收总金额
                }

                // 组合发货单商品表数据
                $dego_goo_data[$key]['digo_wago_class'] = $value['wged_waon_class'];
                $dego_goo_data[$key]['digo_goo_id'] = $value['wged_goo_id'];
                $dego_goo_data[$key]['digo_goo_price'] = $value['wged_goo_price'] * 100;
                $dego_goo_data[$key]['digo_goo_quantity'] =
                    $value['wged_goo_amount'];
                $dego_goo_data[$key]['digo_is_recycle'] = $value['wged_is_recycle'];
                $dego_goo_data[$key]['digo_goo_inventory'] = $value['wged_goo_inventory'];
                $dego_goo_data[$key]['digo_goo_name'] = $value['wged_goo_name'];
                $dego_goo_data[$key]['digo_goo_goods_encode'] = $value['wged_goo_goods_encode'];
                $dego_goo_data[$key]['digo_goo_type'] = $value['wged_goo_type'];

                // 组合仓库商品改变的数据
                $ware_goo_id[$key] = $value['wged_goo_id']; //商品id
                $ware_goo_number[$value['wged_goo_id']] = $value['wged_goo_amount']; //商品数量
                $ware_goo_inventory[$value['wged_goo_id']] = $value['wged_goo_inventory']; //商品出库方式1.良品 2.优先
                $ware_goo_wago_class[$value['wged_goo_id']] = $value['wged_waon_class']; //商品仓库类�����

                // 判断是否有新增的商品
                if ($value['wged_wogo_id'] == 0) {
                    // 工单商品主键id为0的，说明是新添加的商品
                    $add_goo_id[] = $value['wged_goo_id']; //新增商品的id
                    $add_goo_inventory[] = $value['wged_goo_inventory']; //商品出库方式1.良品 2优先
                    $add_goo_is_recycle[] = $value['wged_is_recycle']; //新增商品的是否回收
                    $add_goo_price[] = $value['wged_goo_price']; //新增商品的售价
                    $add_goo_amount[] = $value['wged_goo_amount']; //新增商品的数量
                    $add_goo_collection_price[] = $value['wged_collection_price']; //新增商品的代收金额
                    $add_goo_name[] = $value['wged_goo_name']; //新增商品名称
                    $add_goo_goods_encode[] = $value['wged_goo_goods_encode']; //新增商品的检索编码
                    $add_goo_type[] = $value['wged_goo_type']; //新增商品类型

                    $find_goods_data = DB::table('goods')
                        ->where('goo_id', $value['wged_goo_id'])
                        ->first(['goo_ampere_hour']);

                    $add_goo_data['waon_class'][$value['wged_goo_id']] = $value['wged_waon_class']; //新增仓库类别
                    $add_goo_data['recycle_price'][$value['wged_goo_id']] = $value['wged_recycle_price']; //新增回收金额
                    $add_goo_data['recycle_quantity'][$value['wged_goo_id']] = $value['wged_recycle_quantity']; //新增回收数量
                    $add_goo_data['goo_state'][$value['wged_goo_id']] = $value['wged_state']; //新增商品状态
                    $add_goo_data['goo_type'][$value['wged_goo_id']] = $value['wged_goo_type']; //新增商品类型
                    $add_goo_data['goo_name'][$value['wged_goo_id']] = $value['wged_goo_name']; //新增商品名称
                    $add_goo_data['goo_goods_encode'][$value['wged_goo_id']] = $value['wged_goo_goods_encode']; //新增商品的检索编码
                    $add_goo_data['goo_amount'][$value['wged_goo_id']] = $value['wged_goo_amount']; //新增商品的数量
                    $add_goo_data['goo_price'][$value['wged_goo_id']] = $value['wged_goo_price']; //新增商品的售价
                    $add_goo_data['goo_is_recycle'][$value['wged_goo_id']] = $value['wged_is_recycle']; //新增商品的是否回收
                    $add_goo_data['goo_inventory'][$value['wged_goo_id']] = $value['wged_goo_inventory']; //商品出库方式1.良品 2优先
                    $add_goo_data['goo_collection_price'][$value['wged_goo_id']] = $value['wged_collection_price']; //新增商品的代收金额
                    $add_goo_data['goo_ampere_hour'][$value['wged_goo_id']] = $find_goods_data->goo_ampere_hour; //新增的商品安时数
                }
            }
        }

        // 查询加盟店工单信息
        $join_wor_data = DB::table('work_order as wo')
            ->leftjoin('order as o', 'o.ord_id', '=', 'wo.wor_order_id')
            ->where('wor_id', $join_wor_id)
            ->select('wor_number', 'wor_create_id', 'wor_service_type', 'wor_service_sepr_id', 'wor_state', 'wor_service_state', 'wor_pass', 'wor_service_adm_id', 'wor_service_shop_id', 'wor_ware_id', 'wor_remark', 'wor_type', 'ord_state', 'ord_type', 'ord_other_system_number', 'wor_id', 'ord_cid', 'ord_superior_shop_id', 'ord_shop_id', 'ord_order_state', 'ord_id', 'ord_order_number')
            ->first();

        $dibi_return = $this->editDispatchBill(
            $user_info, //用户信息
            $shop_id, //总店id
            $join_wor_id, //工单id
            $join_wor_data, //工单数据
            $wged_info['wced_service_adm_id'], //改单的服务技师id
            $goo_all_quantity, //改单的商品总数量
            $dego_goo_data, //改单的发货单商品数据
            $ware_goo_id, //改单的商品id
            $ware_goo_number, //改单的商品数量：商品id=>商品数量
            $ware_goo_inventory, //改单的出库类型：商品id=>出库类型
            $ware_goo_wago_class, //改单的仓库类别：商品id=>仓库类别
            $add_goo_id, //改单添加的商品
            $add_goo_is_recycle, //改单添加的商品回收类型
            $add_goo_price, //改单添加的商品售价
            $add_goo_amount, //改单添加的商品数量
            $add_goo_inventory, //改单添加的商品出库类型
            $add_goo_name, //改单添加的商品名称
            $add_goo_goods_encode //改单添加的商品检索编码
        );
        if ($dibi_return['code'] == 500) {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'审核失败']);
        }

        //客户信息
        $ord_client = DB::table('order_client')
            ->where('orcl_ord_id', $wor_data->ord_id)
            ->first(['orcl_channel_unit', 'orcl_name', 'orcl_phone', 'orcl_id']);
        // 获取到当前工单的订单信息
        $ord_info = DB::table('order')
            ->where('ord_id', $wor_data->ord_id)
            ->first(['ord_client_id']);

        $request['wor_service_adm_id'] = $wged_info['wced_service_adm_id'];
        $request['wor_id'] = $join_wor_id;
        $request['wor_service_sepr_id'] = $wor_data->wor_service_sepr_id;
        $request['wocl_collect_state'] = $wged_info['wced_collect_state'];

        // 2. 处理工单数据
        $wor_return = $this->editWorkData(
            $user_info,
            $request,
            $join_wor_data,
            $ord_info,
            $ord_client,
            $del_wogo_id,
            $del_goo_id,
            $del_goo_price,
            $del_goo_amount,
            $add_goo_id,
            $add_goo_is_recycle,
            $add_goo_price,
            $add_goo_amount,
            $add_goo_collection_price,
            $add_goo_inventory,
            $goo_all_price,
            $recycle_number,
            $wor_is_recycle,
            $goo_all_quantity,
            $goo_all_collection,
            $add_goo_data
        );
        if ($wor_return['code'] == 500) {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'审核失败']);
        }
        // 解锁
        $lock_return = $this->editLockUnlock($user_info, $request['wor_id'], 1);
        if ($lock_return['code'] == 500) {
            return response()->json($lock_return);
        }
        if ($wged_res && $delete_eidt && $orgo_delete && $orgo_insert && $join_work_delete && $join_work_insert && $join_orgo_delete && $join_orgo_insert && $ord_client_res && $work_client_res && $join_ord_client_res && $join_order_res) {
            orderLog($user_info, $wor_data->ord_id, 0, '总店审核通过');
            orderLog($user_info, 0, $join_wor_id, '总店审核通过');
            Common::addLog($user_info, getRealIp($request), '工单列表', '审核', '审核通过加盟店申请的改单' . $wor_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 headChangeReject(Request $request)
    {
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $verify_data = new VerifyWorkOrderController;
        $error_message = $verify_data->headChangeRejectValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>$error_message, 'data'=>'{}']);
        }

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

        $order_id = DB::table('work_client_edit')
            ->where('wced_wor_id', $request['wor_id'])
            ->value('wced_order_id');
        if (!empty($order_id)) {
            $wced_res = DB::table('work_client_edit')
                ->where('wced_wor_id', $request['wor_id'])
                ->delete();
        } else {
            $wced_res = true;
        }

        $order_id = DB::table('work_good_edit')
            ->where('wged_wor_id', $request['wor_id'])
            ->value('wged_order_id');
        if (!empty($order_id)) {
            $wged_res = DB::table('work_good_edit')
                ->where('wged_wor_id', $request['wor_id'])
                ->delete();
        } else {
            $wged_res = true;
        }
        // 解锁
        $lock_return = $this->editLockUnlock($user_info, $request['wor_id'], 1);
        if ($lock_return['code'] == 500) {
            return response()->json($lock_return);
        }
        orderLog($user_info, $order_id, 0, '审核驳回');
        orderLog($user_info, 0, $request['wor_id'], '审核驳回');
        if ($lock_return && $wced_res && $wged_res) {
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'error', 'data'=>'审核驳回成功！']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'审核驳回失败']);
        }
    }

    // 跟加盟店结算
    public function settlement(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkOrderController;
        $error_message = $verify_data->settlementValidator($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_wor = DB::table('work_order as wo')
            ->leftjoin('work_client as wc', 'wc.wocl_wor_id', '=', 'wo.wor_id')
            ->where('wor_id', $request['wor_id'])
            ->first(['wor_number', 'wor_state', 'wor_type', 'wor_service_shop_id', 'wor_actual_price', 'wor_remark', 'wor_collection_price', 'wor_service_type', 'wor_plus_minus', 'wor_goo_amount', 'wor_account_state', 'wocl_wor_type', 'wocl_assign_price', 'wocl_plus_minus']);
        if ($find_wor->wor_account_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单不是待结算状态，无法结算！']);
        }
        if ($find_wor->wocl_wor_type != 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'不是加盟店工单无法结算！']);
        }
        // 订单的工单状态1未派工单2服务中3售后中4已完成5无工单
        if ($find_wor->wor_state != 10) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单尚未完成，无法结算！']);
        }
        DB::beginTransaction();
        $settlement_res = WorkOrder::settlement($request->all(), $find_wor, $user_info);
        if ($settlement_res) {
            orderLog($user_info, 0, $request['wor_id'], '结算');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'error', 'data'=>'结算成功！']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'结算失败']);
        }
    }

    // 删除绩效
    public function deletePerformance(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkOrderController;
        $error_message = $verify_data->infoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 查询信息
        $find_wor = DB::table('work_order')
            ->where('wor_id', $request['wor_id'])
            ->select('wor_number', 'wor_state')
            ->first();

        if ($find_wor->wor_state != 11) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单尚未终止,无法删除绩效！']);
        }

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

        $update_data['wor_delete'] = 2;
        $update_data['wor_update_time'] = date('Y-m-d H:i:s');
        $wor_del_res = DB::table('work_order')
            ->where('wor_id', $request['wor_id'])
            ->update($update_data);

        if ($wor_del_res) {
            Common::addLog($user_info, getRealIp($request), '工单列表', '删除绩效', $find_wor->wor_number . '工单删除绩效成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'删除绩效成功']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'删除绩效失败']);
        }
    }

    // 修改车牌号和车型
    public function editLicence(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkOrderController;
        $error_message = $verify_data->assignShowValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 查询信息
        $find_wor = DB::table('work_order')
            ->where('wor_id', $request['wor_id'])
            ->select('wor_number', 'wor_state', 'wor_order_id')
            ->first();
        if ($request['type'] == 1) {
            // 获取车型和车牌号
            $find_wocl_data = DB::table('work_client')
                ->where('wocl_wor_id', $request['wor_id'])
                ->select('wocl_car_num', 'wocl_car_vehicle_type')
                ->first();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$find_wocl_data]);
        }

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

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

        $update_data['wocl_car_num'] = $request['wocl_car_num'] ? $request['wocl_car_num'] : ''; //车牌号
        $update_data['wocl_car_vehicle_type'] = $request['wocl_car_vehicle_type'] ? $request['wocl_car_vehicle_type'] : ''; //车型
        $update_data['wocl_update_time'] = $date;

        $ord_update_data['orcl_car_num'] = $request['wocl_car_num'] ? $request['wocl_car_num'] : ''; //车牌号
        $ord_update_data['orcl_car_vehicle_type'] = $request['wocl_car_vehicle_type'] ? $request['wocl_car_vehicle_type'] : ''; //车型
        $ord_update_data['orcl_update_time'] = $date;

        DB::beginTransaction();

        $wor_del_res = DB::table('work_client')
            ->where('wocl_wor_id', $request['wor_id'])
            ->update($update_data);

        $ord_edit_res = DB::table('order_client')
            ->where('orcl_ord_id', $find_wor->wor_order_id)
            ->update($ord_update_data);

        if ($wor_del_res && $ord_edit_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '工单列表', '修改信息', $find_wor->wor_number . '工单修改车牌和车型成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'操作成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'操作失败']);
        }
    }

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

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

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

        // 查询当前工单数据
        $find_wor_data = DB::table('work_order')
            ->where('wor_id', $request['wor_id'])
            ->first(['wor_id', 'wor_type', 'wor_number',  'wor_appoint_time', 'wor_order_id', 'wor_state', 'wor_delete']);
        if ($find_wor_data->wor_delete == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单已经取消！']);
        }
        if ($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', $find_wor_data->wor_order_id)
            ->update($orcl_edit);

        $wor_id = $find_wor_data->wor_id;
        if ($find_wor_data) {
            $wor_edit['wor_appoint_time'] = $request['appoint_time'];
            $wor_edit['wor_update_time'] = date('Y-m-d H:i:s');
            $wor_edit['wor_service_state'] = 3; //修改服务状态为预约
            $wor_edit['wor_state'] = 5; //修改状态为预约/已预约
            $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, $find_wor_data->wor_order_id, $wor_id, '预约设置');
        // 预约备注内容
        $remark_data = '预约时间：' . $request['appoint_time'];
        if (!empty($request['appoint_remark'])) {
            $remark_data .= ' ' . $request['appoint_remark'];
        }
        $remark_res = orderRemark($user_info, $find_wor_data->wor_order_id, $wor_id, $remark_data, '工单列表-预约设置');

        if ($ord_res && $wor_res && $remark_res) {
            // 如果是速电订单,，并且更改了预约时间，调速电预约接口
            if ($find_wor_data->wor_type == 3 && $find_wor_data->orcl_appoint_time != $request['appoint_time']) {
                $find_order = DB::table('order')
                    ->where('ord_id', $find_wor_data->wor_order_id)
                    ->select('ord_other_system_number')
                    ->first();
                $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_wor_data->wor_number . '成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'预约设置成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'预约设置失败']);
        }
    }

    // 生成凭证【一般情况下用不到】
    public function workOrderVoucher(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id1
        $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_wor_data = DB::table('work_order as wor')
            ->leftjoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wor.wor_id')
            ->where('wor_cid', $user_info->adm_cid)
            ->where('wor_shop_id', $user_info->adm_shop_id)
            ->where('wor_state', 10)
            ->whereIn('wocl_wor_type', [1, 3])
            ->where('wor_delete', 1)
            ->where('wor_collection_bill', 1)
            ->where('wor_service_type', '!=', 4)
            ->where('wor_id', '>=', 1145)
            ->where('wor_id', '<', 4350)
            ->select('wor_id', 'wor_cid', 'wor_superior_shop_id', 'wor_shop_id', 'wor_number', 'wor_order_id', 'wor_order_number', 'wor_create_id', 'wor_actual_price', 'wor_plus_minus', 'wor_recycle_price', 'wor_type', 'wor_collection_price', 'wor_update_time', 'wocl_client_id', 'wocl_channel_unit', 'wocl_name', 'wor_create_time', 'wor_ware_id')
            ->get()->toArray();
        DB::beginTransaction();
        $cost_price = 0;
        foreach ($find_wor_data as $key => $value) {
            // 凭证单据报表
            // 根据订单id和商品状态,查询出回收的商品
            $find_goods_data = DB::table('work_good')
                ->where('wogo_wor_id', $value->wor_id)
                ->where('wogo_state', 3)
                ->select('wogo_id', 'wogo_wor_id', 'wogo_ware_id', 'wogo_waon_class', 'wogo_goo_id', 'wogo_goo_price', 'wogo_goo_amount', 'wogo_recycle_price')
                ->get()->toArray();
            $goo_recycle_price = [];
            foreach ($find_goods_data as $kk => $vv) {
                if (!isset($goo_recycle_price[$vv->wogo_goo_id])) {
                    $goo_recycle_price[$vv->wogo_goo_id] = 0;
                }
                $goo_recycle_price[$vv->wogo_goo_id] += $vv->wogo_goo_price * $vv->wogo_goo_amount; //商品数量
            }
            $recycle_amount = 0;
            foreach ($goo_recycle_price as $kkk => $vvv) {
                $recycle_amount += $vvv;
            }
            // 根据订单id,查询商品
            $find_wogo_data = DB::table('work_good')
                ->where('wogo_wor_id', $value->wor_id)
                ->where('wogo_state', '!=', 2)
                ->select('wogo_id', 'wogo_wor_id', 'wogo_ware_id', 'wogo_waon_class', 'wogo_goo_id', 'wogo_goo_price', 'wogo_goo_amount', 'wogo_recycle_price', 'wogo_state')
                ->get()->toArray();
            if ($find_wogo_data) {
                $cost_price = 0;
                foreach ($find_wogo_data as $kkkk => $vvvv) {
                    // 获取当前月份商品成本价
                    if ($vvvv->wogo_ware_id == '0') {
                        $vvvv->wogo_ware_id = $value->wor_ware_id;
                    } else {
                        $vvvv->wogo_ware_id = $vvvv->wogo_ware_id;
                    }
                    if ($vvvv->wogo_state != 3 && $vvvv->wogo_state != 7) {
                        $list_items = DB::table('enters_sells_saves')
                            ->where('ense_goo_id', $vvvv->wogo_goo_id)
                            ->where('ense_goo_warehouse', $vvvv->wogo_ware_id)
                            ->where('ense_goo_waretype', $vvvv->wogo_waon_class)
                            ->where('ense_order_number', $value->wor_order_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->wogo_ware_id)
                            ->where('ense_goo_waretype', $vvvv->wogo_waon_class)
                            ->whereIn('ense_goo_id', $ids)
                            ->where('ense_order_number', $value->wor_order_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->wogo_goo_amount;
                            }
                        } 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_wor_id', $value->wor_id)
                    ->where('vore_wor_number', $value->wor_number)
                    ->where('vore_order_type', 2)
                    ->where('vore_state', 1)
                    ->select('vore_id', 'vore_wor_id', 'vore_wor_number')
                    ->first();
                if (empty($vore_id)) {
                    $vore_data['vore_cid'] = $value->wor_cid; //公司id
                    $vore_data['vore_superior_shop_id'] = $value->wor_superior_shop_id; //总店id
                    $vore_data['vore_shop_id'] = $value->wor_shop_id; //门店id
                    $vore_data['vore_create_id'] = $value->wor_create_id; //创建人
                    $vore_data['vore_order_type'] = 2; //单号类型1.订单2.工单3.采购单4.销售单
                    $vore_data['vore_wor_id'] = $value->wor_id; //订单id
                    $vore_data['vore_wor_number'] = $value->wor_number; //订单单号
                    $vore_data['vore_ord_id'] = $value->wor_order_id; //订单id
                    $vore_data['vore_ord_number'] = $value->wor_order_number; //订单单号
                    $vore_data['vore_plus_minus'] = $value->wor_plus_minus; //金额正负1正值2负值
                    $vore_data['vore_actual_price'] = $value->wor_actual_price / 100; //结算金额
                    $vore_data['vore_collection_price'] = $value->wor_collection_price / 100; //代收金额
                    $vore_data['vore_recycle_price'] = $recycle_amount / 100; //回收金额
                    $vore_data['vore_early_costing'] = $cost_price; //成本
                    $vore_data['vore_type'] = $value->wor_type; //单位类型1会员零售2客户单位3速电派单
                    $vore_data['vore_client_id'] = $value->wocl_client_id; //客户单位/客户id
                    if ($value->wor_type == 1) { //1.会员零售
                        $vore_data['vore_channel_unit'] = $value->wocl_name;
                    } elseif ($value->wor_type == 2) { //2.客户单位
                        $vore_data['vore_channel_unit'] = $value->wocl_channel_unit;
                    } elseif ($value->wor_type == 3) { //3.速电派单
                        $vore_data['vore_channel_unit'] = $value->wocl_channel_unit;
                    }
                    $vore_data['vore_create_time'] = $value->wor_create_time;
                    $vore_id = DB::table('voucher_receipts')->insertGetId($vore_data);
                    // 凭证借贷表(结算金额)
                    $volo_data[0]['volo_shop_id'] = $value->wor_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'] = $value->wor_create_time; //更新时间
                    // 凭证借贷表(回收金额)
                    $volo_data[1]['volo_shop_id'] = $value->wor_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_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 ($value->wor_plus_minus == 2) {
                        $volo_data[0]['volo_borrow_price'] = (-1) * $value->wor_actual_price / 100; //借方金额
                        $volo_data[1]['volo_borrow_price'] = (-1) * $recycle_amount / 100; //借方金额
                        $volo_data[0]['volo_loan_price'] = (-1) * $value->wor_actual_price / 100 + $recycle_amount / 100; //贷方金额
                    } else {
                        $volo_data[0]['volo_borrow_price'] = $value->wor_actual_price / 100; //借方金额
                        $volo_data[1]['volo_borrow_price'] = $recycle_amount / 100; //借方金额
                        $volo_data[0]['volo_loan_price'] = $value->wor_actual_price / 100 + $recycle_amount / 100; //贷方金额
                    }

                    $volo_data[1]['volo_update_time'] = $value->wor_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 = DB::table('voucher_receipts')
                    ->where('vore_cid', $user_info->adm_cid)
                    ->where('vore_shop_id', $user_info->adm_shop_id)
                    ->where('vore_wor_id', $value->wor_id)
                    ->where('vore_wor_number', $value->wor_number)
                    ->where('vore_order_type', 2)
                    ->where('vore_state', 1)
                    ->select('vore_id', 'vore_wor_id', 'vore_wor_number')
                    ->first();
                if (empty($vore_id)) {
                    $vore_data['vore_cid'] = $value->wor_cid;//公司id
                    $vore_data['vore_superior_shop_id'] = $value->wor_superior_shop_id;//总店id
                    $vore_data['vore_shop_id'] = $value->wor_shop_id;//门店id
                    $vore_data['vore_create_id'] = $value->wor_create_id;//创建人
                    $vore_data['vore_order_type'] = 2;//单号类型1.订单2.工单3.采购单4.销售单
                    $vore_data['vore_wor_id'] = $value->wor_id;//订单id
                    $vore_data['vore_wor_number'] = $value->wor_number;//订单单号
                    $vore_data['vore_ord_id'] = $value->wor_order_id;//订单id
                    $vore_data['vore_ord_number'] = $value->wor_order_number;//订单单号
                    $vore_data['vore_plus_minus'] = $value->wor_plus_minus;//金额正负1正值2负值
                    $vore_data['vore_actual_price'] = $value->wor_actual_price / 100;//结算金额
                    $vore_data['vore_collection_price'] = $value->wor_collection_price / 100;//代收金额
                    $vore_data['vore_recycle_price'] = $recycle_amount / 100;//回收金额
                    $vore_data['vore_early_costing'] = $cost_price;//成本
                    $vore_data['vore_type'] = $value->wor_type;//单位类型1会员零售2客户单位3速电派单
                    $vore_data['vore_client_id'] = $value->wocl_client_id;//客户单位/客户id
                    if ($value->wor_type == 1) {//1.会员零售
                        $vore_data['vore_channel_unit'] = $value->wocl_name;
                    } elseif ($value->wor_type == 2) {//2.客户单位
                        $vore_data['vore_channel_unit'] = $value->wocl_channel_unit;
                    } elseif ($value->wor_type == 3) {//3.速电派单
                        $vore_data['vore_channel_unit'] = $value->wocl_channel_unit;
                    }
                    $vore_data['vore_create_time'] = $value->wor_create_time;
                    $vore_id = DB::table('voucher_receipts')->insertGetId($vore_data);
                    // 凭证借贷表(结算金额)
                    $volo_data[0]['volo_shop_id'] = $value->wor_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_update_time'] = $value->wor_create_time;//更新时间
                    // 凭证借贷表(回收金额)
                    $volo_data[1]['volo_shop_id'] = $value->wor_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_loan_subject'] = '';//贷方科目
                    $volo_data[1]['volo_loan_subject_name'] = '';//贷方科目名称
                    $volo_data[1]['volo_loan_price'] = 0;//贷方金额

                    if ($value->wor_plus_minus == 2) {
                        $volo_data[0]['volo_borrow_price'] = '-' . $value->wor_actual_price / 100;//借方金额
                        $volo_data[1]['volo_borrow_price'] = '-' . $recycle_amount / 100;//借方金额
                        $volo_data[0]['volo_loan_price'] = '-' . $value->wor_actual_price / 100 + $recycle_amount / 100;//贷方金额
                    } else {
                        $volo_data[0]['volo_borrow_price'] = $value->wor_actual_price / 100;//借方金额
                        $volo_data[1]['volo_borrow_price'] = $recycle_amount / 100;//借方金额
                        $volo_data[0]['volo_loan_price'] = $value->wor_actual_price / 100 + $recycle_amount / 100;//贷方金额
                    }

                    $volo_data[1]['volo_update_time'] = $value->wor_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]);
                    }
                } */
                $vore_id = true;
                $volo_id = true;
            }
        }
        if ($vore_id && $volo_id) {
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'生成凭证成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'生成凭证失败']);
        }
    }

    // 虚拟加盟店审核
    public function virtualUpdatePass($user_info, $shop_id, $find_wor, $request)
    {
        // 救援单类型，查询服务项目的工单金额
        $sepr_order_money = 0; //服务项目的工单金额
        if ($find_wor->wocl_wor_type == 4) {
            $sepr_order_money = $request['sepr_order_money'] * 100;
        } elseif ($find_wor->wor_service_type == 7) {
            $sepr_order_money = $find_wor->wocl_rescue_service_price;
        }
        // 查询出工单商品
        $work_good = DB::table('work_good')
            ->where('wogo_state', '<>', 2)
            ->where('wogo_wor_id', $request['wor_id'])
            ->select('wogo_goo_id', 'wogo_goo_amount', 'wogo_goo_inventory', 'wogo_goo_price', 'wogo_collection_price', 'wogo_state', 'wogo_recycle_price', 'wogo_recycle_quantity', 'wogo_ware_id', 'wogo_waon_class', 'wogo_assign_price', 'wogo_actual_recycle_number', 'wogo_id')
            ->get()
            ->toArray();
        $total_price = 0; //总的金额
        $total_collection_price = 0;
        $reduce_total_price  = 0; //回收的总金额，工单订单需要减少的金额

        $voucher_sell_total_price  = 0; //销售总额，换货单，用友系统使用
        $voucher_refund_total_price  = 0; //退货总额，换货单，用友系统使用
        $voucher_cost  = 0; //凭证成本，上传用友系统
        $refund_voucher_cost  = 0; //换货单，换回商品成本，凭证成本，上传用友系统
        $wogo_actual_recycle_number = 0; //app实际回收数量

        $total_collection_price += $request['wocl_rescue_collection_price'] * 100;
        if (!empty($work_good)) {
            foreach ($work_good as $key => $value) {
                if ($value->wogo_state == 1) {
                    // 商品id
                    $goo_id[$key] = $value->wogo_goo_id;
                    //商品数量
                    $goo_number[$key] = $value->wogo_goo_amount;
                    //商品价格
                    $goo_price[$key] = $value->wogo_goo_price;

                    //工单商品总价
                    $total_price += $request['goo_price'][$key] * $value->wogo_goo_amount * 100;
                    //工单商品代收总价
                    $total_collection_price += $request['goo_collection_price'][$key] * 100;
                    // 库存扣除方式1.良品 2.优先
                    $goo_inventory[$key] = $value->wogo_goo_inventory;
                    // 商品id所对应的商品数量
                    $subtract[$value->wogo_goo_id] = $value->wogo_goo_amount;
                    // 商品id所对应的出库方式
                    $goo_repertory[$value->wogo_goo_id] = $value->wogo_goo_inventory;
                } elseif ($value->wogo_state == 4) {
                    $total_price -= $request['goo_price'][$key] * $value->wogo_goo_amount * 100;
                }
                $wogo_actual_recycle_number += $value->wogo_actual_recycle_number;
                $wogo_goo_id_amount[$value->wogo_id] = $value->wogo_goo_amount;
            }

            $goo_work_goods = array_column($work_good, null, 'wogo_goo_id');
            // 编辑工单商品表数据
            $sql = 'UPDATE `faster_work_good` SET ';
            $actual_price_sql = '';
            $collection_price_sql = '';
            $update_time_sql = '';
            $wogo_goo_amount = '';
            $ids = '';
            $junk_recycle = [];
            $goo_exchange_price  = [];
            foreach ($request['wogo_id'] as $key => $value) {
                if (!is_numeric($value) || !is_numeric($request['goo_price'][$key]) || !is_numeric($request['goo_collection_price'][$key])) {
                    DB::rollBack();
                    return ['code'=>500, 'msg'=>'error', 'data'=>'商品参数类型错误'];
                }

                //更改商品价格
                $actual_price_sql = $actual_price_sql . ' WHEN ' . $value;
                $actual_price_sql = $actual_price_sql . ' THEN ' . $request['goo_price'][$key] * 100;

                // 更改商品代收价格
                $collection_price_sql = $collection_price_sql . ' WHEN ' . $value;
                $collection_price_sql = $collection_price_sql . ' THEN ' . $request['goo_collection_price'][$key] * 100;

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

                // 更改商品数量
                $wogo_goo_amount = $wogo_goo_amount . ' WHEN ' . $value;
                $wogo_goo_amount = $wogo_goo_amount . ' THEN ' . $request['wogo_goo_amount'][$key];

                $ids = $ids . $value . ',';
                //旧货回收商品价格
                if (isset($request['wogo_state'][$key]) && $request['wogo_state'][$key] == 3) {
                    $junk_recycle[] = $value; //旧货回收商品id
                    $reduce_total_price += $request['goo_price'][$key] * 100 * $request['wogo_goo_amount'][$key];
                } elseif (isset($request['wogo_state'][$key]) && $request['wogo_state'][$key] == 8) {
                    $junk_recycle[] = $value; //旧货回收商品id
                    $reduce_total_price -= $request['goo_price'][$key] * 100 * $request['wogo_goo_amount'][$key];
                }
                if ($request['wogo_state'][$key] == 3) {
                    DB::table('work_good')
                        ->where('wogo_id', $value)
                        ->update(['wogo_recycle_price' => $request['goo_price'][$key] * 100, 'wogo_goo_amount' => $request['wogo_goo_amount'][$key]]);
                }
            }

            $sql = $sql . ' `wogo_goo_price` = CASE `wogo_id`' . $actual_price_sql . ' END,'; //商品售价
            $sql = $sql . ' `wogo_goo_amount` = CASE `wogo_id`' . $wogo_goo_amount . ' END,'; //商品数量
            $sql = $sql . ' `wogo_collection_price` = CASE `wogo_id`' . $collection_price_sql . ' END,'; //商品代收金额
            $sql = $sql . ' `wogo_update_time`=  CASE `wogo_id` ' . $update_time_sql . ' END';
            $sql = $sql . ' WHERE `wogo_wor_id` = ' . $request['wor_id'] . ' AND `wogo_id` IN (' . trim($ids, ',') . ')';
            $wogo_res = DB::update($sql);
        } else {
            $wogo_res = true;
        }

        $virtual_goo_price = 0; //虚拟加盟店订单金额
        $junk_goo_price = 0;
        $old_junk_goo_price = 0;
        if (!empty($work_good)) {
            $sql = 'UPDATE `faster_order_goods` SET ';
            $actual_price_sql = '';
            $collection_price_sql = '';
            $update_time_sql = '';
            $wogo_goo_amount = '';
            $ids = '';
            foreach ($request['wogo_orgo_id'] as $key => $value) {
                if (!is_numeric($value) || !is_numeric($request['orgo_goo_price'][$key]) || !is_numeric($request['goo_collection_price'][$key])) {
                    DB::rollBack();
                    return ['code'=>500, 'msg'=>'error', 'data'=>'商品参数类型错误'];
                }

                if ($request['wogo_state'][$key] == 3) {
                    $price = $request['goo_price'][$key] * 100;
                } else {
                    $price = $request['orgo_goo_price'][$key] * 100;
                }

                //更改商品价格
                $actual_price_sql = $actual_price_sql . ' WHEN ' . $value;
                $actual_price_sql = $actual_price_sql . ' THEN ' . $price;

                // 更改商品代收价格
                $collection_price_sql = $collection_price_sql . ' WHEN ' . $value;
                $collection_price_sql = $collection_price_sql . ' THEN ' . $request['goo_collection_price'][$key] * 100;

                // 更改商品数量
                $wogo_goo_amount = $wogo_goo_amount . ' WHEN ' . $value;
                $wogo_goo_amount = $wogo_goo_amount . ' THEN ' . $request['wogo_goo_amount'][$key];
                // 更改时间
                $update_time_sql = $update_time_sql . ' WHEN ' . $value;
                $update_time_sql = $update_time_sql . ' THEN "' . date('Y-m-d H:i:s') . '"';
                $ids = $ids . $value . ',';

                if ($request['wogo_state'][$key] != 3) {
                    $virtual_goo_price += $price * $request['wogo_goo_amount'][$key];
                } else {
                    $virtual_goo_price -= $price * $request['wogo_goo_amount'][$key];
                    //计算原来的旧货金额
                    $old_junk_goo_price += $price * $request['wogo_goo_amount'][$key];
                }
            }
            $sql = $sql . ' `orgo_goo_price` = CASE `orgo_id`' . $actual_price_sql . ' END,'; //商品售价
            $sql = $sql . ' `orgo_collection_price` = CASE `orgo_id`' . $collection_price_sql . ' END,'; //商品代收金额
            $sql = $sql . ' `orgo_goo_quantity` = CASE `orgo_id`' . $wogo_goo_amount . ' END,'; //商品数量
            $sql = $sql . ' `orgo_update_time`=  CASE `orgo_id` ' . $update_time_sql . ' END';
            $sql = $sql . ' WHERE `orgo_ord_id` = ' . $find_wor->wor_order_id . ' AND `orgo_id` IN (' . trim($ids, ',') . ')';
            $orgo_res = DB::update($sql);
        } else {
            $orgo_res = true;
        }
        $count_goo_quantity = 0;
        if (!empty($request['virtual_goo_id'])) {
            foreach ($request['virtual_goo_id'] as $key => $value) {
                $junk_goo_price += $request['virtual_goo_price'][$key] * 100 * $request['virtual_goo_quantity'][$key];
                $goods_data = DB::table('goods')
                    ->where('goo_id', $value)
                    ->first(['goo_name', 'goo_goods_encode', 'goo_class']);
                if ($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)) {
                        $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)) {
                        $goods_data->goo_name = $gosa_another_name;
                    }
                }
                $virtual_order['orgo_ord_id'] = $find_wor->wor_order_id;
                $virtual_order['orgo_order_number'] = $find_wor->wor_order_number;
                $virtual_order['orgo_waon_class'] = 3;
                $virtual_order['orgo_goo_id'] = $value;
                $virtual_order['orgo_goo_name'] = $goods_data->goo_name;
                $virtual_order['orgo_goo_goods_encode'] = $goods_data->goo_goods_encode;
                $virtual_order['orgo_goo_type'] = 4;
                $virtual_order['orgo_goo_inventory'] = 1;
                $virtual_order['orgo_is_recycle'] = 2;
                $virtual_order['orgo_state'] = 3;
                $virtual_order['orgo_goo_price'] = $request['virtual_goo_price'][$key] * 100;
                $virtual_order['orgo_goo_quantity'] = $request['virtual_goo_quantity'][$key];
                $virtual_order['orgo_recycle_quantity'] = $request['virtual_goo_quantity'][$key];
                $orgo_id = DB::table('order_goods')->insertGetId($virtual_order);

                $virtual_wor['wogo_wor_id'] = $request['wor_id'];
                $virtual_wor['wogo_goo_id'] = $value;
                $virtual_wor['wogo_orgo_id'] = $orgo_id;
                $virtual_wor['wogo_waon_class'] = 3;
                $virtual_wor['wogo_is_recycle'] = 2;
                $virtual_wor['wogo_goo_name'] = $goods_data->goo_name;
                $virtual_wor['wogo_goo_goods_encode'] = $goods_data->goo_goods_encode;
                $virtual_wor['wogo_goo_type'] = 4;
                $virtual_wor['wogo_state'] = 3;
                $virtual_wor['wogo_goo_price'] = $request['virtual_goo_price'][$key] * 100;
                $virtual_wor['wogo_goo_amount'] = $request['virtual_goo_quantity'][$key];
                $virtual_wor['wogo_recycle_quantity'] = $request['virtual_goo_quantity'][$key];
                $virtual_wor['wogo_actual_recycle_number'] = $request['virtual_goo_quantity'][$key];
                $virtual_wor['wogo_recycle_price'] = $request['virtual_goo_price'][$key] * 100;
                $count_goo_quantity += $request['virtual_goo_quantity'][$key];
                DB::table('work_good')->insert($virtual_wor);
            }
        }

        // 添加备注
        if (!empty($request['remark']) && $find_wor->wor_remark != $request['remark']) {
            orderRemark($user_info, $find_wor->wor_order_id, $request['wor_id'], $request['remark'], '工单列表-审核');
        }

        // 获取到当前工单的订单信息
        $ord_info = DB::table('order as o')
            ->leftjoin('order_client as oc', 'oc.orcl_ord_id', '=', 'o.ord_id')
            ->where('ord_id', $find_wor->wor_order_id)
            ->first(['ord_type', 'ord_client_id', 'ord_state', 'ord_remark', 'ord_actual_price', 'ord_payment_way', 'ord_order_price', 'ord_collection_price', 'ord_plus_minus', 'ord_other_system_number', 'ord_service_type', 'orcl_rescue_service_price', 'orcl_acc_subject_id', 'ord_create_time', 'orcl_shipment_party']);
        if (is_numeric($request['orcl_rescue_service_price'])) {
            $virtual_goo_price += $request['orcl_rescue_service_price'] * 100;
        } else {
            $virtual_goo_price += $ord_info->orcl_rescue_service_price;
        }

        // 应收账款显示客户名称
        $wocl_client_name = $find_wor->wocl_channel_unit ? $find_wor->wocl_channel_unit : $find_wor->wocl_name;

        $goo_info = collect(DB::table('order_goods')
            ->where('orgo_ord_id', $find_wor->wor_order_id)
            ->get(['orgo_goo_id', 'orgo_goo_price', 'orgo_collection_price']))
            ->keyBy('orgo_goo_id')
            ->toArray();

        $shop_info = DB::table('virtual_shop')
            ->where('vish_id', $find_wor->wor_service_shop_id)
            ->first(['vish_store_name as shop_store_name']);

        if (empty($request['imgs64'])) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'最少上传一张图片'];
        }
        $image_change_state = 1; //工单审核图片更改状态：1未上传新图2重新传图
        // 根据图片上传模板判断上传图片
        $find_image_template = DB::table('shop_image_template')
            ->where('shit_id', $find_wor->wocl_shit_id)
            ->value('shit_template_set');
        $find_image_template = json_decode($find_image_template, true);
        $upload_file = json_decode(json_encode($request['imgs64']), true);

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        $imup_data = [];
        foreach ($find_image_template as $key => $value) {
            // 判断必传图片是否上传 must_state 为1是门店设置的必传图片
            if ($value['must_state'] == 1 && empty($upload_file[$key])) {
                DB::rollBack();
                return ['code'=>500, 'msg'=>'error', 'data'=>'请上传 ' . $value['show_word'] . ' 图片'];
            }
        }
        $new_key = 0;
        // 查询图片上传表是否有当前工单的数据，如果有数据说明不是第一次上传
        $imup_id = DB::table('image_upload')
            ->where('imup_wor_id', $request['wor_id'])
            ->value('imup_id');
        foreach ($upload_file as $key => $value) {
            if (!empty($value)) {
                // 判断是否有新图片上传
                if (strpos($value, 'data:image') === 0) {
                    if ($imup_id) {
                        // 有新图片上传，将原来的图片改为删除状态
                        $imup_edit['imup_delete'] = 2;
                        $imup_edit['imup_update_time'] = date('Y-m-d H:i:s');
                        $edit_res = DB::table('image_upload')
                            ->where('imup_wor_id', $request['wor_id'])
                            ->where('imup_delete', 1)
                            ->where('imup_image_name', $find_image_template[$key]['show_word'])
                            ->update($imup_edit);
                        unset($imup_edit);
                        if (!$edit_res) {
                            DB::rollBack();
                            return ['code'=>500, 'msg'=>'error', 'data'=>'图片上传失败'];
                        }
                        // 图片上传id不为空，说明不是第一次审核上传，可以判断有重新传图
                        $image_change_state = 2;
                    }

                    // 调用全局函数 上传图片
                    $image_path = uploadBase64ImgFolder($shop_id, $value, 2);
                    $imup_data[$new_key]['imup_path'] = $image_path;
                    $imup_data[$new_key]['imup_cid'] = $user_info->adm_cid;
                    $imup_data[$new_key]['imup_shop_id'] = $user_info->adm_shop_id;
                    $imup_data[$new_key]['imup_superior_shop_id'] = $shop_id;
                    $imup_data[$new_key]['imup_ord_id'] = $find_wor->wor_order_id;
                    $imup_data[$new_key]['imup_wor_id'] = $request['wor_id'];
                    $imup_data[$new_key]['imup_image_name'] = $find_image_template[$key]['show_word'];
                    $new_key++;
                    $new_img_delete[] = $image_path; //新上传的图片路径
                }
            } else {
                if (empty($imup_id)) {
                    $imup_data[$new_key]['imup_path'] = '';
                    $imup_data[$new_key]['imup_cid'] = $user_info->adm_cid;
                    $imup_data[$new_key]['imup_shop_id'] = $user_info->adm_shop_id;
                    $imup_data[$new_key]['imup_superior_shop_id'] = $shop_id;
                    $imup_data[$new_key]['imup_ord_id'] = $find_wor->wor_order_id;
                    $imup_data[$new_key]['imup_wor_id'] = $request['wor_id'];
                    $imup_data[$new_key]['imup_image_name'] = $find_image_template[$key]['show_word'];
                    $new_key++;
                }
            }
        }
        if ($imup_data) {
            $imup_res = DB::table('image_upload')->insert($imup_data);
            if (!$imup_res) {
                DB::rollBack();
                return ['code'=>500, 'msg'=>'error', 'data'=>'图片上传失败'];
            }
        }
        //旧货回收金额
        $reduce_total_price = $junk_goo_price + $reduce_total_price;
        //商品总金额加服务金额
        $total_price = - ($total_price + $sepr_order_money);
        //商品总金额 加上旧货回收金额
        $total_price +=  $reduce_total_price;
        $now_wor_price = $total_price;

        // 应收账款的金额正负值
        if ($now_wor_price > 0) {
            $wor_plus_minus = 1;
        } else {
            $wor_plus_minus = 2;
        }
        // 更改工单信息
        $wor_data['wor_actual_price'] = $now_wor_price; //工单结算金额(单位:分)
        $wor_data['wor_collection_price'] = $total_collection_price;
        $wor_data['wor_service_type'] = $request['wor_service_type'];   //服务类型
        $wor_data['wor_service_sepr_id'] = $request['wor_service_sepr_id'];   //服务项目
        if ($find_wor->wocl_sd_virtual_type == 1) {
            $wor_data['wor_pass'] = 11;  //审核状态1.待审核 2.合格 3.不合格 11.等待速电审核
        } else {
            $wor_data['wor_pass'] = 2;  //审核状态1.待审核 2.合格 3.不合格 11.等待速电审核
        }
        $wor_data['wor_state'] = 10;    //状态1.新订单 2未派单 3待接单/已派单 4.未出发/已接单 5.预约/已预约 6.出发/已出发  7.抵达/抵达 8.待审核/完成待审核 9驳回/完成已驳回 10完成/完成已通过 11终止
        $wor_data['wor_plus_minus'] = $wor_plus_minus; //金额正负：1正值2负值
        $wor_data['wor_recycle_price'] = $reduce_total_price; //回收金额
        $wor_data['wor_service_state'] = 8; //完成通过
        $wor_data['wor_update_time'] = date('Y-m-d H:i:s');
        $wor_res = DB::table('work_order')
            ->where('wor_id', $request['wor_id'])
            ->update($wor_data);
        // 工单客户信息
        $wocl_data['wocl_name'] = $request['wocl_name'];    //姓名
        $wocl_data['wocl_phone'] = $request['wocl_phone'];    //联系电话
        $wocl_data['wocl_car_num'] = $request['wocl_car_num'];  //车牌号
        $wocl_data['wocl_province'] = $request['wocl_province'] ? $request['wocl_province'] : '';  //省
        $wocl_data['wocl_city'] = $request['wocl_city'] ? $request['wocl_city'] : '';  //市
        $wocl_data['wocl_county'] = $request['wocl_county'] ? $request['wocl_county'] : '';  //县
        $wocl_data['wocl_car_vehicle_type'] = $request['wocl_car_vehicle_type'] ? $request['wocl_car_vehicle_type'] : '';
        $wocl_data['wocl_address'] = $request['wocl_address'];  //地址
        $wocl_data['wocl_rescue_collection_price'] = $request['wocl_rescue_collection_price'] * 100;  //代收金额
        $wocl_data['wocl_update_time'] = date('Y-m-d H:i:s');  //时间
        $wocl_data['wocl_join_audit_adm_id'] = $user_info->adm_id;
        $wocl_data['wocl_rescue_service_price'] = $request['sepr_order_money'] * 100;
        $wocl_id = DB::table('work_client')
            ->where('wocl_wor_id', $find_wor->wor_id)
            ->update($wocl_data);

        $ord_actual_price = $virtual_goo_price - $junk_goo_price;
        $virtual_ord_plus_minus = 1;
        if ($ord_actual_price < 0) {
            $virtual_ord_plus_minus = 2;
        }
        //是否为速电派到加盟店的工单1是 2否
        if ($find_wor->wocl_sd_virtual_type == 2) {
            //订单金额应该是不减回收的金额
            $virtual_goo_price = $old_junk_goo_price + $virtual_goo_price;
            $ord_edit_data['ord_actual_price'] = $ord_actual_price;     //减回收金额
            $ord_edit_data['ord_order_price'] = $virtual_goo_price;     //不减回收金额
            $ord_edit_data['ord_plus_minus'] = $virtual_ord_plus_minus; //新正负值
            $ord_edit_data['ord_collection_price'] = $total_collection_price;
        }

        // 订单状态改为完成状态
        $ord_edit_data['ord_wor_state'] = 4; //订单的工单状态1未派工单2服务中3售后中4已完成
        $ord_edit_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_res = DB::table('order')
            ->where('ord_id', $find_wor->wor_order_id)
            ->update($ord_edit_data);
        if (!empty($request['wocl_car_vehicle_type']) || !empty($request['wocl_car_num']) || !empty($request['orcl_rescue_service_price'])) {
            $orcl['orcl_car_num'] = $request['wocl_car_num'] ? $request['wocl_car_num'] : '';
            $orcl['orcl_car_vehicle_type'] = $request['wocl_car_vehicle_type'] ? $request['wocl_car_vehicle_type'] : '';
            $orcl['orcl_rescue_service_price'] = $request['orcl_rescue_service_price'] * 100;
            $order_client = DB::table('order_client')
                ->where('orcl_ord_id', $find_wor->wor_order_id)
                ->update($orcl);
        } else {
            $order_client = true;
        }

        $request_voucher['find_wocl'] = ''; //用友接口上传凭证使用
        // 订单状态为未结算时，可以生成应收账款、结款明细
        if ($ord_info->ord_state == 1 && $find_wor->wocl_sd_virtual_type == 2) {
            // 3.订单应收
            $ord_bill = ReceivableBill::create(
                $user_info, //用户信息
                3, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $find_wor->wor_order_id, //原始id(订单id)
                $find_wor->wor_order_number, //应收账款单号/原始号(订单编号)
                $ord_info->ord_type, //客户类型：1.门店零售 2.来往单位
                $ord_info->ord_client_id, //会员id/来往单位id
                $wocl_client_name, //来往单位名称
                abs($ord_actual_price), //结算金额(应收金额)
                // $genre == 1 ? $find_wor->wocl_assign_price : $ord_info->ord_actual_price, //结算金额(应收金额)
                '', //结款时间
                $ord_info->orcl_acc_subject_id, //会计科目id
                $ord_info->ord_state == 1 ? 0 : $find_wor->wocl_assign_price, //实际金额(应收金额)
                0, //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                $ord_info->ord_remark,  //备注
                $ord_info->ord_state == 1 ? 0 : $find_wor->wocl_assign_price,  //已收金额
                '', //截止时间
                $virtual_ord_plus_minus, //金额正负1正   2负值
                $find_wor->wor_service_type == 4 ? 10 : 1, //显示类型：1订单收款 10订单退款
                1, //是否合并代收：1是2否
                $ord_info->ord_create_time
            );
            $wor_bill = ReceivableBill::create(
                $user_info, //用户信息
                4, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $find_wor->wor_id, //原始id(工单id)
                $find_wor->wor_number, //应收账款单号/原始号(工单编号)
                7, //客户类型：1.门店零售 2.来往单位3.外派门店（加盟店或总店）
                $find_wor->wor_service_shop_id, //派单门店id
                $shop_info->shop_store_name, //派单门店名称
                abs($now_wor_price), //结算金额
                '', //结款时间
                $ord_info->orcl_acc_subject_id, //会计科目id
                $ord_info->ord_state == 1 ? 0 : abs($now_wor_price), //实际金额
                0,  //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                $request['remark'] ? $request['remark'] : '',  //备注
                $ord_info->ord_state == 1 ? 0 : abs($now_wor_price),  //已收金额
                '', //截止时间
                $wor_plus_minus, //金额正负1正   2负值
                4, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
                1, //是否合并代收：1是2否
                $ord_info->ord_create_time
            );
            $goo_state_update = true;
        } else {
            // 订单状态为已结算状态，不生成应收账款
            $wor_bill = true;
            $ord_bill = true;
            $goo_state_update = true;
        }
        if ($total_collection_price > 0 && $find_wor->wocl_sd_virtual_type == 2) {
            $find_wocl = DB::table('work_client')
                ->where('wocl_wor_id', $request['wor_id'])
                ->first(['wocl_client_id', 'wocl_channel_unit', 'wocl_name', 'wocl_acti_id', 'wocl_collect_state']);
            $client_type = 7;
            // 1. 订单代收
            $ord_coll_bill = ReceivableBill::create(
                $user_info, //用户信息
                3, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $find_wor->wor_order_id, //原始id(订单id)
                $find_wor->wor_order_number, //应收账款单号/原始号(订单编号)
                $ord_info->ord_type, //客户类型：1.会员零售 2.来往单位 3.加盟店 4会员零售(工单代收）
                $ord_info->ord_client_id, //会员id/来往单位id
                $wocl_client_name, //来往单位名称
                $total_collection_price, //结算金额(代收金额)
                '', //结款时间
                $ord_info->orcl_acc_subject_id, //会计科目id
                $find_wocl->wocl_collect_state == 1 ? $total_collection_price : 0, //实际金额(未结算:0，已结算：代收金额)
                0, //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                $ord_info->ord_remark,  //备注
                0,  //已收金额
                '', //截止时间
                2, //金额正负1正   2负值
                2, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
                1, //是否合并代收：1是2否
                $ord_info->ord_create_time
            );

            // 2 工单代收，生成工单代收应收账款，判断是否让技师收款
            $recr_id = ReceivableBill::create(
                $user_info, //用户信息
                4, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $find_wor->wor_id, //原始id(工单id)
                $find_wor->wor_number, //应收账款单号/原始号(工单编号)
                $client_type, //客户类型：1.门店零售 2.来往单位 3.加盟店 4会员零售(工单代收）
                $find_wor->wor_service_shop_id, //会员id/来往单位id
                $shop_info->shop_store_name, //来往单位名称
                $total_collection_price, //结算金额
                '', //结款时间
                $find_wocl->wocl_acti_id, //会计科目id
                $find_wocl->wocl_collect_state == 1 ? $total_collection_price : 0, //实际金额
                0, //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                $request['remark'] ? $request['remark'] : '',  //备注
                0,  //已收金额
                '', //截止时间
                1, //金额正负:1正2负值
                3, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
                2, //是否合并代收：1是2否
                $ord_info->ord_create_time //开单时间
            );
        } else {
            $recr_id = true;
            $ord_coll_bill = true;
        }
        // 生成操作记录
        if ($image_change_state == 2) {
            $log_hint = '改图审核通过工单';
        } else {
            $log_hint = '审核通过工单';
        }
        // 生成操作记录
        $edit_record = orderLog($user_info, 0, $request['wor_id'], $log_hint);

        if ($wor_res && $ord_res && $wogo_res && $wocl_id && $edit_record && $ord_bill && $wor_bill && $orgo_res && $goo_state_update && $recr_id && $ord_coll_bill) {
            // 上传数据到凭证列表
            if (config('apiu8cloud.CODE_STARTS') && in_array($user_info->adm_shop_id, config('apiu8cloud.u8cloud_shop'))) {
                // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
                $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
                // 生成凭证单据
                $vore_order_data = WorkOrder::voucherReceipts($user_info, $shop_id, 1, $request['wor_id'], $find_wor->wor_number, $find_wor->wor_order_id, $find_wor->wor_order_number, $ord_actual_price, $old_junk_goo_price, $total_collection_price, '', $find_wor->wor_service_type, $find_wor->wor_type, $find_wor->wocl_client_id, $wocl_client_name);
                // 查询虚拟加盟店门店名称
                $virtual_shop = DB::table('virtual_shop')
                    ->where('vish_id', $find_wor->wor_service_shop_id)
                    ->select('vish_id', 'vish_store_name')
                    ->first();
                $vore_data = WorkOrder::voucherReceipts($user_info, $shop_id, 2, $request['wor_id'], $find_wor->wor_number, $find_wor->wor_order_id, $find_wor->wor_order_number, $now_wor_price, $reduce_total_price, $total_collection_price, '', $find_wor->wor_service_type, $find_wor->wor_type, $virtual_shop->vish_id, $virtual_shop->vish_store_name);
                if (!$vore_order_data || !$vore_data) {
                    deleteImage($new_img_delete); //删除新上传的图片
                    DB::rollBack();
                    return ['code'=>500, 'msg'=>'error', 'data'=>'生成凭证单失败'];
                }
            }
            if (config('apisystem.SYNC_STATE') && $find_wor->wocl_sd_virtual_type == 1) {
                // 如果是速电派单
                if ($ord_info->ord_type == 3) {
                    $lat = DB::table('lat')
                        ->where('lat_aid', $find_wor->wor_service_adm_id)
                        ->first(['lat_lat', 'lat_lon']);
                    // 查询工单的技师完成时间
                    $orlo_time = DB::table('order_log')
                        ->where('orlo_shop_id', $user_info->adm_shop_id)
                        ->where('orlo_wor_id', $request['wor_id'])
                        ->where('orlo_content', '完成')
                        ->value('orlo_time');

                    $adm_data = DB::table('admin')
                        ->where('adm_id', $find_wor->wor_service_adm_id)
                        ->first(['adm_name', 'adm_phone']);
                    $param['serial_number'] = $ord_info->ord_other_system_number;
                    $param['state'] = 5;
                    $param['ip'] = $param['ip'] = getRealIp($request);
                    $param['line'] = $lat->lat_lat . ',' . $lat->lat_lon;
                    $param['install_name'] = $adm_data->adm_name;
                    $param['install_phone'] = $adm_data->adm_phone;
                    $param['app_achieve_time'] = $orlo_time; //APP完成提交时间
                    $param['time'] = date('Y-m-d H:i:s');
                    $server = config('apisystem.server_name') . '/';
                    $find_image_upload = DB::table('image_upload')
                        ->where('imup_wor_id', $request['wor_id'])
                        ->where('imup_delete', 1)
                        ->select('imup_path', 'imup_image_name')
                        ->get()->toArray();
                    $find_image_upload = json_decode(json_encode($find_image_upload), true);
                    foreach ($find_image_upload as $key => $value) {
                        if ($value['imup_path']) {
                            $find_image_upload[$key]['imup_path'] = $server . $value['imup_path'];
                        }
                    }
                    $param['filePic'] = $find_image_upload; //速电模板图片

                    $param['image_change_state'] = $image_change_state; //工单审核图片更改状态：1未上传新图2重新传图
                    $param['token'] = config('apisystem.sd_token');
                    $url = config('apisystem.sd_server_name') . '/index.php/Supply/installLine';
                    $doPost_res = Common::doPost($param, $url);
                    $doPost_res = json_decode($doPost_res);
                    if ($doPost_res->code == 203) {
                        deleteImage($new_img_delete); //删除新上传的图片
                        DB::rollBack();
                        return ['code'=>500, 'msg'=>'error', 'data'=>'等待速电驳回上一次的状态,才能继续审核'];
                    }
                    if ($doPost_res->code != 200) {
                        deleteImage($new_img_delete); //删除新上传的图片
                        DB::rollBack();
                        return ['code'=>500, 'msg'=>'error', 'data'=>'失败'];
                    }
                }
            }

            // 添加新增订单信息的提示
            $inhi_data['inhi_original_adm_id'] = $find_wor->wor_create_id; //原始单号创建人
            $inhi_data['inhi_original_id'] = $request['wor_id']; //原始单id
            $inhi_data['inhi_original_number'] = $find_wor->wor_number; //原始单号
            $inhi_data['inhi_original_state'] = $wor_data['wor_state']; //原始单状态
            $inhi_data['inhi_original_operation'] = '工单审核通过'; //操作
            $inhi_data['inhi_operation_state'] = 15; //操作状态：15工单审核通过
            addInformationHint($user_info, $inhi_data, 2);

            DB::commit();
            Common::addLog($user_info, getRealIp($request), '工单列表', '通过', $find_wor->wor_number . '通过成功');
            return ['code'=>200, 'msg'=>'success', 'data'=>'通过成功'];
        } else {
            deleteImage($new_img_delete); //删除新上传的图片
            DB::rollBack();
            return ['code'=>500, 'msg'=>'error', 'data'=>'通过失败'];
        }
    }

    // 虚拟加盟店改单
    public function editVirtual(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkOrderController;
        $error_message = $verify_data->editShowValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 查询工单信息
        $wor_data = DB::table('work_order as wo')
            ->leftjoin('work_client as o', 'o.wocl_wor_id', '=', 'wo.wor_id')
            ->where('wor_id', $request['wor_id'])
            ->select('wor_number', 'wor_create_id', 'wor_service_type', 'wor_service_sepr_id', 'wor_state', 'wor_service_state', 'wor_pass', 'wor_service_adm_id', 'wor_service_shop_id', 'wor_ware_id', 'wor_order_id', 'wor_order_number', 'wor_remark', 'wor_type', 'wocl_wor_type', 'wocl_sd_virtual_type')
            ->first();
        //订单数据
        $order_data = DB::table('order')
            ->where('ord_id', $wor_data->wor_order_id)
            ->first(['ord_state', 'ord_payment_way']);
        // 判断工单是否存在
        if (empty($wor_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单不存在！']);
        }
        // 结算状态1未结算2已结算3已核销4已收款
        if ($order_data->ord_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单已结算，无法改单！']);
        }
        // 订单类型为服务单类型的可以编辑
        if ($wor_data->wor_service_type != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'订单类型不是服务单，无法改单！']);
        }
        // 不是虚拟加盟店订单
        if ($wor_data->wocl_wor_type != 4) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'不是虚拟加盟店订单,无法改单']);
        }
        //速电派单,无法改单
        if ($wor_data->wocl_sd_virtual_type == 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'速电派单,无法改单']);
        }
        // 服务状态：1待接单2已接单3预约4出发5抵达6完成待审核7完成已驳回8完成通过9终止
        // 技师完成之前可以改单，完成以后不能改单；原来定的改单条件
        if ($wor_data->wor_service_state > 5 &&  $wor_data->wor_service_state != 10) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单已服务完成，无法改单！']);
        }

        //获取用户信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 返回工单数据
        if ($request['type'] == 1) {
            // 锁定之后不可以改单
            if ($wor_data->wor_pass == 4) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单已锁定，无法改单！']);
            }
            // 改单锁定
            $lock_return = $this->editLockUnlock($user_info, $request['wor_id'], 4);
            if ($lock_return['code'] == 500) {
                return response()->json($lock_return);
            }

            // 获取账号id对应的姓名
            $adm_id[] = $wor_data->wor_create_id;
            $adm_id[] = $wor_data->wor_service_adm_id;
            $adm_id = array_filter($adm_id); //如果没有回调函数，默认就是删除数组中值为false的元素
            $find_admin = DB::table('admin')
                ->whereIn('adm_id', $adm_id)
                ->pluck('adm_name', 'adm_id')->toArray();

            $wor_data->wor_create_name = $find_admin[$wor_data->wor_create_id];
            $wor_data->wor_service_adm_name = isset($find_admin[$wor_data->wor_service_adm_id]) ? $find_admin[$wor_data->wor_service_adm_id] : '';

            // 查询服务项目名称
            $wor_data->wor_service_sepr_name = DB::table('service_project')
                ->where('sepr_id', $wor_data->wor_service_sepr_id)
                ->value('sepr_name');
            // 查询服务门店名称 等于4查找虚拟加盟店表
            if ($wor_data->wocl_wor_type == 4) {
                $wor_data->wor_service_shop_name = DB::table('virtual_shop')
                    ->where('vish_id', $wor_data->wor_service_shop_id)
                    ->value('vish_store_name');
            } else {
                $wor_data->wor_service_shop_name = DB::table('shop')
                    ->where('shop_id', $wor_data->wor_service_shop_id)
                    ->value('shop_store_name');
            }

            // 获取工单商品数据
            $wogo_goods = DB::table('work_good')
                ->where('wogo_wor_id', $request['wor_id'])
                ->where('wogo_state', '!=', 2)
                ->get([
                    'wogo_id', 'wogo_waon_class', 'wogo_goo_id', 'wogo_goo_name', 'wogo_goo_type', 'wogo_goo_goods_encode',
                    'wogo_goo_price', 'wogo_state', 'wogo_collection_price', 'wogo_recycle_price', 'wogo_goo_amount',
                    'wogo_goo_inventory', 'wogo_recycle_quantity', 'wogo_is_recycle', 'wogo_tem_goo_name as tem_goo_name'
                ]);

            $order_data = DB::table('order_goods')
                ->where('orgo_ord_id', $wor_data->wor_order_id)
                ->where('orgo_state', '!=', 2)
                ->pluck('orgo_goo_price', 'orgo_goo_id')->toArray();



            foreach ($wogo_goods as $key => $value) {
                $wogo_goods[$key]->orgo_goo_price = $order_data[$value->wogo_goo_id] ?? 0;
            }

            // 获取工单技师代收状态
            $wor_client = DB::table('work_client')
                ->where('wocl_wor_id', $request['wor_id'])
                ->first(['wocl_collect_state', 'wocl_name', 'wocl_phone', 'wocl_car_num', 'wocl_province', 'wocl_city', 'wocl_county', 'wocl_address', 'wocl_wor_type', 'wocl_standby_battery_type', 'wocl_channel_unit']);

            if ($wor_client->wocl_wor_type == 3) {
                $wor_client->wocl_channel_unit = '北京速电快保';
            }
            $data['wor_client'] = $wor_client;
            $wor_data->wocl_collect_state = $wor_client->wocl_collect_state;
            $wor_data->standby_battery_type = $wor_client->wocl_standby_battery_type;
            $data['wor_data'] = $wor_data;
            $data['wogo_goods'] = $wogo_goods;
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        } elseif ($request['type'] == 3) {
            // 改单取消，取消锁定
            $lock_return = $this->editLockUnlock($user_info, $request['wor_id'], 1);
            return response()->json($lock_return);
        }

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

        //判断是否为外派工单
        $join_ord_data = DB::table('work_client')
            ->where('wocl_wor_id', $request['wor_id'])
            ->first(['wocl_join_ord_id', 'wocl_wor_type']);
        // 处理提交的商品数据
        $goo_all_price = 0; //商品总金额
        $goo_all_quantity = 0; //商品总数量
        $goo_all_collection = 0; //总的代收金额
        $recycle_number = 0; //工单计划总的旧货回收数量
        $recycle_price = 0; //工单计划总的旧货回收金额
        $wor_is_recycle = 2; //是否回收：1.回收2.不回收
        $goo_order_all_price = 0; //订单金额

        $del_wogo_id = [];
        $del_goo_id = [];
        $del_is_recycle = [];
        $del_goo_amount = [];
        $del_goo_inventory = [];
        $del_goo_price = [];
        $del_collection_price = [];
        $del_order_goo_price = [];
        $add_goo_id = [];
        $add_goo_inventory = [];
        $add_goo_is_recycle = [];
        $add_goo_price = [];
        $add_goo_amount = [];
        $add_goo_collection_price = [];
        $add_goo_name = [];
        $add_goo_goods_encode = [];
        $add_goo_data = [];

        $eidt_wogo_id = [];
        $eidt_wogo_goo_price = [];
        $eidt_orgo_goo_price = [];
        $eidt_wogo_collection_price = [];
        $eidt_wogo_goo_id = [];
        foreach ($request['wogo_goo_id'] as $key => $value) {
            if (!is_numeric($value) || !is_numeric($request['wogo_goo_price'][$key]) || !is_numeric($request['wogo_goo_amount'][$key]) || !in_array($request['wogo_is_recycle'][$key], [1, 2]) || !is_numeric($request['wogo_recycle_quantity'][$key]) || !is_numeric($request['wogo_id'][$key]) || !in_array($request['wogo_state'][$key], [1, 2, 5, 6]) || !is_numeric($request['wogo_collection_price'][$key]) || !is_numeric($request['orgo_goo_price'][$key])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品参数类型错误']);
            }
            // 判断是否有删除的商品 wogo_state 商品状态1.正常 2.删除
            if ($request['wogo_state'][$key] == 2) {
                // 改单时删除的商品信息
                $del_wogo_id[] = $request['wogo_id'][$key]; //删除的商品工单主键id
                $del_goo_id[] = $value; //删除的商品id
                $del_goo_amount[$value] = $request['wogo_goo_amount'][$key]; //删除的商品数量
                $del_goo_price[$value] = $request['wogo_goo_price'][$key]; //删除的商品工单金额
                $del_order_goo_price[$value] = $request['orgo_goo_price'][$key]; //删除的商品金额
                $del_collection_price[$value] = $request['wogo_collection_price'][$key]; //删除的商品代收金额
            } else {
                // 需要保存的商品数据，包括新添加的商品，更改的商品
                // 没有被删除的都计算到  工单结算金额内
                $goo_all_price += $request['wogo_goo_price'][$key] * $request['wogo_goo_amount'][$key];
                $goo_order_all_price += $request['orgo_goo_price'][$key] * $request['wogo_goo_amount'][$key];
                // 没有被删除的都计算到  总的商品数量内
                $goo_all_quantity += $request['wogo_goo_amount'][$key];
                // 没有被删除的都计算到  代收金额，代收金额不乘以数量
                $goo_all_collection += $request['wogo_collection_price'][$key];

                if ($request['wogo_id'][$key] != 0) {
                    $eidt_wogo_id[] = $request['wogo_id'][$key];
                    $eidt_wogo_goo_price[] = $request['wogo_goo_price'][$key];
                    $eidt_orgo_goo_price[] = $request['orgo_goo_price'][$key];
                    $eidt_wogo_collection_price[] = $request['wogo_collection_price'][$key];
                    $eidt_wogo_goo_id[] = $value;
                }

                // 判断是否有新增的商品
                if ($request['wogo_id'][$key] == 0) {
                    $find_goods_data = DB::table('goods')
                        ->where('goo_id', $value)
                        ->first(['goo_name', 'goo_goods_encode', 'goo_type', 'goo_ampere_hour', '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;
                        }
                    }
                    // 工单商品主键id为0的，说明是新添加的商品
                    $add_goo_id[] = $value; //新增商品的id
                    $add_goo_is_recycle[] = $request['wogo_is_recycle'][$key]; //新增商品的是否回收
                    $add_goo_price[] = $request['wogo_goo_price'][$key]; //新增商品的售价
                    $add_order_goo_price[] = $request['orgo_goo_price'][$key]; //新增商品的订单售价
                    $add_goo_amount[] = $request['wogo_goo_amount'][$key]; //新增商品的数量
                    $add_goo_collection_price[] = $request['wogo_collection_price'][$key]; //新增商品的代收金额
                    $add_goo_name[] = $find_goods_data->goo_name; //新增商品名称
                    $add_goo_goods_encode[] = $find_goods_data->goo_goods_encode; //新增商品的检索编码
                    $add_goo_type[] = $find_goods_data->goo_type; //新增商品类型

                    $add_goo_data['recycle_quantity'][$value] = $request['wogo_recycle_quantity'][$key]; //新增回收数量
                    $add_goo_data['goo_state'][$value] = $request['wogo_state'][$key]; //新增商品状态
                    $add_goo_data['goo_type'][$value] = $find_goods_data->goo_type; //新增商品类型
                    $add_goo_data['goo_name'][$value] = $find_goods_data->goo_name; //新增商品名称
                    $add_goo_data['goo_goods_encode'][$value] = $find_goods_data->goo_goods_encode; //新增商品的检索编码
                    $add_goo_data['goo_amount'][$value] = $request['wogo_goo_amount'][$key]; //新增商品的数量
                    $add_goo_data['goo_price'][$value] = $request['wogo_goo_price'][$key]; //新增商品的售价
                    $add_goo_data['goo_order_price'][$value] = $request['orgo_goo_price'][$key]; //新增商品的售价
                    $add_goo_data['goo_is_recycle'][$value] = $request['wogo_is_recycle'][$key]; //新增商品的是否回收
                    $add_goo_data['goo_inventory'][$value] = $request['wogo_goo_inventory'][$key]; //商品出库方式1.良品 2优先
                    $add_goo_data['goo_collection_price'][$value] = $request['wogo_collection_price'][$key]; //新增商品的代收金额
                    $add_goo_data['goo_ampere_hour'][$value] = $find_goods_data->goo_ampere_hour; //新增的商品安时数
                    if (!empty($request['tem_goo_name'][$key])) {
                        $tem_goo_name = $request['tem_goo_name'][$key];
                    } else {
                        $tem_goo_name = '';
                    }
                    $add_goo_data['tem_goo_name'][$value] = $tem_goo_name;
                }
            }
        }

        // 判断是否为加盟店账号,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. 处理发货单的数据
        DB::beginTransaction();

        //客户信息
        $ord_client = DB::table('order_client')
            ->where('orcl_ord_id', $wor_data->wor_order_id)
            ->first(['orcl_channel_unit', 'orcl_name', 'orcl_phone', 'orcl_id']);

        // 获取到当前工单的订单信息
        $ord_info = DB::table('order')
            ->where('ord_id', $wor_data->wor_order_id)
            ->first(['ord_client_id']);

        if (!empty($del_wogo_id)) {
            // 2.1 存在工单商品被删除的情况，需要把删除的商品生成退换回收单，回收到仓库
            // 1 将工单商品表删除的商品,直接删除
            $update_wogo_del = DB::table('work_good')
                ->where('wogo_wor_id', $request['wor_id'])
                ->whereIn('wogo_id', $del_wogo_id)
                ->delete();
        } else {
            $update_wogo_del = true;
        }

        // 2.2 有新添加的工单商品，工单商品表新增商品
        if (!empty($add_goo_id)) {
            foreach ($add_goo_id as $key => $value) {
                $wogo_data[$key]['wogo_wor_id'] = $request['wor_id']; //工单id
                $wogo_data[$key]['wogo_goo_id'] = $value; //商品id
                $wogo_data[$key]['wogo_is_recycle'] = $add_goo_data['goo_is_recycle'][$value]; //是否回收：1回收2不回收
                $wogo_data[$key]['wogo_goo_price'] = $add_goo_data['goo_price'][$value] * 100; //商品售价
                $wogo_data[$key]['wogo_goo_amount'] = $add_goo_data['goo_amount'][$value]; //商品数量
                $wogo_data[$key]['wogo_collection_price'] = $add_goo_data['goo_collection_price'][$value] * 100; //商品代收金额
                $wogo_data[$key]['wogo_recycle_quantity'] = $add_goo_data['recycle_quantity'][$value]; //回收数量
                $wogo_data[$key]['wogo_state'] = $add_goo_data['goo_state'][$value]; //商品状态
                $wogo_data[$key]['wogo_update_time'] = date('Y-m-d H:i:s');
                $wogo_data[$key]['wogo_goo_name'] = $add_goo_data['goo_name'][$value]; //商品名称
                if (!empty($add_goo_data['tem_goo_name'][$value])) {
                    $tem_goo_name = $add_goo_data['tem_goo_name'][$value];
                } else {
                    $tem_goo_name = '';
                }
                $wogo_data[$key]['wogo_tem_goo_name'] = $tem_goo_name; //商品别名
                $wogo_data[$key]['wogo_goo_goods_encode'] = $add_goo_data['goo_goods_encode'][$value]; //检索编码
                $wogo_data[$key]['wogo_goo_type'] = $add_goo_data['goo_type'][$value]; //商品类型
            }
            $wogo_res = DB::table('work_good')->insert($wogo_data);
        } else {
            $wogo_res = true;
        }
        // 2.3 工单表数据做修改
        $wor_update_data['wor_service_sepr_id'] = $request['wor_service_sepr_id']; // 服务项目id
        // 新订单,未派单,待接单/已派单的状态下,服务技师可以更改
        $wor_update_data['wor_service_adm_id'] = $request['wor_service_adm_id'];
        $wor_update_data['wor_service_state'] = 1; //服务状态：1待接单2已接单3预约4出发5抵达6完成待审核
        $wor_update_data['wor_state'] = 3; //1.新订单 2未派单 3待接单/已派单
        $wor_update_data['wor_actual_price'] = $goo_all_price * 100; // 工单结算金额（单位：分）
        $wor_update_data['wor_recycle_number'] = $recycle_number; // 工单计划总的旧货回收数量
        $wor_update_data['wor_is_recycle'] = $wor_is_recycle; // 1.回收2.不回收
        $wor_update_data['wor_goo_amount'] = $goo_all_quantity; //总的商品数量
        $wor_update_data['wor_collection_price'] = $goo_all_collection * 100; //总的代收金额
        $wor_update_data['wor_pass'] = 1; //审核：1.待审核 2.合格 3.不合格 4锁定
        $wor_update_data['wor_update_time'] = date('Y-m-d H:i:s');
        $wor_res = DB::table('work_order')
            ->where('wor_id', $request['wor_id'])
            ->update($wor_update_data);
        if (!empty($eidt_wogo_id)) {
            foreach ($eidt_wogo_id as $key => $value) {
                $wogo['wogo_goo_price'] = $eidt_wogo_goo_price[$key] * 100;
                $wogo['wogo_collection_price'] = $eidt_wogo_collection_price[$key] * 100;
                $wogo['wogo_update_time'] = date('Y-m-d H:i:s');
                $wogo_res = DB::table('work_good')
                    ->where('wogo_id', $value)
                    ->update($wogo);

                $orgo['orgo_goo_price'] = $eidt_orgo_goo_price[$key] * 100;
                $orgo['orgo_collection_price'] = $eidt_wogo_collection_price[$key] * 100;
                $orgo['orgo_update_time'] = date('Y-m-d H:i:s');
                $orgo_res = DB::table('order_goods')
                    ->where('orgo_goo_id', $eidt_wogo_goo_id[$key])
                    ->where('orgo_ord_id', $wor_data->wor_order_id)
                    ->update($orgo);
                if (!$wogo_res || !$orgo_res) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'改单失败']);
                }
            }
        }
        // 3.1 订单商品表中减去删除的商品数量
        $del_sql = 'UPDATE `faster_order_goods` SET ';
        $goo_quantity = '';
        $recycle_quantity = '';
        $update_time = '';
        $goo_id = '';
        if (!empty($del_goo_id)) {
            foreach ($del_goo_id as $key => $value) {
                // 减去商品数量
                $goo_quantity = $goo_quantity . ' WHEN ' . $value;
                $goo_quantity = $goo_quantity . ' THEN orgo_goo_quantity - ' . $del_goo_amount[$value];

                // 如果回收 减去商品回收数量
                if ($del_is_recycle[$key] == 1) {
                    $recycle_quantity = $recycle_quantity . ' WHEN ' . $value;
                    $recycle_quantity = $recycle_quantity . ' THEN orgo_recycle_quantity - ' . $del_goo_amount[$value];
                }

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

                //要更改的商品id
                $goo_id = $goo_id . $value . ',';
            }
            $del_sql = $del_sql . ' `orgo_goo_quantity`=  CASE `orgo_goo_id` ' . $goo_quantity . ' END,';
            if (!empty($recycle_quantity)) {
                $del_sql = $del_sql . ' `orgo_recycle_quantity`=  CASE `orgo_goo_id` ' . $recycle_quantity . ' END,';
            }
            $del_sql = $del_sql . ' `orgo_update_time`=  CASE `orgo_goo_id` ' . $update_time . ' END';
            $del_sql = $del_sql . ' WHERE `orgo_ord_id` = ' . $wor_data->wor_order_id . ' AND `orgo_state` = 1 AND `orgo_goo_id` IN (' . trim($goo_id, ',') . ')';
            $orgo_res = DB::update($del_sql);
        } else {
            $orgo_res = true;
        }

        // 3.2 订单商品表中减去删除的商品数量后如果为0,商品状态改为删除状态
        // 查询订单商品表中商品数量为0的数据
        $find_orgo_data = DB::table('order_goods')
            ->where('orgo_ord_id', $wor_data->wor_order_id)
            ->where('orgo_state', 1)
            ->get(['orgo_id', 'orgo_goo_quantity', 'orgo_goo_id'])->toArray();
        $ord_goo_id = []; //订单商品表原有的商品id
        $del_orgo_id = []; //订单商品表商品数量为0的
        foreach ($find_orgo_data as $key => $value) {
            if ($value->orgo_goo_quantity == 0) {
                $del_orgo_id[] = $value->orgo_id;
            } else {
                $ord_goo_id[] = $value->orgo_goo_id;
            }
        }

        if (!empty($del_orgo_id)) {
            // 将订单商品中商品数量为0的，删除订单商品数据
            $del_orgo_res = DB::table('order_goods')
                ->whereIn('orgo_id', $del_orgo_id)
                ->delete();
        } else {
            $del_orgo_res = true;
        }

        // 3.3 改单有新添加的商品，订单商品表中加上新增的商品数量(如果没有,添加新的商品数据)
        if (!empty($add_goo_id)) {
            // 有新添加的商品，求出订单商品表中没有的商品
            $diff_goo_id = array_diff($add_goo_id, $ord_goo_id);
            $add_sql = 'UPDATE `faster_order_goods` SET ';
            $add_goo_quantity = '';
            $add_recycle_quantity = '';
            $add_update_time = '';
            $update_goo_id = '';
            foreach ($add_goo_id as $key => $value) {
                if (in_array($value, $diff_goo_id)) {
                    // 订单商品表中 没有的商品(新增)
                    $orgo_data[$key]['orgo_ware_id'] = $wor_data->wor_ware_id; //仓库id
                    $orgo_data[$key]['orgo_ord_id'] = $wor_data->wor_order_id; //订单id
                    $orgo_data[$key]['orgo_order_number'] = $wor_data->wor_order_number; //订单编号
                    $orgo_data[$key]['orgo_goo_id'] = $value; //商品id
                    $orgo_data[$key]['orgo_goo_price'] = $add_goo_data['goo_order_price'][$value] * 100; //商品售价
                    $orgo_data[$key]['orgo_goo_quantity'] = $add_goo_data['goo_amount'][$value]; //商品数量
                    $orgo_data[$key]['orgo_is_recycle'] = $add_goo_data['goo_is_recycle'][$value]; //是否回收：1回收2不回收
                    $orgo_data[$key]['orgo_recycle_quantity'] = $add_goo_data['recycle_quantity'][$value]; //回收数量
                    $orgo_data[$key]['orgo_collection_price'] = $add_goo_data['goo_collection_price'][$value] * 100; //商品代收金额
                    $orgo_data[$key]['orgo_can_assign_quantity'] = 0; //剩余可以派工单的商品数量
                    $orgo_data[$key]['orgo_goo_name'] = $add_goo_data['goo_name'][$value]; //商品名称
                    $orgo_data[$key]['orgo_goo_goods_encode'] = $add_goo_data['goo_goods_encode'][$value]; //检索编码
                    $orgo_data[$key]['orgo_goo_type'] = $add_goo_data['goo_type'][$value]; //商品类型
                    $orgo_data[$key]['orgo_goo_ampere_hour'] = $add_goo_data['goo_ampere_hour'][$value]; //商品安时数
                    if (!empty($add_goo_data['tem_goo_name'][$value])) {
                        $tem_goo_name = $add_goo_data['tem_goo_name'][$value];
                    } else {
                        $tem_goo_name = '';
                    }
                    $orgo_data[$key]['orgo_tem_goo_name'] = $tem_goo_name;
                } else {
                    // 订单商品表中 存在的商品(加数量)
                    $add_goo_quantity = $add_goo_quantity . ' WHEN ' . $value;
                    $add_goo_quantity = $add_goo_quantity . ' THEN orgo_goo_quantity + ' . $add_goo_amount[$key];

                    // 如果回收 增加商品回收数量
                    if ($add_goo_is_recycle[$key] == 1) {
                        $add_recycle_quantity = $add_recycle_quantity . ' WHEN ' . $value;
                        $add_recycle_quantity = $add_recycle_quantity . ' THEN orgo_recycle_quantity + ' . $add_goo_amount[$key];
                    }

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

                    //要更改的商品id
                    $update_goo_id = $update_goo_id . $value . ',';
                }
            }

            // 商品添加数量
            if (empty($update_goo_id)) {
                $add_orgo_num = true;
            } else {
                $add_sql = $add_sql . ' `orgo_goo_quantity`=  CASE `orgo_goo_id` ' . $add_goo_quantity . ' END,';
                $add_sql = $add_sql . ' `orgo_recycle_quantity`=  CASE `orgo_goo_id` ' . $add_recycle_quantity . ' END,';
                $add_sql = $add_sql . ' `orgo_update_time`=  CASE `orgo_goo_id` ' . $add_update_time . ' END';
                $add_sql = $add_sql . ' WHERE `orgo_ord_id` = ' . $wor_data->wor_order_id .
                    ' AND `orgo_goo_id` IN (' . trim($update_goo_id, ',') . ')';
                $add_orgo_num = DB::update($add_sql);
            }
        } else {
            $add_orgo_num = true;
        }

        // 商品新增
        if (empty($orgo_data)) {
            $add_orgo_res = true;
        } else {
            $add_orgo_res = DB::table('order_goods')->insert($orgo_data);
        }

        // 3.4 修改订单表数据(合计金额,商品总数量)
        // 查询出该订单下所有的商品
        $all_goods = DB::table('order_goods')
            ->where('orgo_ord_id', $wor_data->wor_order_id)
            ->where('orgo_state', 1)
            ->get(['orgo_goo_price', 'orgo_goo_quantity', 'orgo_collection_price']);
        $price_sum = 0;
        $quantity_sum = 0;
        $collection_sum = 0;
        foreach ($all_goods as $key => $value) {
            // 合计金额
            $price_sum += $value->orgo_goo_quantity * $value->orgo_goo_price;
            // 商品总数量
            $quantity_sum += $value->orgo_goo_quantity;
            // 代收金额
            $collection_sum += $value->orgo_collection_price;
        }

        $update_ord['ord_actual_price'] = $price_sum; // 结算金额（单位：分）
        $update_ord['ord_order_price'] = $price_sum; // 合计金额（单位：分）
        $update_ord['ord_goods_quantity'] = $quantity_sum; // 商品总数量
        $update_ord['ord_collection_price'] = $collection_sum; // 代收金额
        $update_ord['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_res = DB::table('order')
            ->where('ord_id', $wor_data->wor_order_id)
            ->update($update_ord);

        // 添加操作记录
        $order_record = orderLog($user_info, $wor_data->wor_order_id, 0, '改单');
        $work_record = orderLog($user_info, 0, $request['wor_id'], '改单');

        if ($order_record && $work_record && $ord_res && $add_orgo_res && $add_orgo_num && $del_orgo_res && $orgo_res && $wor_res && $wogo_res  && $update_wogo_del) {
            $adm_phone =  DB::table('admin')
                ->where('adm_id', $request['wor_service_adm_id'])
                ->value('adm_phone');
            $push_name['alias'][] = $adm_phone; //发送对象
            $result_push = pushMessage($push_name, '您有新的工单：' . $wor_data->wor_number . ' 请注意查收');

            // 添加新增订单信息的提示
            $inhi_data['inhi_original_adm_id'] = $wor_data->wor_create_id; //原始单号创建人
            $inhi_data['inhi_original_id'] = $request['wor_id']; //原始单id
            $inhi_data['inhi_original_number'] = $wor_data->wor_number; //原始单号
            $inhi_data['inhi_original_state'] = $wor_data->wor_state; //原始单状态
            $inhi_data['inhi_original_operation'] = '工单改单'; //操作
            $inhi_data['inhi_operation_state'] = 13; //操作状态：13工单改单
            addInformationHint($user_info, $inhi_data, 2);

            Common::addLog($user_info, getRealIp($request), '工单列表', '改单', '改单：' . $wor_data->wor_number . '成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'改单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'改单失败']);
        }
    }

    // 强行终止 虚拟加盟店
    public function forceTermination(Request $request)
    {
        // 使用验证器 验证数据
        $verify_data = new VerifyWorkOrderController;
        $error_message = $verify_data->terminationValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>$error_message, 'data'=>'{}']);
        }

        // 查询工单表数据
        $work_data = DB::table('work_order')
            ->where('wor_id', $request['wor_id'])
            ->select('wor_service_state', 'wor_state', 'wor_cid', 'wor_superior_shop_id', 'wor_shop_id', 'wor_create_id', 'wor_order_id', 'wor_order_number', 'wor_service_shop_id', 'wor_service_sepr_id', 'wor_service_type', 'wor_ware_id', 'wor_pass', 'wor_recycle_number', 'wor_actual_price', 'wor_is_recycle', 'wor_type', 'wor_goo_amount', 'wor_remark', 'wor_collection_price', 'wor_plus_minus', 'wor_collection_bill', 'wor_create_id', 'wor_number')
            ->first();
        // wor_service_state 服务状态：1待接单2已接单3预约4出发5抵达6完成待审核7完成已驳回8完成通过9终止10锁定11速电撤销回收
        if (!in_array($work_data->wor_service_state, [1, 2, 3, 4, 5, 9, 10])) {
            // 工单状态为：4出发5抵达10锁定 的时候可以终止
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'完成后不可终止']);
        }

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

        DB::beginTransaction();

        $sd_repeal_order = false; //速电是否撤销订单，true撤销，false没有撤销

        // 外派工单状态修改
        $join_wor = DB::table('work_client')
            ->where('wocl_wor_id', $request['wor_id'])
            ->first(['wocl_join_wor_id', 'wocl_wor_type']);
        if ($join_wor->wocl_wor_type == 4 || $work_data->wor_state == 3) {
            $wor_update_data['wor_service_state'] = 0; //修改服务状态为终止
            $wor_update_data['wor_state'] = 2; //修改状态为终止
            $wor_update_data['wor_service_adm_id'] = 0; //修改状态为终止
        } else {
            $wor_update_data['wor_service_state'] = 9; //修改服务状态为终止
            $wor_update_data['wor_state'] = 11; //修改状态为终止
        }
        // wor_service_state 服务状态：1待接单2已接单3预约4出发5抵达6完成待审核7完成已驳回8完成通过9终止10锁定11速电撤销回收
        if ($work_data->wor_service_state == 10) {
            // 判断是系统订单或是速电派单
            // 订单类型：1门店零售2渠道单位3速电派单
            if ($work_data->wor_type == 3) {
                // 速电派单，判断工单对应的订单是否已撤销
                // ord_wor_state 订单的工单状态1未派工单2服务中3售后中4已完成5无工单6审核活动7待接单8锁定9速电撤销回收
                $ord_wor_state = DB::table('order')
                    ->where('ord_id', $work_data->wor_order_id)
                    ->value('ord_wor_state');
                if ($ord_wor_state == 9) {
                    // 速电已经撤销回收当前订单
                    // 工单状态改成已撤销，服务状态改成撤销
                    $sd_repeal_order = true;
                    $wor_data['wor_service_state'] = 11;
                    $wor_data['wor_state'] = 13;

                    $wor_update_data['wor_service_state'] = 11;
                    $wor_update_data['wor_state'] = 13;
                // $wor_update_data['wor_service_adm_id'] = 0;
                } else {
                    // 速电没有撤销回收当前订单
                    // 工单状态是锁定状态，锁定前的状态改成未派单状态
                    $wor_data['wor_service_state'] = 0;
                    $wor_data['wor_state'] = 12; //状态为 锁定
                    if ($join_wor->wocl_wor_type == 4 && $ord_wor_state == 8) {
                        $wor_update_data['wor_state'] = 12; //状态为 锁定
                        $wor_update_data['wor_service_adm_id'] = 0; //修改状态为终止
                    }
                }
            } else {
                $wor_data['wor_service_state'] = 0;
                $wor_data['wor_state'] = 12; //状态为 锁定
            }
        } else {
            $wor_data['wor_service_state'] = 0;
            $wor_data['wor_state'] = 2; //状态为 未派单
        }
        // 1.工单表提交的工单修改为终止
        $wor_update_data['wor_update_time'] = date('Y-m-d H:i:s');
        $wor_update_data['wor_achieve_time'] = date('Y-m-d H:i:s'); //将终止时间存进完成时间字段中
        $wor_update_res = DB::table('work_order')
            ->where('wor_id', $request['wor_id'])
            ->update($wor_update_data);

        if (isset($join_wor->wocl_wor_type) && $join_wor->wocl_wor_type == 2) {
            $join_wor_res = DB::table('work_order')
                ->where('wor_id', $join_wor->wocl_join_wor_id)
                ->update($wor_update_data);
            $order_record_res = orderLog($user_info, 0, $join_wor->wocl_join_wor_id, '终止');
        } else {
            $join_wor_res = true;
            $order_record_res = true;
        }

        // 2.给客户发送过出发短信的话 将短信状态改为终止
        // 查询发送短信数据
        $find_loc = DB::table('location_link')
            ->where('loc_wor_id', $request['wor_id'])
            ->where('loc_state', 1)
            ->select('loc_id')
            ->first();
        if ($find_loc) {
            // 将短信状态改为终止
            $loc_edit_data['loc_state'] = 2;
            $loc_edit_data['loc_update_time'] = date('Y-m-d H:i:s');
            $loc_update_res = DB::table('location_link')
                ->where('loc_id', $find_loc->loc_id)
                ->update($loc_edit_data);
        } else {
            $loc_update_res = true;
        }
        // 3. 电话提醒表 清除技师id 技师电话
        $phre_edit_data['phre_service_adm_id'] = 0;
        $phre_edit_data['phre_service_phone'] = '';
        $phre_edit_data['phre_update_time'] = date('Y-m-d H:i:s');
        $phre_update_res = DB::table('phone_remind')
            ->where('phre_phone_type', 1)
            ->where('phre_wor_id', $request['wor_id'])
            ->update($phre_edit_data);
        // 4. 此工单有未发货的发货单 则作废
        $find_dego_data = DB::table('dispatch_bill')
            ->where('dego_wor_id', $request['wor_id'])
            ->where('dego_order_type', 2)
            ->where('dego_type', 1)
            ->first(['dego_id', 'dego_out_ware_id']);
        // 查询工单商品数据
        $work_good = DB::table('work_good')
            ->where('wogo_wor_id', $request['wor_id'])
            ->where('wogo_state', '<>', 2)
            ->get()->toArray();
        // 生成新的工单
        $wor_number = Common::workRule($user_info);
        $wor_data['wor_cid'] = $work_data->wor_cid;
        $wor_data['wor_superior_shop_id'] = $work_data->wor_superior_shop_id;
        $wor_data['wor_shop_id'] = $work_data->wor_shop_id;
        $wor_data['wor_create_id'] = $work_data->wor_create_id;
        $wor_data['wor_number'] = $wor_number; //工单编号
        $wor_data['wor_order_id'] = $work_data->wor_order_id; //订单id
        $wor_data['wor_order_number'] = $work_data->wor_order_number; //订单号
        $wor_data['wor_service_shop_id'] = $work_data->wor_service_shop_id; //服务门店id
        $wor_data['wor_service_sepr_id'] = $work_data->wor_service_sepr_id; //服务项目id
        // $wor_data['wor_service_adm_id'] = $work_data->wor_service_adm_id;//服务技师id
        $wor_data['wor_service_type'] = $work_data->wor_service_type;

        $wor_data['wor_ware_id'] = $work_data->wor_ware_id; //仓库id
        $wor_data['wor_pass'] = $work_data->wor_pass; // 审核：1.待审核 2.合格 3.不合格
        $wor_data['wor_recycle_number'] = $work_data->wor_recycle_number; // 工单计划总的旧货回收数量
        $wor_data['wor_actual_price'] = $work_data->wor_actual_price; //工单结算金额（单位：分）
        $wor_data['wor_is_recycle'] = $work_data->wor_is_recycle; // 1.回收2.不回收
        $wor_data['wor_type'] = $work_data->wor_type;
        $wor_data['wor_goo_amount'] = $work_data->wor_goo_amount; //总的商品数量
        $wor_data['wor_remark'] = $work_data->wor_remark; //工单备注
        $wor_data['wor_collection_price'] = $work_data->wor_collection_price; //代收金额（单位：分）
        $wor_data['wor_plus_minus'] = $work_data->wor_plus_minus; //金额正负：1正值2负值
        $wor_data['wor_collection_bill'] = $work_data->wor_collection_bill; //是否代收账单：1正常工单2代收账单
        // 5. 工单表添加新数据
        if ($sd_repeal_order || ($join_wor->wocl_wor_type == 4) || $work_data->wor_state == 3) {
            // 如果速电撤销订单，不生成新的工单
            $wor_id = true;
        } else {
            $wor_id = DB::table('work_order')->insertGetId($wor_data);
        }
        // 6. 工单商品表添加新数据
        foreach ($work_good as $key => $value) {
            $wogo_add_data[$key]['wogo_wor_id'] = $wor_id;
            $wogo_add_data[$key]['wogo_ware_id'] = $value->wogo_ware_id;
            $wogo_add_data[$key]['wogo_waon_class'] = $value->wogo_waon_class;
            $wogo_add_data[$key]['wogo_actual_goo_id'] = $value->wogo_actual_goo_id;
            $wogo_add_data[$key]['wogo_wago_id'] = $value->wogo_wago_id;
            $wogo_add_data[$key]['wogo_goo_id'] = $value->wogo_goo_id;
            $wogo_add_data[$key]['wogo_is_recycle'] = $value->wogo_is_recycle;
            $wogo_add_data[$key]['wogo_goo_name'] = $value->wogo_goo_name;
            $wogo_add_data[$key]['wogo_tem_goo_name'] = $value->wogo_tem_goo_name;
            $wogo_add_data[$key]['wogo_goo_goods_encode'] = $value->wogo_goo_goods_encode;
            $wogo_add_data[$key]['wogo_goo_type'] = $value->wogo_goo_type;
            $wogo_add_data[$key]['wogo_state'] = $value->wogo_state;
            $wogo_add_data[$key]['wogo_goo_price'] = $value->wogo_goo_price;
            $wogo_add_data[$key]['wogo_collection_price'] = $value->wogo_collection_price;
            $wogo_add_data[$key]['wogo_recycle_price'] = $value->wogo_recycle_price;
            $wogo_add_data[$key]['wogo_goo_amount'] = $value->wogo_goo_amount;
            $wogo_add_data[$key]['wogo_goo_inventory'] = $value->wogo_goo_inventory;
            $wogo_add_data[$key]['wogo_assign_price'] = $value->wogo_assign_price;
            $wogo_add_data[$key]['wogo_remark'] = $value->wogo_remark;
            $wogo_add_data[$key]['wogo_update_time'] = date('Y-m-d H:i:s');
        }
        if ($sd_repeal_order || ($join_wor->wocl_wor_type == 4) || $work_data->wor_state == 3) {
            // 如果速电撤销订单，不生成新的工单
            $wogo_res = true;
        } else {
            $wogo_res = DB::table('work_good')->insert($wogo_add_data);
        }
        // 7.工单客户表添加数据
        $work_client = DB::table('work_client')
            ->where('wocl_wor_id', $request['wor_id'])
            ->first();
        $wocl_data = (array)$work_client;
        unset($wocl_data['wocl_id']);
        $wocl_data['wocl_wor_id'] = $wor_id;
        if ($work_data->wor_service_state == 10) {
            $wocl_data['wocl_before_wor_state'] = 2;
        }
        $wocl_data['wocl_update_time'] = date('Y-m-d H:i:s');
        if ($sd_repeal_order || ($join_wor->wocl_wor_type == 4) || $work_data->wor_state == 3) {
            // 如果速电撤销订单，不生成新的工单
            $wocl_res = true;
        } else {
            $wocl_res = DB::table('work_client')->insert($wocl_data);
        }

        // 有未发货的发货单 对发货单进行修改
        if (!empty($find_dego_data->dego_id)) {
            // 作废原来的发货单
            $dego_edit_data['dego_type'] = 3;
            $dego_edit_data['dego_update_time'] = date('Y-m-d H:i:s');
            $dego_update_res = DB::table('dispatch_bill')
                ->where('dego_id', $find_dego_data->dego_id)
                ->update($dego_edit_data);
            $lock_turn_normal = true;
        } elseif ($join_wor->wocl_wor_type == 4) {
            $lock_turn_normal = true;
            $dego_update_res = true;
        } else {
            // 没有未发货的发货单
            $dego_update_res = true;
            $lock_turn_normal = true;
            // 查看工单选择的仓库类型，如果是移动仓库不需要更改，如果是固定仓库需要更改
            // ware_type 仓库类型：1固定仓2移动仓
            $ware_type = DB::table('warehouse')
                ->where('ware_id', $work_data->wor_ware_id)
                ->value('ware_type');
            // 选的是固定仓库，工单对应的发货单已经发货
            // 订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单 7救援单
            // 服务单、销售单、换货单有发货单需要发货，救援单可能有发货单需要发货，其他类型没有发货单不需要处理
            if ($ware_type == 1 && in_array($work_data->wor_service_type, [1, 2, 3, 7])) {
                //wogo_state 商品状态1正常2删除3回收的商品4换货商品5赠品商品6备用电池7临时商品8旧货商品
                // 工单商品有数据，生成退换回收单，后台入库
                if (!empty($work_good)) {
                    // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
                    $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
                    // 查询当前技师的移动仓库id
                    $ware_id = DB::table('warehouse')
                        ->where('ware_cid', $user_info->adm_cid)
                        ->where('ware_superior_shop_id', $shop_id)
                        ->where('ware_leader_id', $user_info->adm_id)
                        ->where('ware_type', 2)
                        ->value('ware_id');
                    $goo_all_price = 0;
                    $goo_all_quantity = 0;
                    // 生成退换回收单，退换回收商品表添加数据
                    $num = 0;
                    foreach ($work_good as $key => $value) {
                        if ($value->wogo_state == 4 || $value->wogo_state == 3) {
                            continue;
                        }
                        $goo_all_price += $value->wogo_goo_amount * $value->wogo_goo_price;
                        $goo_all_quantity += $value->wogo_goo_amount;

                        if ($value->wogo_goo_inventory == 1) {
                            $rego_data[$num]['rego_fine_quantity'] = $value->wogo_goo_amount;
                        } else {
                            $rego_data[$num]['rego_priority_quantity'] = $value->wogo_goo_amount;
                        }
                        $rego_data[$num]['rego_ware_id'] = $value->wogo_ware_id;
                        $rego_data[$num]['rego_waon_class'] = $value->wogo_waon_class;
                        $rego_data[$num]['rego_wago_id'] = $value->wogo_wago_id;
                        $rego_data[$num]['rego_goo_id'] = $value->wogo_goo_id;
                        $rego_data[$num]['rego_goo_price'] = $value->wogo_goo_price;
                        $rego_data[$num]['rego_sell_number'] =  $value->wogo_goo_amount;
                        $rego_data[$num]['rego_recycle_number'] =  $value->wogo_goo_amount;
                        $rego_data[$num]['rego_goo_inventory'] =  $value->wogo_goo_inventory;
                        $rego_data[$num]['rego_goo_name'] = $value->wogo_goo_name;
                        $rego_data[$num]['rego_goo_goods_encode'] = $value->wogo_goo_goods_encode;
                        $num++;
                    }

                    // 生成退换回收单，退换回收单表添加数据
                    $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_number; //新的工单号
                    $add_recycle['rec_source_type'] = 7; //类型：6技师拒单 7技师终止
                    $add_recycle['rec_price'] = $goo_all_price; //回收总金额（单位：分）
                    $add_recycle['rec_amount'] = $goo_all_quantity; //回收总数量
                    $add_recycle['rec_state'] = 1; //回收状态 1.未回收 2.已回收
                    $add_recycle['rec_type'] = $work_data->wor_type; //买家类型 1.门店零售 2.来往单位
                    $add_recycle['rec_ware_id'] =  $work_data->wor_ware_id; //仓库id
                    $add_recycle['rec_create_adm_id'] = $user_info->adm_id; //创建人id
                    // $add_recycle['rec_remark'] = $request['cause'] ? $request['cause'] : ''; //备注
                    $add_recycle['rec_mobile_ware_id'] = $ware_id; //移动仓库id
                    $recycle_id = DB::table('recede_recycle')->insertGetId($add_recycle);

                    // 2退换回收商品表添加数据
                    $num = 0;
                    foreach ($work_good as $key => $value) {
                        if ($value->wogo_state == 4 || $value->wogo_state == 3) {
                            continue;
                        }
                        $rego_data[$num]['rego_rec_id'] = $recycle_id;
                        $num++;
                    }
                    $add_goods =  DB::table('recede_goods')->insert($rego_data);

                    $find_wocl_data = DB::table('work_client')
                        ->where('wocl_wor_id', $request['wor_id'])
                        ->select('wocl_client_id', 'wocl_channel_unit', 'wocl_name', 'wocl_phone')
                        ->first();
                    // 10.3 退换回收客户表添加数据
                    $jucl_data['recl_rec_id'] = $recycle_id; //回收单id
                    $jucl_data['recl_client_id'] = $find_wocl_data->wocl_client_id; //来往单位id/客户id
                    $jucl_data['recl_name'] = $find_wocl_data->wocl_name; //客户姓名
                    $jucl_data['recl_phone'] = $find_wocl_data->wocl_phone; //联系电话
                    $jucl_data['recl_channel_unit'] = $find_wocl_data->wocl_channel_unit; //渠道单位
                    $add_client =  DB::table('recede_client')->insert($jucl_data);
                    if ($add_client && $add_goods && $recycle_id) {
                    } else {
                        DB::rollBack();
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'终止失败']);
                    }
                }
            }
        }

        // 8. 添加操作记录
        $order_record = orderLog($user_info, 0, $request['wor_id'], '强行终止');

        // 添加新增订单信息的提示
        $inhi_data['inhi_original_adm_id'] = $work_data->wor_create_id; //原始单号创建人
        $inhi_data['inhi_original_id'] = $request['wor_id']; //原始单id
        $inhi_data['inhi_original_number'] = $work_data->wor_number; //原始单号
        $inhi_data['inhi_original_state'] = $wor_update_data['wor_state']; //原始单状态
        $inhi_data['inhi_original_operation'] = '终止'; //操作
        $inhi_data['inhi_operation_state'] = 4; //操作状态：4终止
        addInformationHint($user_info, $inhi_data, 2);

        if ($wor_update_res && $loc_update_res && $dego_update_res && $lock_turn_normal && $wor_id && $wogo_res && $wocl_res && $order_record && $join_wor_res && $order_record_res) {
            // 将暂停之前获取的数据改为暂停状态
            $get_tablename = $this->GetTableName('5000' . $user_info->adm_cid);
            if ($get_tablename['code'] == 200) {
                $tablename = $get_tablename['data'];
                $loc_data['loc_type'] = 3;
                $loc_res =  DB::table($tablename . '_location')
                    ->where('loc_ord_id', $request['wor_id'])
                    ->where('loc_type', 1)
                    ->update($loc_data);
            }

            Common::addLog($user_info, getRealIp($request), '工单列表', '强制终止', '工单：' . $work_data->wor_number . ' 技师：' . $user_info->adm_name . ' 终止');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'终止成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'终止失败']);
        }
    }

    // 精确打卡开关
    public function preciseLock(Request $request)
    {
        // 使用验证器 验证数据
        $verify_data = new VerifyWorkOrderController;
        $error_message = $verify_data->preciseLockValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>$error_message, 'data'=>'{}']);
        }

        //获取用户信息
        $user_info = Common::getUserInfo($request['api_token']);

        DB::beginTransaction();

        $wor_data = DB::table('work_order')
            ->where('wor_id', $request['wor_id'])
            ->first(['wor_order_id', 'wor_number']);

        $wor_res = DB::table('work_client')
            ->where('wocl_wor_id', $request['wor_id'])
            ->update(['wocl_update_time' => date('Y-m-d H:i:s'), 'wocl_precise_lock' => $request['precise_lock']]);

        $order_res = DB::table('order_client')
            ->where('orcl_ord_id', $wor_data->wor_order_id)
            ->update(['orcl_update_time' => date('Y-m-d H:i:s'), 'orcl_precise_lock' => $request['precise_lock']]);
        if ($request['precise_lock'] == 1) {
            $precise_lock = '精确打卡-开启';
        } else {
            $precise_lock = '精确打卡-关闭';
        }

        // 添加操作记录
        $order_record = orderLog($user_info, $wor_data->wor_order_id, 0, $precise_lock);
        $work_record = orderLog($user_info, 0, $request['wor_id'], $precise_lock);

        if ($order_record && $work_record && $order_res && $wor_res) {
            Common::addLog($user_info, getRealIp($request), '工单列表', '精确打卡', '工单：' . $wor_data->wor_number . ' ' . $precise_lock);
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$precise_lock]);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$precise_lock]);
        }
    }

    // 建码选择表
    private function GetTableName($codeid)
    {
        $tab_yemo = date("ym");
        // 查找码表是否存在
        $result = DB::table('table_link')->where('tab_codeid', $codeid)
            ->where('tab_yemo', $tab_yemo)
            ->select('id', 'tab_nums', 'tab_table_name')
            ->first();
        if ($result) {
            DB::table('table_link')->where('id', $result->id)->increment('tab_nums');
            return ['code'=>200, 'msg'=>'success', 'data'=>$result->tab_table_name];
        } else {
            // 查询当前二维码标识下是否建数据表
            $tab_table_name = DB::table('table_link')
                ->where('tab_codeid', $codeid)
                ->orderBy('id', 'desc')
                ->select('tab_table_name')
                ->first();
            if ($tab_table_name) {
                $result = DB::table('table_link')
                    ->where('tab_codeid', $codeid)
                    ->where('tab_table_name', $tab_table_name->tab_table_name)
                    ->get(['tab_nums'])->toArray();
                if ($result) {
                    $nums = 0;
                    foreach ($result as $k => $v) {
                        $nums = $nums + $v->tab_nums;
                    }
                    if ($nums < $this->max_location_table) {
                        $tab_data = [
                            'tab_codeid' => $codeid,
                            'tab_yemo' => $tab_yemo,
                            'tab_table_name' => $tab_table_name->tab_table_name,
                            'tab_nums' => 1,
                        ];
                        $tab_res =  DB::table('table_link')->insert($tab_data);
                        return ['code' => 200, 'msg' => 'success', 'data' => $tab_table_name->tab_table_name];
                    } else {
                        return $this->createTable($codeid, $tab_yemo);
                    }
                } else {
                    return $this->createTable($codeid, $tab_yemo);
                }
            } else {
                return $this->createTable($codeid, $tab_yemo);
            }
        }
    }

    // 改派技师
    public function updateTechnician(Request $request)
    {
        // 使用验证器 验证数据
        $verify_data = new VerifyWorkOrderController;
        $error_message = $verify_data->updateTechnicianValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>$error_message, 'data'=>'{}']);
        }

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

        $find_wor = DB::table('work_order as wor')
            ->leftJoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wor.wor_id')
            ->where('wor_id', $request['wor_id'])
            ->where('wor_shop_id', $user_info->adm_shop_id)
            ->select('wor_number', 'wor_service_adm_id', 'wor_service_type', 'wor_ware_id', 'wor_goo_amount', 'wor_remark', 'wor_service_shop_id', 'wor_pass', 'wor_order_id', 'wor_create_id', 'wor_type', 'wocl_client_id', 'wocl_wor_type', 'wor_delete', 'wor_state', 'wor_order_number', 'wocl_name', 'wocl_phone', 'wocl_province', 'wocl_city', 'wocl_address', 'wocl_county', 'wocl_whether_app')
            ->first();
        if (empty($find_wor)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单不存在，无法派单！']);
        }
        if ($find_wor->wor_pass == 4) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单已经锁定，无法派单！']);
        }
        if ($find_wor->wor_delete == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单已经取消，无法派单！']);
        }
        if (!in_array($find_wor->wor_state, [2, 3])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'该状态不是待接单或者未派单状态, 不能改派技师']);
        }

        DB::beginTransaction();

        $work_order = new WorkOrders();
        $return_data = $work_order->sendAssing($user_info, $request->all(), 2, $find_wor);
        if ($return_data['code'] == 200) {
            $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), '工单列表', '改派技师', $find_wor->wor_number . ' 派单成功');

            $find_order = DB::table('order')
                ->where('ord_id', $find_wor->wor_order_id)
                ->first(['ord_other_system_number', 'ord_type', 'ord_service_type']);

            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'=>'失败']);
                }
            }
            $result_push = pushMessage($push_name, '您有新的工单：' . $find_wor->wor_number . ' 请注意查收');

            if (!empty($request['wor_service_adm_id']) && $find_wor->wocl_whether_app == 1) {
                $wechat_msg['pushtype'] = 1; //工单推送
                $wechat_msg['adm_id'] = $request['wor_service_adm_id']; //推送人
                $wechat_msg['wor_number'] = $find_wor->wor_number; //工单号
                $wechat_msg['ord_number'] = $find_wor->wor_order_number; //订单号
                $wechat_msg['order_type'] = ordType($find_order->ord_service_type); //订单类型
                $wechat_msg['user_name'] = $find_wor->wocl_name; //姓名
                $wechat_msg['user_phone'] = $find_wor->wocl_phone; //手机号
                $wechat_msg['user_dress'] = $find_wor->wocl_province . $find_wor->wocl_city . $find_wor->wocl_county . $find_wor->wocl_address; //手机号
                $wechat_msg['tittle'] = '您有新工单请及时处理'; //手机
                $wechat_msg['remark'] = $find_wor->wor_remark; //备注
                $CashierDesk = new CashierDesk;
                $CashierDesk->inforPush($wechat_msg);
            }
            DB::commit();
            return response()->json($return_data);
        } else {
            DB::rollBack();
            return response()->json($return_data);
        }
    }

    // // 发送短信
    // public function sendMessage(Request $request)
    // {
    //     // 验证数据
    //     $verify_data = new VerifyWorkOrderController;
    //     $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']);

    //     // 根据工单id,查询单号
    //     $find_data = DB::table('work_order')
    //         ->where('wor_id', $request['wor_id'])
    //         ->select('wor_id', 'wor_number', 'wor_service_state', 'wor_state', 'wor_service_type', 'wor_pass', 'wor_order_id', 'wor_create_id')
    //         ->first();
    //     if ($find_data->wor_service_state != 3 || $find_data->wor_state != 5) {
    //         return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'预约状态,才可以点击出发']);
    //     }
    //     if (in_array($find_data->wor_pass, [4, 5, 6])) {
    //         return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单已锁定，无法操作！']);
    //     }
    //     if ($find_data->wor_service_state == 10) {
    //         return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单已锁定，无法操作！']);
    //     }
    //     if ($find_data->wor_service_state == 11) {
    //         return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单已撤销回收，无法操作！']);
    //     }

    //     // 1.判断该技师是否出发过 且 是暂停的工单
    //     $is_loc_id = DB::table('location_link')
    //         ->where('loc_wor_id', $request['wor_id'])
    //         ->where('loc_service_adm_id', $user_info->adm_id)
    //         ->where('loc_state', 1)
    //         ->value('loc_id');
    //     DB::beginTransaction();
    //     if ($is_loc_id) {
    //         // 2.出发过不发送短信
    //         $send_res = 1;

    //         // 3.只修改位置链接表中的状态
    //         $save_loc_state['loc_update_time'] = date('Y-m-d H:i:s');
    //         $save_loc_state['loc_state'] = 1; //状态1.正常 2.终止
    //         $location_link = DB::table('location_link')
    //             ->where('loc_id', $is_loc_id)
    //             ->update($save_loc_state);
    //         if ($location_link) {
    //             DB::commit();
    //             return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'当前技师已发送短信']);
    //         } else {
    //             DB::rollBack();
    //             return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'短信发送失败']);
    //         }
    //     } else {
    //         // 2.给相应的客户发送短信
    //         $phone = DB::table('work_client')
    //             ->where('wocl_wor_id', $request['wor_id'])
    //             ->value('wocl_phone');

    //         // dechex():把十进制转换为十六进制,strtoupper:把字符串转换为大写。
    //         $code = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    //         $sole = $code[rand(0, 61)] . strtoupper(dechex(date('m'))) . date('d') . time() . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
    //         $sole_char = $this->get62($sole); //得到8位唯一字符串

    //         // $key = '7cha.co?'.$sole_char;//域名+8位唯一字符串
    //         // $link = "http://".$key;// 生成链接
    //         $key = config('apimesssage.SHORT_DOMAINS') . '/' . $sole_char; //域名+8位唯一字符串
    //         $link = config('apimesssage.NETWORK_PROTOCOL') . $key; // 生成链接
    //         $message = "您的服务技师已出发，详情请查看：{$link}"; //短信信息

    //         // 3.将该条链接存储到表里
    //         $add_link['loc_cid'] = $user_info->adm_cid; //公司id
    //         $add_link['loc_wor_id'] = $request['wor_id']; //工单id
    //         $add_link['loc_key'] = $key; //key值
    //         $add_link['loc_link'] = config('apimesssage.REDIRECT_URL') . '?uniqueid=' . md5(time() . rand(10000, 99999) . $request['wor_id']); //链接
    //         $add_link['loc_service_adm_id'] = $user_info->adm_id; //服务技师id
    //         $add_link['loc_state'] = 1; //状态1.正常 2.终止
    //         $add_link['loc_evaluate_state'] = 1; //是否评价1.未评价 2.已评价
    //         $location_link = DB::table('location_link')->insert($add_link);
    //         if (!$is_loc_id) {
    //             // $phone = '17601083915';
    //             $send_res = sendSmsCode($phone, $message);
    //             // $send_res = 1;
    //         }
    //         if ($send_res != -5) {
    //             Common::addLog($user_info, getRealIp($request), '工单列表', '发送短信', '工单：' . $find_data->wor_number . ' 发送成功');
    //             DB::commit();
    //             return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'短信发送成功']);
    //         } else {
    //             DB::rollBack();
    //             return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'短信发送失败']);
    //         }
    //     }
    // }

    // 获取8位唯一字符串
    private function get62($src, $length = 8)
    {
        $md5 = md5($src, true); //转换为原始 16 字符二进制格式
        $pos = 0;
        $res = "";
        while (strlen($res) < $length && ($bin = substr($md5, $pos, 4)) != "") {
            // unpack() 函数从二进制字符串对数据进行解包
            // 第一个参数：解包数据时所使用的格式
            // 第二个参数：规定被解包的二进制数据
            // sprintf() %u - 不包含正负号的十进制数
            $uint =  sprintf("%u", unpack("Nint", $bin)['int']);
            $res .= $this->decto62($uint);
            $pos += 4;
        }
        return substr($res, 0, $length);
    }

    private function decto62($src)
    {
        static $table = [];
        $table = array_merge(range(0, 9), range('A', "Z"), range('a', "z"));

        $arr62 = [];
        $div = $src;
        do {
            $mod = $div % 62;
            array_unshift($arr62, $table[$mod]);
            $div = intval($div / 62);
        } while ($div != 0);

        return implode("", $arr62);
    }
}
