<?php

namespace App\Http\Controllers\Mounting\Business;

use App\Http\Controllers\Api\Verify\MemberManage\VerifyMemberListController;
use App\Http\Controllers\Api\Verify\OrderManage\VerifyOrderController;
use App\Http\Controllers\Common\CommonController;
use App\Http\Models\Api\Export;
use App\Http\Models\Api\ReceivablePay;
use App\Models\Business\WashOrder;
use App\Services\ReceivablePay\ReceivablePayService;
use Illuminate\Http\Request;
use BlueCity\Core\Controllers\MountingCoreController as Controller;
use BlueCity\Core\Traits\ResourceControllerMethod;
use App\Services\Business\WashOrderService;
use App\Services\Business\WashOrderBasicService;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\LoginUserService;
use App\Models\OperationLog;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Validators\Business\WashOrderBasicValidator;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Session;
use App\Http\Models\Api\Common;
use App\Services\CommonService;

class WashOrderController extends Controller
{
    public $dataService = null;

    public function __construct()
    {
        $this->dataService = $service = new WashOrderService();
        $this->bootWithService($service);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->indexValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }

        $user_info = LoginUserService::getUser();
        if (empty($request['ord_service_type'])) {
            $request['ord_service_type'] = [1,2,3,4,5,6,7];
        }
        $request['show_count'] = isset($request['show_count']) ?$request['show_count']:10;
        $search_data = $this->dataService->searchPage($user_info, $request->all(), $request['show_count']);
        $find_title = DB::table('custom_header')
            ->where('ch_shop_id', $user_info->adm_shop_id)
            ->where('ch_adm_id', $user_info->adm_id)
            ->where('ch_type', 1)
            ->first();
        if ($find_title) {
            $ch_data = json_decode($find_title->ch_data, true);
            $new_data = [];
            foreach ($ch_data as $key => $value) {
                if ($value['is_selected'] == 1) {
                    $new_data[] = $value;
                }
            }
            $ch_data = $new_data;
        } else {
            $ch_data = DB::table('title')
                ->where('type', 1)
                ->select('title', 'field')
                ->get()->toArray();
        }
        
        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        //获取top按钮
        $sea_button_data = 'createBill,export,orderType,basicSet';
        $top_button = CommonService::getTopButton('',$sea_button_data,$list_button);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$search_data, 'list_button'=>$list_button, 'top_button'=>$top_button, 'ch_data'=>$ch_data]);
    }

    // 新增
    public function add(Request $request)
    {
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        // 判断门店版本
        if ($user_info->shop_versions == 1) {
            // 基础版验证
            $error_message = (new WashOrderBasicValidator())->addValidator($request->all());
        } else {
            $error_message = (new WashOrderBasicValidator())->addValidator($request->all());
            // $error_message = $this->dataService->mainValidator->addValidator($request->all());
        }
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }


        // 记录日志
        $log_record['request'] = $request->all();
        $log_record['time'] = date('Y-m-d H:i:s');
        $log_record['function'] = 'add';
        logFileRecord($log_record, 'pc/Business/WashOrder', 2);
        if (!isset($request['ware_id'])) {
            request()->offsetSet('ware_id', 1);
        }
        request()->offsetSet('ord_service_type', 1);//贴膜订单
        request()->offsetSet('orcl_shipment_party', 1);
        request()->offsetSet('ip', getRealIp($request));

        DB::beginTransaction();
        $request['client_ip'] = getRealIp($request);
        // 判断门店版本
        $order_data = WashOrderBasicService::add($user_info, $request->all());
        if ($order_data['code'] != 200) {
            DB::rollBack();
            return response()->json($order_data);
        }
        // 订单历史记录
        $data['wohi_primary_id'] = $order_data['data']['ord_id'];
        $data['wohi_state_name'] = '已创建';
        $data['wohi_state'] = 1;
        $data['wohi_type'] = 1;
        addHistory($data);
        unset($data);
        // 生成操作记录
        $orlo_res = orderLog($user_info, $order_data['data']['ord_id'], 0, '生成订单');
        OperationLog::addLog($user_info, $request['client_ip'], '订单列表', '生成订单', '生成订单' . $order_data['data']['ord_order_number'] . '成功');
        if ($order_data['code'] == 200) {
            DB::commit();
            return $this->success('生成订单成功');
        } else {
            DB::rollBack();
            return $this->error('生成订单失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 编辑
    public function edit(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->editShowValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        // 订单信息
        $order_data = DB::table('order as o')
            ->leftjoin('order_client as oc', 'oc.orcl_ord_id', '=', 'o.ord_id')
            ->where('ord_id', $request['ord_id'])
            ->select('ord_id', 'ord_orcl_id', 'ord_service_type', 'ord_state', 'ord_wor_quantity', 'ord_payment_way', 'ord_actual_price', 'ord_type', 'ord_remark', 'ord_ware_id', 'ord_client_id', 'ord_service_sepr_id', 'ord_service_adm_id', 'ord_collection_price', 'ord_service_shop_id', 'ord_order_number', 'ord_plus_minus', 'ord_order_plus_minus', 'orcl_shipment_party', 'orcl_rescue_assign_price', 'orcl_junk_type', 'orcl_whether_app', 'orcl_precise_lock', 'orcl_appoint_time', 'ord_delete', 'ord_wor_state', 'ord_create_time', 'ord_superior_shop_id as shop_id', 'ord_add_work_state', 'ord_other_payway', 'ord_new_type')
            ->first();
        // 判断发货单是否发货，已发货的不允许编辑
        $dego_type = DB::table('dispatch_bill')
            ->where('dego_order_type', 1)
            ->where('dego_wor_id', $request['ord_id'])
            ->where('dego_original_number', $order_data->ord_order_number)
            ->value('dego_type');
        if ($dego_type == 2) {
            return response()->json(['code'=>500, 'msg'=>'当前订单的发货单已发货不允许编辑', 'data'=>'当前订单的发货单已发货不允许编辑']);
        }
        if ($order_data->ord_delete == 2) {
            return ['code'=>500, 'msg'=>'当前订单已取消，无法编辑', 'data'=>'当前订单已取消，无法编辑'];
        }
        if ($order_data->ord_wor_quantity > 0) {
            // 工单数量大于0，已经派工单
            return ['code'=>500, 'msg'=>'当前订单已经派工单，无法编辑', 'data'=>'当前订单已经派工单，无法编辑'];
        }
        if ($order_data->ord_wor_state == 4) {
            // 发货单发货之后，退货单退货入库之后订单就是完成状态
            return ['code'=>500, 'msg'=>'当前订单已经完成，无法编辑', 'data'=>'当前订单已经完成，无法编辑'];
        }
        // $create_year_month = substr($order_data->ord_create_time, 0, 7); //创建时间年月
        // $now_year_month = date('Y-m'); //当前年月
        // if ($now_year_month != $create_year_month) {
        //     return ['code'=>500, 'msg'=>'不是本月订单，无法编辑！', 'data'=>'不是本月订单，无法编辑！'];
        // }

        // 获取用户信息
        $user_info = LoginUserService::getUser();
        // 获取订单编辑数据
        if ($request['type'] == 1) {
            $return_data = WashOrderService::editShow($user_info, $request->all());
            return response()->json($return_data);
        }

        // 验证参数
        $error_message = $this->dataService->mainValidator->editValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }

        DB::beginTransaction();
        if (!isset($request['ware_id'])) {
            request()->offsetSet('ware_id', 1);
        }
        request()->offsetSet('ord_service_type', 1);
        request()->offsetSet('orcl_shipment_party', 1);
        // 提交订单编辑数据
        $order_data = WashOrderService::edit($user_info, $request->all(), $order_data);
        if ($order_data['code'] != 200) {
            DB::rollBack();
            return response()->json($order_data);
        }
        // 生成操作记录
        $orlo_res = orderLog($user_info, $request['ord_id'], 0, '编辑订单');
        if ($orlo_res) {
            DB::commit();
            OperationLog::addLog($user_info, getRealIp($request), '订单列表', '编辑订单', '编辑订单' . $request['ord_order_number'] . '成功');
            return $this->success('编辑订单成功001');
        } else {
            DB::rollBack();
            return $this->error('编辑订单失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 生成工单
    public function createWork(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->editShowValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        // 获取生成订单数据
        if ($request['type'] == 1) {
            $return_data = WashOrderService::editShow($user_info, $request->all());
            return response()->json($return_data);
        }

        DB::beginTransaction();
        request()->offsetSet('ord_service_type', 1);
        // 判断门店版本
        // if ($user_info->shop_versions == 1) {
        //     // 基础版流程
        //     $order_data = WashOrderBasicService::createWork($user_info, $request->all());
        // } else {
        //     // 其他版本流程
        //     // 生成工单
        // }
        $order_data = WashOrderService::createWork($user_info, $request->all());
        if ($order_data['code'] != 200) {
            DB::rollBack();
            return response()->json($order_data);
        }
        $find_wor_data = DB::table('work_order')
            ->where('wor_id', $order_data['data']['wor_id'])
            ->select('wor_service_adm_id')
            ->first();
        // 添加技师消息
        $add_data['adm_id'] = $find_wor_data->wor_service_adm_id;
        $add_data['shop_id'] = $user_info->adm_shop_id;
        $add_data['primary_id'] = $order_data['data']['wor_id']; //单据的主键id
        $add_data['primary_type'] = 2; //单据类型：1订单2工单3预约单4售后单
        $add_data['message_type'] = 1;
        $add_data['primary_wor_state'] = 3; //状态1订单待派单2工单待派单3待接单
        // $add_data['message_type'] = $data['message_type'];
        $add_data['title'] = '派单通知'; //
        $add_data['content'] = '您有新的工单，请及时处理'; //操作内容
        $add_data['read_state'] = 1; //阅读状态：1未读2已读
        $add_data['create_adm_name'] = $user_info->adm_name; //操作人姓名
        $add_data['create_adm_id'] = $user_info->adm_id; //操作人id
        $addAdminMessage_res = addAdminMessage($add_data);
        // 订单历史记录
        $data['wohi_primary_id'] = $request['ord_id'];
        $data['wohi_state_name'] = '待施工';
        $data['wohi_state'] = 2;
        $data['wohi_type'] = 1;//1订单2工单
        addHistory($data);
        unset($data);
        // 工单的历史记录
        $data['wohi_primary_id'] = $order_data['data']['wor_id'];
        $data['wohi_state_name'] = '已创建';
        $data['wohi_state'] = 1;//服务状态：1已创建
        $data['wohi_type'] = 2;//1订单2工单
        addHistory($data);
        unset($data);
        // 工单的历史记录
        $data['wohi_primary_id'] = $order_data['data']['wor_id'];
        $data['wohi_state_name'] = '待接单';
        $data['wohi_state'] = 2;//服务状态：2待接单
        $data['wohi_type'] = 2;//1订单2工单
        addHistory($data);
        unset($data);
        if ($addAdminMessage_res['code'] != 200) {
            DB::rollBack();
            return response()->json($addAdminMessage_res);
        }
        // 生成操作记录
        $orlo_res = orderLog($user_info, $request['ord_id'], $order_data['data']['wor_id'], '生成工单');
        if ($orlo_res) {
            DB::commit();
            OperationLog::addLog($user_info, getRealIp($request), '订单列表', '生成工单', '生成工单' . $order_data['data']['wor_order_number'] . '成功');
            return $this->success('生成工单成功');
        } else {
            DB::rollBack();
            return $this->error('生成工单失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 验车
    public function validateCar(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->validateCarShowValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }

        // 获取用户信息
        $user_info = LoginUserService::getUser();
        if ($request['type'] == 1) {
            $find_wash_order_validate_car = DB::table('wash_order_validate_car as ovc')
                ->leftJoin('order_client as oc', 'ovc.orvc_ord_id', '=', 'oc.orcl_ord_id')
                ->leftJoin('admin as a', 'ovc.orvc_adm_id', '=', 'a.adm_id')
                ->where('orvc_shop_id', $user_info->adm_shop_id)
                ->where('orvc_ord_id', $request['ord_id'])
                ->select('orvc_car_interior', 'orvc_mileage', 'orvc_film_roll_number', 'orvc_car_exterior', 'orcl_check_car_state', 'orcl_signature_img', 'orvc_adm_id', 'adm_name')
                ->first();
            if (empty($find_wash_order_validate_car)) {
                $find_wash_order_validate_car['orvc_car_interior'] = '';
                $find_wash_order_validate_car['orvc_car_exterior'] = '';
                $find_wash_order_validate_car['orvc_mileage'] = '';
                $find_wash_order_validate_car['orvc_film_roll_number'] = '';
                $find_wash_order_validate_car['orcl_check_car_state'] = 2;
                $find_wash_order_validate_car['orcl_signature_img'] = '';
                $find_wash_order_validate_car['orvc_adm_id'] = '';
                $find_wash_order_validate_car['adm_name'] = '';
            }
            return ['code'=>200, 'msg'=>'success', 'data'=>$find_wash_order_validate_car];
        }

        // 验证参数
        $error_message = $this->dataService->mainValidator->validateCarValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }

        DB::beginTransaction();
        // 提交订单验车数据
        $order_data = WashOrderService::validateCar($user_info, $request->all());
        if ($order_data['code'] != 200) {
            DB::rollBack();
            return response()->json($order_data);
        }
        // 生成操作记录
        $orlo_res = orderLog($user_info, $request['ord_id'], 0, '验车');
        // 订单信息
        $find_ord_data = DB::table('order as o')
            ->leftJoin('order_client as oc', 'o.ord_id', '=', 'oc.orcl_ord_id')
            ->where('ord_id', $request['ord_id'])
            ->select('orcl_client_id', 'ord_shop_id', 'ord_id', 'ord_order_number', 'orcl_car_num')
            ->first();
        // 客户小程序-微信用户id
        $weus_id = DB::table('user_shop')
            ->where('ussh_shop_id', $find_ord_data->ord_shop_id)
            ->where('ussh_user_id', $find_ord_data->orcl_client_id)
            ->value('ussh_weus_id');
        if ($weus_id) {
            // 添加客户消息
            $add_data['weus_id'] = $weus_id;
            $add_data['shop_id'] = $find_ord_data->ord_shop_id;
            $add_data['primary_id'] = $find_ord_data->ord_id; //单据的主键id
            $add_data['primary_type'] = 1; //单据类型：1订单2工单3预约单4售后单
            $add_data['read_state'] = 1; //阅读状态：1未读2已读
            // 您的爱车（津HYC666）已完成验车，请您签字确认
            $add_data['title'] = '验车确认通知'; //操作内容
            $add_data['content'] = '您的爱车（'.$find_ord_data->orcl_car_num.'）已完成验车，请您签字确认'; //操作内容
            // $add_data['content'] = '您的订单：' . $find_ord_data->ord_order_number . '验车成功,验车人：' . $user_info->adm_name; //操作内容
            $add_data['create_adm_name'] = $user_info->adm_name; //操作人姓名
            $add_data['create_adm_id'] = $user_info->adm_id; //操作人id
            $addUserMessage_res = addUserMessage($add_data);
            unset($add_data);
        } else {
            $addUserMessage_res['code'] = 200;
        }

        if ($orlo_res && $addUserMessage_res['code'] == 200) {
            DB::commit();
            OperationLog::addLog($user_info, getRealIp($request), '订单列表', '验车', '验车' . '成功');
            return $this->success('验车成功');
        } else {
            DB::rollBack();
            return $this->error('验车失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 签字
    public function signatureSubmit(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->pcsignatureSubmitValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }

        $user_info = LoginUserService::getUser();
        DB::beginTransaction();
        // 提交订单签字数据
        $signatureSubmit = WashOrderService::signatureSubmit($user_info, $request->all());
        if ($signatureSubmit['code'] != 200) {
            DB::rollBack();
            return response()->json($signatureSubmit);
        }
        // 生成操作记录
        $orlo_res = orderLog($user_info, $request['ord_id'], 0, '订单签字');

        if ($orlo_res && $signatureSubmit['code'] == 200) {
            DB::commit();
            OperationLog::addLog($user_info, getRealIp($request), '订单列表', '订单签字', '订单签字' . '成功');
            return $this->success('签字成功');
        } else {
            DB::rollBack();
            return $this->error('签字失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 详情
    public function info(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->infoValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }

        // 获取用户信息
        $user_info = LoginUserService::getUser();
        $return_data = WashOrderService::info($user_info, $request->all());
        return response()->json($return_data);
    }

    // 取消订单
    public function cancel(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->remarkValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }

        // 获取用户信息
        $user_info = LoginUserService::getUser();

        DB::beginTransaction();
        // 取消订单
        $return_data = WashOrderService::cancel($user_info, $request->all());
        if ($return_data['code'] != 200) {
            DB::rollBack();
            return response()->json($return_data);
        }
        //取消应收应付
        $requests = $request->all();
        $find_rece = DB::table('receivable_pay')
            ->where('recpay_original_id', $requests['ord_id'])
            ->first();
        if($find_rece){
            $update_qrres = DB::table('receivable_pay')
                ->where('recpay_original_id', $requests['ord_id'])
                ->update(['recpay_order_state'=>3]);
        }

        // 生成操作记录
        $orlo_res = orderLog($user_info, $request['ord_id'], 0, '取消订单');
        if ($request['remark']) {
            // 添加备注
            $orre_res = orderRemark($user_info, $request['ord_id'], '', $request['remark'], '订单列表');
        } else {
            $orre_res = true;
        }
        if ($orlo_res && $orre_res) {
            DB::commit();
            OperationLog::addLog($user_info, getRealIp($request), '订单列表', '取消订单', '取消订单' . $return_data['data']['ord_order_number'] . '成功');
            return $this->success('取消订单成功');
        } else {
            DB::rollBack();
            return $this->error('取消订单失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 备注
    public function remark(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->remarkValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }

        // 获取用户信息
        $user_info = LoginUserService::getUser();
        $return_data = WashOrderService::remarkSearch($user_info, $request->all());
        $orre_res = orderRemark($user_info, $request['ord_id'], $return_data['wor_id'], $request['remark'], '订单列表');
        if ($orre_res) {
            OperationLog::addLog($user_info, getRealIp($request), '订单列表', '备注', '订单 ' . $return_data['ord_order_number'] . ' 添加备注 :' . $request['remark']);
            return $this->success('备注成功');
        } else {
            return $this->error('备注失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 预约设置
    public function appointmentSet(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->appointmentSetValidator($request->all());
        if (!empty($error_message)) {
            // return ['code'=>ErrorInc::INVALID_PARAM, 'msg'=>'请求参数错误！222', 'data'=>$error_message];
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();

        DB::beginTransaction();
        $return_data = $this->dataService->appointmentSet($user_info, $request->all());
        // // 订单信息
        // $find_ord_data = DB::table('order as o')
        //     ->leftJoin('order_client as oc', 'o.ord_id', '=', 'oc.orcl_ord_id')
        //     ->where('ord_id', $request['ord_id'])
        //     ->select('orcl_client_id', 'ord_shop_id', 'ord_id', 'ord_order_number')
        //     ->first();
        // // 客户小程序-微信用户id
        // $weus_id = DB::table('user_shop')
        //     ->where('ussh_shop_id', $find_ord_data->ord_shop_id)
        //     ->where('ussh_user_id', $find_ord_data->orcl_client_id)
        //     ->value('ussh_weus_id');

        // if ($weus_id) {
        //     // 添加客户消息
        //     $add_data['weus_id'] = $weus_id;
        //     $add_data['shop_id'] = $find_ord_data->ord_shop_id;
        //     $add_data['primary_id'] = $find_ord_data->ord_id; //单据的主键id
        //     $add_data['primary_type'] = 1; //单据类型：1订单2工单3预约单4售后单
        //     $add_data['read_state'] = 1; //阅读状态：1未读2已读
        //     $add_data['content'] = '您的订单：' . $find_ord_data->ord_order_number . '预约设置成功,操作人：' . $user_info->adm_name; //操作内容
        //     $add_data['create_adm_name'] = $user_info->adm_name; //操作人姓名
        //     $add_data['create_adm_id'] = $user_info->adm_id; //操作人id
        //     $addUserMessage_res = addUserMessage($add_data);
        //     unset($add_data);
        // } else {
        //     $addUserMessage_res['code'] = 200;
        // }
        // if ($addUserMessage_res['code'] != 200) {
        //     DB::rollBack();
        //     return response()->json($addUserMessage_res);
        // }
        if ($return_data['code'] != 200) {
            DB::rollBack();
            return response()->json($return_data);
        } else {
            DB::commit();
            OperationLog::addLog($user_info, getRealIp($request), '订单列表', '预约设置', '预约设置：' . $return_data['data']['ord_order_number'] . '成功');
            return $this->success('预约设置成功');
        }
    }

    // 转售后
    public function afterSale(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->infoValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();

        DB::beginTransaction();
        $return_data = $this->dataService->afterSale($user_info, $request->all());
        if ($return_data['code'] != 200) {
            DB::rollBack();
            return response()->json($return_data);
        } else {
            DB::commit();
            OperationLog::addLog($user_info, getRealIp($request), '订单列表', '申请售后', '申请售后：' . $return_data['data']['afsl_after_number'] . '成功');
            return $this->success('申请售后成功');
        }
    }

    // 订单作品-新增
    public function addOrderWorks(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->addOrderWorksValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();

        DB::beginTransaction();
        $return_data = $this->dataService->addOrderWorks($user_info, $request->all());
        if ($return_data['code'] != 200) {
            DB::rollBack();
            return response()->json($return_data);
        } else {
            DB::commit();
            OperationLog::addLog($user_info, getRealIp($request), '订单列表', '添加作品', '添加作品成功');
            return $this->success('添加作品成功');
        }
    }

    // 订单作品-列表
    public function OrderWorksindex(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->OrderWorksindexValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();

        $return_data = $this->dataService->OrderWorksindex($user_info, $request->all());
        if (empty($return_data)) {
            return $this->error('未找到数据', ErrorInc::DATA_EMPTY);
        } else {
            // 获取当前列表下的按钮
            $list_button = getListButton($request['api_token'], $request['pri_id']);
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$return_data, 'list_button'=>$list_button]);
        }
    }

    // 订单作品-详情
    public function OrderWorksinfo(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->OrderWorksinfoValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();

        $return_data = $this->dataService->OrderWorksinfo($user_info, $request->all());
        if (empty($return_data)) {
            return $this->error('未找到数据', ErrorInc::DATA_EMPTY);
        } else {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$return_data]);
        }
    }

    // 订单作品-编辑
    public function OrderWorksedit(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->OrderWorksinfoValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        if ($request['type'] == 1) {
            $return_data = $this->dataService->OrderWorksinfo($user_info, $request->all());
            if (empty($return_data)) {
                return $this->error('未找到数据', ErrorInc::DATA_EMPTY);
            } else {
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$return_data]);
            }
        }
        // 验证参数
        $error_message = $this->dataService->mainValidator->OrderWorkseditValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        $return_data = $this->dataService->OrderWorksedit($user_info, $request->all());
        if ($return_data['code'] != 200) {
            DB::rollBack();
            return response()->json($return_data);
        } else {
            DB::commit();
            OperationLog::addLog($user_info, getRealIp($request), '订单列表', '编辑作品', '编辑作品成功');
            return $this->success('编辑作品成功');
        }
    }

    // 订单作品-删除
    public function OrderWorksdel(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->OrderWorksdelValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();

        $return_data = $this->dataService->OrderWorksdel($user_info, $request->all());
        if ($return_data) {
            DB::rollBack();
            return response()->json($return_data);
        } else {
            DB::commit();
            OperationLog::addLog($user_info, getRealIp($request), '订单列表', '删除作品', '删除作品成功');
            return $this->success('删除作品成功');
        }
    }

    // 订单审核
    public function auditOrder(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->auditOrderValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        $return_data = $this->dataService->auditOrder($user_info, $request->all());
        if ($return_data['code'] == 500) {
            DB::rollBack();
            return response()->json($return_data);
        } else {
            DB::commit();
            OperationLog::addLog($user_info, getRealIp($request), '订单列表', '订单审核', '订单审核成功');
            return response()->json($return_data);
        }
    }

    // 订单结算
    public function settlement(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->settlementValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        request()->offsetSet('ip', getRealIp($request));
        $return_data = WashOrderService::settlement($user_info, $request->all());
        if ($return_data['code'] == 500) {
            DB::rollBack();
            return response()->json($return_data);
        } else {
            DB::commit();
            OperationLog::addLog($user_info, getRealIp($request), '订单列表', '订单结算', '订单结算成功');
            return response()->json($return_data);
        }
    }

    // 取消结算
    public function cancelSettlement(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->cancelSettlementValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }

        // 获取用户信息
        $user_info = LoginUserService::getUser();

        DB::beginTransaction();
        request()->offsetSet('ip', getRealIp($request));
        // 取消订单
        $return_data = WashOrderService::cancelSettlement($user_info, $request->all());
        if ($return_data['code'] != 200) {
            DB::rollBack();
            return response()->json($return_data);
        }

        // 生成操作记录
        $orlo_res = orderLog($user_info, $request['ord_id'], 0, '取消结算');
        if ($request['remark']) {
            // 添加备注
            $orre_res = orderRemark($user_info, $request['ord_id'], '', $request['remark'], '订单列表');
        } else {
            $orre_res = true;
        }
        if ($orlo_res && $orre_res) {
            DB::commit();
            OperationLog::addLog($user_info, getRealIp($request), '订单列表', '取消结算', '取消结算成功');
            return $this->success('取消结算成功');
        } else {
            DB::rollBack();
            return $this->error('取消结算失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 查询可用会员卡
    public function getmyVip(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->pcgetmyVipValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        $log_record['request'] = $request->all();
        $log_record['time'] = date('Y-m-d H:i:s');
        $log_record['function'] = 'pcgetmyVip';
        logFileRecord($log_record, 'wash/WashOrder', 2);
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        $res = WashOrderService::getmyVip($user_info, $request->all());
        if (empty($res)) {
            return $this->error('未找到数据', ErrorInc::DATA_EMPTY);
        } else {
            return response()->json($res);
        }
    }

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

        $search_data = $request->all();

        $orderby_type = 'desc'; //排序类型，默认倒序查询
        // 当查询待接单状态订单时，按正序查询
        if (!empty($request['ord_wor_state']) && $request['ord_wor_state'] == 7) {
            $orderby_type = 'asc'; //默认排序类型
        }
        if (!isset($search_data['ord_service_type'])) {
           $search_data['ord_service_type'] = [1,2];
        }
        //最多导出一个月时间的
        // 验证数据
        $verify_data = new VerifyOrderController;
        $error_message = $verify_data->exportValidator($request->all());
        if ($error_message) {
            //return response()->json(['code'=>500, 'msg'=>'请先选择订单创建的开始日期和结束日期再导出（最多可以导出90天）', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $days = floor((strtotime($request['create_time_end'])-strtotime($request['create_time_start']))/86400);
        //if($days > 90){return response()->json(['code'=>500, 'msg'=>'最多可以导出90天', 'data'=>'最多可以导出90天']);}


        $ord_id = [];
        // 查询小程序的待付款的订单
        // $ord_id = DB::table('order as ord')
        //     ->leftJoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
        //     ->where('ord_shop_id', $user_info->adm_shop_id)
        //     ->where('ord_collection_bill', 1) //是否代收账单：1正常订单2代收账单
        //     ->where('ord_classify', 2) //工单分类：1蓄电池2洗美店3易损件
        //     ->where('ord_is_split', '<>', 3) //订单是否拆分，1是2否
        //     ->where('ord_source', 2)
        //     ->where('ord_state', 1)
        //     ->where('ord_wor_state', '!=', 11)//取消订单
        //     ->select('ord_id')
        //     ->get()->toArray();
        $ord_id = array_column($ord_id, 'ord_id');

        DB::connection()->enableQueryLog();#开启执行日志

        $data = DB::table('order as ord')
            ->leftJoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
            ->rightJoin('order_goods as orgo', 'orgo.orgo_ord_id', '=', 'ord.ord_id')
            ->leftJoin('shop as shop', 'shop.shop_id', '=', 'ord.ord_shop_id')
            ->leftJoin('admin as admin', 'admin.adm_id', '=', 'ord.ord_create_id')
            ->where('ord_shop_id', $user_info->adm_shop_id)
            ->where('ord_collection_bill', 1) //是否代收账单：1正常订单2代收账单
            ->where('ord_classify', 2) //工单分类：1蓄电池2洗美店3易损件
            ->where('ord_is_split', '<>', 3) //订单是否拆分，1是2否
            ->whereNotIn('ord_id', $ord_id)
            ->where(function ($query) use ($search_data) { //订单类型搜索
                if (!empty($search_data['ord_service_type'])) {
                    $query->whereIn('ord_service_type', $search_data['ord_service_type']);
                }
            })
            ->where(function ($query) use ($search_data) { //关键字搜索
                if (!empty($search_data['keywords'])) {
                    $query->where('orcl_phone', 'like', '%' . $search_data['keywords'] . '%')
                        ->orwhere('orcl_name', 'like', '%' . $search_data['keywords'] . '%')
                        ->orwhere('ord_order_number', 'like', '%' . $search_data['keywords'] . '%')
                        ->orwhere('orcl_car_num', 'like', '%' . $search_data['keywords'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //销售人员搜索
                if (!empty($search_data['orcl_sales_adm_id'])) {
                    $query->where('orcl_sales_adm_id', $search_data['orcl_sales_adm_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //订单分类：1蓄电池2洗美店3易损件
                if (!empty($search_data['ord_classify'])) {
                    $query->where('ord_classify', $search_data['ord_classify']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ord_order_number'])) {
                    $query->where('ord_order_number', 'like', '%' . $search_data['ord_order_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orcl_name'])) {
                    $query->where('orcl_name', 'like', '%' . $search_data['orcl_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orcl_phone'])) {
                    $query->where('orcl_phone', 'like', '%' . $search_data['orcl_phone'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orcl_carowner_name'])) {
                    $query->where('orcl_carowner_name', 'like', '%' . $search_data['orcl_carowner_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orcl_carowner_phone'])) {
                    $query->where('orcl_carowner_phone', 'like', '%' . $search_data['orcl_carowner_phone'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orcl_car_num'])) {
                    $query->where('orcl_car_num', 'like', '%' . $search_data['orcl_car_num'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //车架号车辆识别码
                if (!empty($search_data['orcl_car_vin'])) {
                    $query->where('orcl_car_vin', 'like', '%' . $search_data['orcl_car_vin'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //买家类型：1会员零售2企业客户         
                if (!empty($search_data['ord_type'])) {
                    $query->where('ord_type', $search_data['ord_type']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ord_create_id'])) {
                    $query->where('ord_create_id', $search_data['ord_create_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ord_state'])) {
                    $query->where('ord_state', $search_data['ord_state']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ord_source'])) {
                    $query->where('ord_source', $search_data['ord_source']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ord_wor_state']) && $search_data['ord_wor_state'] != 21) {
                    $query->where('ord_wor_state', $search_data['ord_wor_state']);
                } elseif (!empty($search_data['ord_wor_state']) && $search_data['ord_wor_state'] == 21) {
                    $query->whereIn('ord_wor_state', [4,20]);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ord_payment_way'])) {
                    $query->where('ord_payment_way', $search_data['ord_payment_way']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orgo_goo_name'])) {
                    $query->where('orgo_goo_name', $search_data['orgo_goo_name']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orgo_goo_goods_encode'])) {
                    $query->where('orgo_goo_type', 3)
                        ->where('orgo_goo_goods_encode', $search_data['orgo_goo_goods_encode']);
                }
            })
            ->where(function ($query) use ($search_data) { //创建时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                    $query->whereBetween('ord_create_time', [$search_data['create_time_start'], $search_data['create_time_end'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['create_time_start'])) {
                        $query->where('ord_create_time', '>=', $search_data['create_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['create_time_end'])) {
                            $query->where('ord_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) { //预约时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['appoint_time_start']) && !empty($search_data['appoint_time_end'])) {
                    $query->whereBetween('orcl_appoint_time', [$search_data['appoint_time_start'], $search_data['appoint_time_end'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['appoint_time_start'])) {
                        $query->where('orcl_appoint_time', '>=', $search_data['appoint_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['appoint_time_end'])) {
                            $query->where('orcl_appoint_time', '<=', $search_data['appoint_time_end'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ord_client_id'])) {
                    $query->where('ord_client_id', $search_data['ord_client_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //实际金额区间搜索
                // 如果选择最小钱数并且选择最大钱数
                if (!empty($search_data['min_price']) && !empty($search_data['max_price'])) {
                    $query->whereBetween('ord_actual_price', [$search_data['min_price'] * 100, $search_data['max_price'] * 100]);
                } else {
                    // 如果选择最小钱数
                    if (!empty($search_data['min_price'])) {
                        $query->where('ord_actual_price', '>=', $search_data['min_price'] * 100);
                    } else {
                        // 如果选择最大钱数
                        if (!empty($search_data['max_price'])) {
                            $query->where('ord_actual_price', '<=', $search_data['max_price'] * 100);
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['ord_address_type']) && !empty($search_data['ord_address_id'])) {
                    $query->where('ord_address_type', $search_data['ord_address_type'])
                    ->where('ord_address_id', $search_data['ord_address_id']);
                }
            })
            //->select('ord_id', 'ord_order_number','orgo_goo_name','orgo_goo_quantity', 'orgo_goo_goods_encode', 'ord_ware_id', 'ord_order_price', 'ord_actual_price', 'ord_state', 'ord_type', 'ord_wor_state', 'ord_wor_quantity', 'ord_delete', 'ord_create_time', 'orcl_client_id', 'orcl_name', 'orcl_phone', 'orcl_car_num', 'ord_zero_price', 'orcl_appoint_time', 'orcl_car_brand_series', 'orcl_car_vin', 'orcl_sales_adm_id', 'ord_address', 'orcl_carowner_name', 'orcl_carowner_phone', 'orcl_business_name', 'ord_shop_id', 'ord_address_type', 'ord_address_id', 'ord_service_type', 'ord_settlement_time', 'ord_settlement_adm_id', 'ord_payment_way', 'orcl_mem_source', 'orcl_carbrse_type', 'ord_explain', 'ord_create_id', 'ord_service_type', 'ord_service_sepr_id', 'orcl_rescue_service_price', 'orgo_state', 'orgo_goo_price', 'ord_client_id', 'ord_ware_id', 'orgo_goo_goods_encode')
            ->select('ord_id', 'ord_order_number','ord_wor_state','orgo_state','ord_source','orgo_goo_name','orgo_goo_unit','orgo_goo_quantity', 'orgo_goo_goods_encode', 'ord_ware_id', 'ord_order_price', 'ord_actual_price', 'ord_state', 'ord_payment_way','ord_settlement_time','orcl_client_id', 'orcl_name', 'orcl_phone', 'orcl_car_num', 'orcl_car_brand_series', 'ord_type','orcl_mem_source',  'orcl_carowner_name', 'orcl_carowner_phone' ,'orcl_sales_adm_id' ,'ord_create_id', 'ord_service_adm_id', 'orcl_appoint_time','ord_create_time', 'ord_wor_quantity', 'ord_zero_price',   'orcl_car_vin', 'ord_address', 'orcl_business_name', 'ord_shop_id', 'ord_address_type','ord_service_type',  'ord_settlement_adm_id', 'orcl_carbrse_type', 'ord_explain', 'ord_service_type', 'ord_service_sepr_id', 'orcl_rescue_service_price',  'orgo_goo_price', 'ord_client_id', 'ord_ware_id', 'ord_delete' ,'ord_address_id','shop_store_name','adm_name')
            ->orderBy('ord_id', $orderby_type)
            //->groupBy('ord_id')
            ->get()->toArray();
        $data['sqls'] = DB::getQueryLog()[0];
        $sqls = $data['sqls'];
        $excel = new CommonController();
        $amp_id = $search_data['amp_id']??0;
        return $excel->getExcelOut($amp_id,$user_info,$search_data['pri_id'], $sqls, $search_data['api_token'],200);
        if (!empty($data)) {
            // 将对象转化为数组
            $data = json_decode(json_encode($data), true);
            $ord_create_id = array_unique(array_column($data, 'ord_create_id')); //创建人id
            $orcl_sales_adm_id = array_unique(array_column($data, 'orcl_sales_adm_id')); //销售人id
            $ord_service_adm_id = array_unique(array_column($data, 'ord_service_adm_id')); //技师id
            $ord_ware_id = array_unique(array_column($data, 'ord_ware_id')); //仓库id
            $ord_client_id = array_unique(array_column($data, 'ord_client_id')); //选择的客户id，会员id/单位id
            $ord_address_id = array_unique(array_column($data, 'ord_address_id')); //门店id
            $ord_shop_id = array_unique(array_column($data, 'ord_shop_id')); //门店id
            // 查询创建人信息
            $find_adm_data = DB::table('admin')
                ->whereIn('adm_id', array_merge($ord_create_id,$orcl_sales_adm_id,$ord_service_adm_id))
                ->where('adm_shop_id', $shop_id)
                ->pluck('adm_name', 'adm_id')
                ->toArray();
            // 查询客户单位
            $channel = DB::table('channel_unit')
                ->whereIn('chun_id', $ord_client_id)
                ->where('chun_shop_id', $shop_id)
                ->where('chun_state', '1')
                ->pluck('chun_unit_name', 'chun_id')
                ->toArray();
            // 查找仓库id对应的仓库名称
            $find_ware_data = DB::table('warehouse')
                ->whereIn('ware_id', $ord_ware_id)
                ->where('ware_shop_id', $user_info->adm_shop_id)
                ->pluck('ware_name', 'ware_id')
                ->toArray();
            $sepr_id = array_unique(array_column($data, 'ord_service_sepr_id'));
            // 查找服务项目id对应的名称
            $service_project = DB::table('service_project')
                ->whereIn('sepr_id', $sepr_id)
                ->pluck('sepr_name', 'sepr_id');
            //门店
            $service_project_shop = DB::table('shop')
                ->whereIn('shop_id', array_merge($ord_address_id,$ord_shop_id))
                ->pluck('shop_store_name', 'shop_id');
            $service_project_client = DB::table('business_client')
                ->whereIn('bucl_id', array_merge($ord_address_id,$ord_shop_id))
                ->pluck('bucl_name', 'bucl_id');
            foreach ($data as $key => $value) {
                if (isset($service_project[$value['ord_service_sepr_id']])) {
                    $data[$key]['ord_service_sepr_id'] = $service_project[$value['ord_service_sepr_id']];
                } else {
                    $data[$key]['ord_service_sepr_id'] = '';
                }
                $data[$key]['orcl_rescue_service_price'] = $value['orcl_rescue_service_price'] / 100; //服务项目金额
                // ord_service_type订单类型为退货单或orgo_state商品状态3回收的商品4换货商品
                if ($value['ord_service_type'] == 4 || $value['orgo_state'] == 3 || $value['orgo_state'] == 4) {
                    $data[$key]['orgo_goo_price'] = '-' . $value['orgo_goo_price'] / 100;
                } else {
                    $data[$key]['orgo_goo_price'] = $value['orgo_goo_price'] / 100;
                }
                $data[$key]['ord_actual_price'] = $value['ord_actual_price'] / 100; //结算金额
                $data[$key]['ord_order_price'] = $value['ord_order_price'] / 100; //订单金额
                if($value['ord_address_type'] == 2){
                    $data[$key]['ord_address_id'] = $service_project_client[$value['ord_address_id']];
                }else if($value['ord_address_type'] == 1){
                    $data[$key]['ord_address_id'] = $service_project_shop[$value['ord_address_id']];
                }else{
                    $data[$key]['ord_address_id'] = $service_project_shop[$value['ord_shop_id']];
                }
                // 结算方式
                /*if ($value['ord_payment_way'] == 1) {
                    $data[$key]['ord_payment_way'] = '账期';
                } elseif ($value['ord_payment_way'] == 2) {
                    $data[$key]['ord_payment_way'] = '现结';
                } elseif ($value['ord_payment_way'] == 3) {
                    $data[$key]['ord_payment_way'] = '微信';
                } elseif ($value['ord_payment_way'] == 4) {
                    $data[$key]['ord_payment_way'] = '支付宝';
                }*/
                if ($value['ord_payment_way'] == 1) {
                    $data[$key]['ord_payment_way'] = '现金';
                } elseif ($value['ord_payment_way'] == 2) {
                    $data[$key]['ord_payment_way'] = '支付宝';
                } elseif ($value['ord_payment_way'] == 3) {
                    $data[$key]['ord_payment_way'] = '微信';
                } elseif ($value['ord_payment_way'] == 4) {
                    $data[$key]['ord_payment_way'] = '银行卡';
                } elseif ($value['ord_payment_way'] == 5) {
                    $data[$key]['ord_payment_way'] = '会员卡';
                }
                // 结算状态
                if ($value['ord_state'] == '1') {
                    $data[$key]['ord_state'] = '未结算';
                } elseif ($value['ord_state'] == '2') {
                    $data[$key]['ord_state'] = '已结算';
                }
                /*if ($value['ord_state'] == '1') {
                    $data[$key]['ord_state'] = '未结算';
                } elseif ($value['ord_state'] == '2') {
                    $data[$key]['ord_state'] = '结算中';
                } elseif ($value['ord_state'] == '3') {
                    $data[$key]['ord_state'] = '已结算';
                } elseif ($value['ord_state'] == '4') {
                    $data[$key]['ord_state'] = '已代收';
                }*/
                // 订单的工单状态
                if ($value['ord_wor_state'] == '1') {
                    $data[$key]['ord_wor_state'] = '未派工单';
                } elseif ($value['ord_wor_state'] == '2') {
                    $data[$key]['ord_wor_state'] = '服务中';
                } elseif ($value['ord_wor_state'] == '4') {
                    $data[$key]['ord_wor_state'] = '待评价';
                } elseif ($value['ord_wor_state'] == '20') {
                    $data[$key]['ord_wor_state'] = '已经完成';
                } elseif ($value['ord_wor_state'] == '11') {
                    $data[$key]['ord_wor_state'] = '已取消';
                } elseif ($value['ord_wor_state'] == '7') {
                    $data[$key]['ord_wor_state'] = '待接单';
                }else{
                    $data[$key]['ord_wor_state'] = '';
                }
                // 订单类型
                if ($value['ord_type'] == '1') {
                    $data[$key]['ord_type'] = '会员零售';
                } elseif ($value['ord_type'] == '2') {
                    $data[$key]['ord_type'] = '客户单位';
                } elseif ($value['ord_type'] == '3') {
                    $data[$key]['ord_type'] = '速电派单';
                } elseif ($value['ord_type'] == '4') {
                    $data[$key]['ord_type'] = '第三方派单';
                } elseif ($value['ord_type'] == '5') {
                    $data[$key]['ord_type'] = '运营中心给门店派单';
                } else{
                    $data[$key]['ord_type'] = '';
                }
                // 服务类型
                if ($value['ord_service_type'] == '1') {
                    $data[$key]['ord_service_type'] = '服务单';
                } elseif ($value['ord_service_type'] == '2') {
                    $data[$key]['ord_service_type'] = '销售单';
                } elseif ($value['ord_service_type'] == '3') {
                    $data[$key]['ord_service_type'] = '换货单';
                } elseif ($value['ord_service_type'] == '4') {
                    $data[$key]['ord_service_type'] = '退货单';
                } elseif ($value['ord_service_type'] == '5') {
                    $data[$key]['ord_service_type'] = '发货单';
                } elseif ($value['ord_service_type'] == '6') {
                    $data[$key]['ord_service_type'] = '结清单';
                } elseif ($value['ord_service_type'] == '7') {
                    $data[$key]['ord_service_type'] = '救援单';
                }
                // 是否删除
                if ($value['ord_delete'] == 1) {
                    $data[$key]['ord_delete'] = '正常订单';
                } elseif ($value['ord_delete'] == 2) {
                    $data[$key]['ord_delete'] = '取消订单';
                }
                // 客户单位名称
                if (isset($channel[$value['ord_client_id']])) {
                    $data[$key]['orcl_channel_unit'] = $channel[$value['ord_client_id']];
                } else {
                    $data[$key]['orcl_channel_unit'] = '';
                }
                // 仓库
                if ($value['ord_ware_id'] == '0') {
                    $data[$key]['ord_ware_id'] = '';
                } else {
                    if(isset($find_ware_data[$value['ord_ware_id']])){
                        $data[$key]['ord_ware_id'] = $find_ware_data[$value['ord_ware_id']];
                    }
                }
                // 创建人
                if (isset($find_adm_data[$value['ord_create_id']])) {
                    $data[$key]['ord_create_id'] = $find_adm_data[$value['ord_create_id']];
                } else {
                    $data[$key]['ord_create_id'] = '';
                }
                // 技师
                if (isset($find_adm_data[$value['ord_service_adm_id']])) {
                    $data[$key]['ord_service_adm_id'] = $find_adm_data[$value['ord_service_adm_id']];
                } else {
                    $data[$key]['ord_service_adm_id'] = '';
                }
                // 销售人员
                if (isset($find_adm_data[$value['orcl_sales_adm_id']])) {
                    $data[$key]['orcl_sales_adm_id'] = $find_adm_data[$value['orcl_sales_adm_id']];
                } else {
                    $data[$key]['orcl_sales_adm_id'] = '';
                }
                // 订单来源
                if ($value['ord_source'] == '1') {
                    $data[$key]['ord_source'] = 'pc端';
                } elseif ($value['ord_source'] == '2') {
                    $data[$key]['ord_source'] = '车主端';
                } elseif ($value['ord_source'] == '3') {
                    $data[$key]['ord_source'] = '技师端';
                } elseif ($value['ord_source'] == '4') {
                    $data[$key]['ord_source'] = '合作商';
                } elseif ($value['ord_source'] == '5') {
                    $data[$key]['ord_source'] = '智配贴装';
                }
                // 商品编号
                $data[$key]['orgo_goo_goods_encode'] = empty("\t" . $value['orgo_goo_goods_encode']) ? '' : "\t" . $value['orgo_goo_goods_encode'];
                $data[$key]['orgo_goo_name'] = empty($value['orgo_goo_name']) ? '' : $value['orgo_goo_name'];
                $data[$key]['orgo_goo_unit'] = empty($value['orgo_goo_unit']) ? '' : $value['orgo_goo_unit'];
                $data[$key]['orgo_goo_price'] = empty($data[$key]['orgo_goo_price']) ? 0 : $data[$key]['orgo_goo_price'];
                //结算金额 // 实付金额等于 订单金额减去抹零金额，实际上应该和ord_actual_price 相等，但是还是在算一下吧；
                //$data[$key]['ord_actual_price']= $value['ord_order_price'] - $value['ord_zero_price'];
                if($value['ord_payment_way'] == 0){
                    $data[$key]['ord_payment_way'] = '';
                }
                if($value['ord_settlement_time'] == '0000-00-00 00:00:00'){
                    $data[$key]['ord_settlement_time'] = '';
                }
                if($value['orcl_appoint_time'] == '0000-00-00 00:00:00'){
                    $data[$key]['orcl_appoint_time'] = '';
                }
                unset($data[$key]['ord_plus_minus']);
                unset($data[$key]['orgo_state']);
                unset($data[$key]['ord_order_plus_minus']);
                unset($data[$key]['ord_client_id']);
                unset($data[$key]['orcl_client_id']);
                unset($data[$key]['orcl_car_vin']);
                unset($data[$key]['ord_shop_id']);
                unset($data[$key]['ord_address_type']);
                unset($data[$key]['ord_address_type']);
                unset($data[$key]['orcl_rescue_service_price']);
                unset($data[$key]['orgo_state']);
                unset($data[$key]['orcl_carbrse_type']);
                unset($data[$key]['ord_service_type']);
                unset($data[$key]['ord_settlement_adm_id']);
                unset($data[$key]['ord_service_sepr_id']);
                unset($data[$key]['orcl_channel_unit']);
                unset($data[$key]['ord_zero_price']);
                unset($data[$key]['ord_address']);
                unset($data[$key]['orcl_business_name']);
                unset($data[$key]['ord_id']);
                unset($data[$key]['ord_wor_quantity']);
                unset($data[$key]['ord_explain']);
                unset($data[$key]['orgo_goo_price']);
                unset($data[$key]['ord_delete']);
                unset($data[$key]['ord_service_adm_id']);
            }
        } else {
            return response()->json(['code'=>500, 'msg'=>'没有符合条件的数据', 'data'=>'没有符合条件的数据']);
        }



        $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
        // 创建文件夹
        if (!file_exists($pathName)) {
            mkdir($pathName, 0775, true);
            chmod($pathName, 0775);
        }

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

        $where['action_name'] = '订单列表';
        //$where['field_name'] = ['订单号', '速电单号', '录单员', '仓库名称', '服务项目', '服务金额', '商品名称', '商品编号', '单价', '商品数量', '商品总数量', '结算金额', '订单金额', '结算方式', '结算状态', '订单的工单状态', '工单数量', '订单类型', '服务类型', '客户单位', '客户姓名', '客户电话', '车牌号', '地址', '订单备注', '添加时间'];
        //$where['field_name'] = ['订单ID','订单编号','结算金额','实付金额','买家类型','结算状态','订单的工单状态','工单数量','订单状态','添加时间','客户姓名','客户电话','车牌号码','预约时间','品牌车系','车主姓名','车主电话','结算时间','结算方式','客户来源','施工说明','创建人','商品售价','仓库','商品编号','商品名称'];
        //$where['field_name'] = ['订单单号','商品名称','商品数量','检索编码','仓库','订单总额','实付金额','结算状态','买家类型','订单的工单状态','工单数量','订单状态','添加时间','客户姓名','客户电话','车牌号码','预约时间','品牌车系','车主姓名','车主电话','结算时间','结算方式','客户来源','施工说明','创建人','商品售价'];
        $where['field_name'] = ['订单单号','订单状态','订单来源','商品名称','商品单位','商品数量','检索编码','仓库','订单总额(元)','实付金额(元)','结算状态','结算方式','结算时间','会员姓名','会员电话','车牌号','品牌车系','客户类型','客户来源','车主姓名','车主电话','销售人','录单人','预约时间','创建时间','施工门店'];

        // 调用导出的公共方法
        export::publicExport(
            $streamFilename, //路径
            $where,    //sheet名及其每一行的标题
            $data      //导出数据
        );

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

    // 接单
    public function receive(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->receiveValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        $log_record['request'] = $request->all();
        $log_record['time'] = date('Y-m-d H:i:s');
        $log_record['function'] = 'receive';
        logFileRecord($log_record, 'wash/WashOrder', 2);
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        DB::beginTransaction();
        $res = WashOrderService::receive($user_info, $request->all(), $request['ord_service_type']);
        if ($res['code'] != 200) {
            DB::rollBack();
            return response()->json($res);
        }
        // 生成操作记录
        $orlo_res = orderLog($user_info, $request['ord_id'], 0, '订单接单');
        
        if ($orlo_res) {
            OperationLog::addLog($user_info, getRealIp($request), '订单列表', '接单', '接单成功');
            DB::commit();
            return $this->success('接单成功');
        } else {
            DB::rollBack();
            return $this->error('接单失败', ErrorInc::MYSQL_FAILED);
        }
    }

    /**
     * 查看凭证
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-07-11
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function getorderpic(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->getorderpicValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }

        // 获取用户信息
        $user_info = LoginUserService::getUser();
        $ord_id = $request['ord_id'];
        $return_data = WashOrderService::getorderpic($user_info, $ord_id);
        return response()->json($return_data);
    }

    /**
     * 获取支付方式
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-07-11
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function getPaymentWay(Request $request)
    {
        // 获取用户信息
        request()->offsetSet('rt', 'pc');
        $return_data = WashOrderService::getPaymentWayName(false);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$return_data]);
    }

    /*
     * @name 新增技师
     * @param array $request
     * @retrun array
     * @author Ma 2023/8/21 9:18
     *
    */
    public function addPerson(Request $request){
        $input = $request->all();
        return WashOrderService::addPerson($input);
    }

    /**
     * 换货
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|mixed
     *
     * @author huangyongqi
     *
     * @since 2023-10-24
     */
    public function exchangeGoods(Request $request) {
        $error_message = $this->dataService->mainValidator->exchangeGoods($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, [$error_message]);
        }
        $user_info = LoginUserService::getUser();
        $returnData = $this->dataService->exchangeGoods($request->all());
        if($returnData['code'] == 200) {
            OperationLog::addLog($user_info, getRealIp($request), '订单列表', '换货', '换货' . $request['ord_order_number'] . '成功');
        }
        return response()->json($returnData);
    }

    /**
     * 换货获取退款方式
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     * @author huangyongqi
     *
     * @since 2023-10-25
     */
    public function getRefundWay()
    {
        $returnData = $this->dataService->getRefundWay();
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => $returnData]);
    }

    /**
     * 换货获取付款方式
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     * @author huangyongqi
     *
     * @since 2023-10-25
     */
    public function getPayWay()
    {
        $returnData = $this->dataService->getPayWay();
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => $returnData]);
    }

    /**
     * 根据商品搜索仓库
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-09-23
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function searchWarehouse(Request $request) {
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        $return_data = WashOrderService::searchWarehouse($user_info, $request);
        return response()->json($return_data);
    }

    /**
     * 客户领取状态
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-09-23
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function recOrder(Request $request) {
        // 验证参数
        $error_message = $this->dataService->mainValidator->infoValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        $return_data = WashOrderService::recOrder($user_info, $request);
        // 生成操作记录
        $orlo_res = orderLog($user_info, $request['ord_id'], 0, '领取成功');
        return response()->json($return_data);
    }
    /**|---------------------------------------------------------------------------------
     * @name 批量新增订单导入
     * @param string file 表格数据
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2024/3/19 15:05
     * |---------------------------------------------------------------------------------
     */
    // 批量新增导入
    public function lead(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyMemberListController;
        $error_message = $verify_data->leadValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 201, 'msg' => $error_message, '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;

        $file = $request->file('file');

        if ($file->isValid()) {
            // 获取表格的大小，限制上传表格的大小5M
            $file_size = $_FILES['file']['size'];
            if ($file_size > 10 * 1024 * 1024) {
                return response()->json(['code' => 201, 'msg' => '文件大小不能超过5M', 'data' => '文件大小不能超过5M']);
            }

            // 限制上传表格类型
            $ext = $file->getClientOriginalExtension(); //文件拓展名
            if ($ext != 'xlsx') {
                return response()->json(['code' => 201, 'msg' => '仅允许上传以xlsx结尾的后缀文件', 'data' => '仅允许上传以xlsx结尾的后缀文件']);
            }

            // 有Xls和Xlsx格式两种
            $objReader = IOFactory::createReader('Xlsx');
            $filename = $_FILES['file']['tmp_name'];
            $objPHPExcel = $objReader->load($filename);  //$filename可以是上传的表格，或者是指定的表格
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            if ($highestRow < 3) {
                return response()->json(['code' => 201, 'msg' => '未获取到会员数据', 'data' => '未获取到会员数据']);
            }
            if ($highestRow > 15003) {
                return response()->json(['code' => 201, 'msg' => '一次最多导入1500条数据', 'data' => '一次最多导入1500条数据']);
            }

            // 循环读取excel表格，整合成数组,如果是不指定key的二维,就用$data[i][j]表示。
            DB::beginTransaction();
            $a = 0;
            $error = 0;
            $melo_number = $user_info->adm_shop_id . time();
            $num = 0;
            for ($j = 3; $j <= $highestRow; $j++) {
                $add_mem[$num]['ol_cid'] = $user_info->adm_cid; //所属企业id
                $add_mem[$num]['ol_shop_id'] = $user_info->adm_shop_id; //所属门店id
                $add_mem[$num]['ol_superior_shop_id'] = $shop_id; //所属门店id

                $add_mem[$num]['ol_creact_id'] = $user_info->adm_id;//操作人id
                $add_mem[$num]['ol_creact_name'] = $user_info->adm_name;//导入人姓名
                $add_mem[$num]['ol_creact_time'] = date('Y-m-d H:i:s');//导入时间
                $add_mem[$num]['ol_update_time'] = date('Y-m-d H:i:s');//更新时间
                $add_mem[$num]['ol_store_name'] = trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue());//店铺名称
                $add_mem[$num]['ol_order_num'] = trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue());//订单单号
                if (empty($add_mem[$num]['ol_order_num'])) {
                    DB::rollback();
                    $message = '第'.$j.'行订单编号未填写';
                    return response()->json(['code' => 201, 'msg' => '导入失败'.$message, 'data' => '导入失败']);
                }
                $add_mem[$num]['ol_order_creact_time'] = trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue());//订单创建时间
                if (empty($add_mem[$num]['ol_order_creact_time'])) {
                    DB::rollback();
                    $message = '第'.$j.'行进店时间未填写';
                    return response()->json(['code' => 201, 'msg' => '导入失败'.$message, 'data' => '导入失败']);
                }
                $add_mem[$num]['ol_business_source'] = trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue());//业务来源
                $add_mem[$num]['ol_reception'] = trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue());//接待人员
                $add_mem[$num]['ol_complete_time'] = trim($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue());//提车/完成时间
                if (empty($add_mem[$num]['ol_complete_time'])) {
                    DB::rollback();
                    $message = '第'.$j.'行提车时间（完工时间）未填写';
                    return response()->json(['code' => 201, 'msg' => '导入失败'.$message, 'data' => '导入失败']);
                }
                $add_mem[$num]['ol_user_name'] = trim($objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue());//客户姓名
                $add_mem[$num]['ol_user_phone'] = trim($objPHPExcel->getActiveSheet()->getCell("H" . $j)->getValue());//客户电话
                $add_mem[$num]['ol_car_plate'] = trim($objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue());//车牌号码
                $add_mem[$num]['ol_car_model'] = trim($objPHPExcel->getActiveSheet()->getCell("J" . $j)->getValue());//车辆信息
                $add_mem[$num]['ol_vin'] = trim($objPHPExcel->getActiveSheet()->getCell("K" . $j)->getValue());//vin码
                $add_mem[$num]['ol_start_mileage'] = trim($objPHPExcel->getActiveSheet()->getCell("L" . $j)->getValue());//进店里程
                $add_mem[$num]['ol_servise_type'] = trim($objPHPExcel->getActiveSheet()->getCell("M" . $j)->getValue());//服务类型
                $add_mem[$num]['ol_servise_name'] = trim($objPHPExcel->getActiveSheet()->getCell("N" . $j)->getValue());//服务名称
                if (empty($add_mem[$num]['ol_servise_name'])) {
                    DB::rollback();
                    $message = '第'.$j.'行项目名称未填写';
                    return response()->json(['code' => 201, 'msg' => '导入失败'.$message, 'data' => '导入失败']);
                }
                $add_mem[$num]['ol_servise_number'] = trim($objPHPExcel->getActiveSheet()->getCell("O" . $j)->getValue());//服务编号
                $add_mem[$num]['ol_class_one'] = trim($objPHPExcel->getActiveSheet()->getCell("P" . $j)->getValue());//一级分类
                $add_mem[$num]['ol_class_two'] = trim($objPHPExcel->getActiveSheet()->getCell("Q" . $j)->getValue());//二级分类
                $add_mem[$num]['ol_order_price'] = trim($objPHPExcel->getActiveSheet()->getCell("R" . $j)->getValue());//项目单价
                if (empty($add_mem[$num]['ol_order_price'])) {
                    $add_mem[$num]['ol_order_price'] = '0.00';
                }
                $add_mem[$num]['ol_goods_quantity'] = trim($objPHPExcel->getActiveSheet()->getCell("S" . $j)->getValue());//数量
                if (empty($add_mem[$num]['ol_goods_quantity'])) {
                    $add_mem[$num]['ol_goods_quantity'];
//                    DB::rollback();
//                    $message = '第'.$j.'行数量未填写';
//                    return response()->json(['code' => 201, 'msg' => '导入失败'.$message, 'data' => '导入失败']);
                }
                $add_mem[$num]['ol_actual_price'] = trim($objPHPExcel->getActiveSheet()->getCell("T" . $j)->getValue());//实收金额
                if (empty($add_mem[$num]['ol_actual_price'])) {
                    $add_mem[$num]['ol_actual_price'] = '0.00';
                }
                $add_mem[$num]['ol_ord_remark'] = trim($objPHPExcel->getActiveSheet()->getCell("U" . $j)->getValue());//订单备注
                $add_mem[$num]['ol_salesman'] = trim($objPHPExcel->getActiveSheet()->getCell("V" . $j)->getValue());//业务人员
                $add_mem[$num]['ol_workman'] = trim($objPHPExcel->getActiveSheet()->getCell("W" . $j)->getValue());//施工人员
                $add_mem[$num]['ol_out_num'] = trim($objPHPExcel->getActiveSheet()->getCell("X" . $j)->getValue());//出库数量
                $add_mem[$num]['ol_out_price'] = trim($objPHPExcel->getActiveSheet()->getCell("Y" . $j)->getValue());//出库金额
                $add_mem[$num]['ol_payment_way'] = trim($objPHPExcel->getActiveSheet()->getCell("Z" . $j)->getValue());//支付方式
                $add_mem[$num]['ol_user_number'] = trim($objPHPExcel->getActiveSheet()->getCell("AA" . $j)->getValue());//会员卡号
                $add_mem[$num]['ol_deduction_price'] = trim($objPHPExcel->getActiveSheet()->getCell("AB" . $j)->getValue());//抵扣金额
                $num++;
            }
            $add_res = DB::table('order_leadhistry')->insert($add_mem);
            if(!$add_res) {
                DB::rollback();
                return response()->json(['code' => 201, 'msg' => '导入失败', 'data' => '导入失败']);
            }

            Common::addLog($user_info, getRealIp($request), '服务列表', '导入', '导入服务信息');
            DB::commit();
            $msg = '上传'.($highestRow - 2).'条，失败'.$error.'条';
            return response()->json(['code' => 200, 'msg' => $msg, 'data' => $melo_number, 'num' => $highestRow - 2]);
        } else {
            return response()->json(['code' => 201, 'msg' => '上传有误，请重新上传！', 'data' => '上传有误，请重新上传！']);
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 执行导入数据
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2024/3/20 16:45
     * |---------------------------------------------------------------------------------
     */
    public function executeLead ( Request $request ){
        $request['api_token'] = '0856fcc729baa5f8ab5be39440af1629d3d6a79f';
//        return response()->json(['code' => 200, 'msg' => '操作成功！', 'data' => $request['api_token']]);
        // 获取当前操作账号信息
//        $user_info = Common::getUserInfo($request['api_token']);
        $user_info['adm_id'] = 1499;
        $user_info['adm_cid'] = 1;
        $user_info['adm_shop_id'] = 496;
        $user_info['shop_superior_id'] = 2;
        $user_info['adm_name'] = "李君利";
        $user_info['adm_phone'] = "15333806888";
        $user_info['shop_versions'] = 2;
//        return response()->json(['code' => 200, 'msg' => '操作成功！', 'data' => $user_info]);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info['shop_superior_id'] ? $user_info['shop_superior_id'] : $user_info['adm_shop_id'];
        $leadhistry = DB::table('order_leadhistry')
            ->where('ol_state',1)
            ->where('ol_cid',$user_info['adm_cid'])
            ->where('ol_superior_shop_id',$shop_id)
            ->first();
        $pay_way = [['type'=>0,'name'=>'暂不结算'],['type'=>1,'name'=>'现金'],['type'=>2,'name'=>'支付宝'],['type'=>3,'name'=>'微信'],['type'=>4,'name'=>'银行卡'],['type'=>5,'name'=>'会员卡'],['type'=>6,'name'=>'余额'],['type'=>7,'name'=>'他人代付'],['type'=>8,'name'=>'账期'],['type'=>9,'name'=>'部分结款'], ['type'=>10,'name'=>'签到领取'], ['type'=>11,'name'=>'积分兑换'], ['type'=>12,'name'=>'会员礼品'], ['type'=>13,'name'=>'美团'], ['type'=>14,'name'=>'其它']];
        $pay_way = CommonService::jointArrayKey($pay_way, 'name');
        $service_type = [['type'=>1,'name'=>'服务'],['type'=>2,'name'=>'洗车'],['type'=>3,'name'=>'商品']];
        $service_type = CommonService::jointArrayKey($service_type, 'name');
        if($leadhistry){
            DB::beginTransaction();
            $leadhistry = CommonService::dataToArray($leadhistry);
            $order = DB::table('order')
                ->where('ord_cid',$leadhistry['ol_cid'])
                ->where('ord_superior_shop_id',$leadhistry['ol_superior_shop_id'])
                ->where('ord_order_number',$leadhistry['ol_order_num'])
                ->first();
            if($order){
                $order = CommonService::dataToArray($order);
                $orgo_goo_name = '';
                if (!empty($leadhistry['ol_class_one'])) {
                    $orgo_goo_name .= $leadhistry['ol_class_one'] . "-";
                }
                if (!empty($leadhistry['ol_class_two'])) {
                    $orgo_goo_name .= $leadhistry['ol_class_two'] . "-";
                }
                if (!empty($leadhistry['ol_servise_name'])) {
                    $orgo_goo_name .= $leadhistry['ol_servise_name'];
                }
                $goods = DB::table('order_goods')
                    ->where('orgo_ord_id',$order['ord_id'])
                    ->where('orgo_goo_name',$orgo_goo_name)
                    ->first();
                if($goods){
                    $addleadhistry['ol_state'] = 3;
                    $addleadhistry['ol_state_value'] = '单号已存在';
                    $addleadhistry['ol_update_time'] = date("Y-m-d H:i:s");
                    CommonService::startmysql();
                    $data = DB::table('order_leadhistry')
                        ->where("ol_id", $leadhistry['ol_id'])
                        ->update($addleadhistry);
                    if ($data) {
                        DB::commit();
                       // return redirect('/api/b1/WashOrder/executeLead');
                        return response()->json(['code' => 200, 'msg' => '操作失败1！', 'data' => CommonService::showmysql()]);
                    } else {
                        DB::rollback();
                        return response()->json(['code' => 201, 'msg' => '执行异常请联系管理员', 'data' => '导入失败']);
                    }
                }else{
                    $ord_id = $order['ord_id'];
                    if($leadhistry['ol_order_price'] > 0 ) {
                        $edit_data['ord_order_price'] = $order['ord_order_price'] + $leadhistry['ol_order_price'] * $leadhistry['ol_goods_quantity'] * 100;//订单价格
                    }else{
                        $edit_data['ord_order_price'] = 0;
                    }
                    $edit_data['ord_update_time'] = date('Y-m-d H:i:s');
                    if( $edit_data['ord_order_price'] > 0 ){
                        $edit_order = WashOrder::where('ord_id', $ord_id)->update($edit_data);
                    }else{
                        $edit_order = true;
                    }
                    // 服务类型单子，传过来的是服务 循环来商品存
                    $orgo_data['orgo_ord_id'] = $ord_id;
                    $orgo_data['orgo_order_number'] = $leadhistry['ol_order_num'];
                    $orgo_data['orgo_goo_id'] = 660;
                    $orgo_data['orgo_goo_type'] = 2;//商品类型 1正常商品2服务3会员卡
                    $orgo_data['orgo_goo_inventory'] = 1;
                    $orgo_data['orgo_state'] = 1;
                    $orgo_data['orgo_goo_unit'] = '次';
                    $orgo_data['orgo_update_time'] = date('Y-m-d H:i:s');
                    $sepr_names = '';
                    $sepr_quantitys = 0;
                    $orgo_goo_name = '';
                    if (!empty($leadhistry['ol_class_one'])) {
                        $orgo_goo_name .= $leadhistry['ol_class_one'] . "-";
                    }
                    if (!empty($leadhistry['ol_class_two'])) {
                        $orgo_goo_name .= $leadhistry['ol_class_two'] . "-";
                    }
                    if (!empty($leadhistry['ol_servise_name'])) {
                        $orgo_goo_name .= $leadhistry['ol_servise_name'];
                    }
                    $orgo_data['orgo_goo_name'] = $orgo_goo_name;
                    $orgo_data['orgo_goo_quantity'] = $leadhistry['ol_goods_quantity'];
                    if($leadhistry['ol_order_price'] > 0 ) {
                        $orgo_data['orgo_goo_price'] = $leadhistry['ol_order_price'] * $leadhistry['ol_goods_quantity'] * 100;
                        $orgo_data['orgo_goo_amount'] = $leadhistry['ol_order_price'] * $leadhistry['ol_goods_quantity'] * 100;
                    }else{
                        $orgo_data['orgo_goo_price'] = 0;
                        $orgo_data['orgo_goo_amount'] = 0;
                    }
                    $orgo_data['orgo_can_assign_quantity'] = 0;
                    $orgo_id = DB::table('order_goods')->insertGetId($orgo_data);
                    if( $edit_order && $orgo_id ){
                        $addleadhistry['ol_state'] = 2;
                        $addleadhistry['ol_state_value'] = '添加成功';
                        $addleadhistry['ol_update_time'] = date("Y-m-d H:i:s");
                        $datas = DB::table('order_leadhistry')
                            ->where("ol_id", $leadhistry['ol_id'])
                            ->update($addleadhistry);
                        if ($datas) {
                            DB::commit();
                           // return redirect('/api/b1/WashOrder/executeLead');
                            return response()->json(['code' => 200, 'msg' => '操作成功！', 'data' => []]);
                        } else {
                            DB::rollback();
                            return response()->json(['code' => 201, 'msg' => '执行异常请联系管理员', 'data' => '导入失败']);
                        }
                    }else{
                        $addleadhistry['ol_state'] = 3;
                        $addleadhistry['ol_state_value'] = '添加订单失败';
                        $addleadhistry['ol_update_time'] = date("Y-m-d H:i:s");
                        $data = DB::table('order_leadhistry')
                            ->where("ol_id", $leadhistry['ol_id'])
                            ->update($addleadhistry);
                        if ($data) {
                            DB::commit();
                            return response()->json(['code' => 200, 'msg' => '操作失败2！', 'data' => [$edit_order,$orgo_id]]);
                        } else {
                            DB::rollback();
                            return response()->json(['code' => 201, 'msg' => '执行异常请联系管理员', 'data' => '导入失败']);
                        }
                    }
                }
            }else {
                $data['ord_cid'] = $leadhistry['ol_cid'];
                $data['ord_superior_shop_id'] = $leadhistry['ol_superior_shop_id'];
                $data['ord_shop_id'] = $leadhistry['ol_shop_id'];
                $data['ord_other_system_number'] ="" ;//$leadhistry['ol_order_num'];
                $data['ord_other_order_num'] = "";//$leadhistry['ol_order_num'];
                $data['ord_order_number'] = $leadhistry['ol_order_num'];
                $data['ord_state'] = 2;
                $data['ord_type'] = 1;//买家类型：1门店零售2企业客户
                //            $data['ord_service_type'] = 2; //订单类型：1生成工单类2不生成工单类3商品单4会员卡
                $data['ord_classify'] = 2; //订单分类：1蓄电池2洗美店3易损件
                $data['ord_is_split'] = 1; //订单拆分1正常单服务订单2多服务分订单3多服务总订单
                $data['ord_payment_way'] = $pay_way[$leadhistry['ol_payment_way']]['type'] ?? $pay_way['其它']['type']; //结算方式：1现金2支付宝3微信4银行卡5会员卡
                $data['ord_source'] = 1;  //下单来源：1pc端2车主端(车主小程序)3技师端4合作商5智配贴装
                $data['ord_add_work_state'] = 2;  //是否生成工单1是2否
                $data['ord_wor_state'] = 20;  //订单的工单状态1未派工单2服务中4已完成、待评价7待接单11取消订单20已评价
                if($leadhistry['ol_order_price'] > 0 ) {
                    $data['ord_order_price'] = $leadhistry['ol_order_price'] * $leadhistry['ol_goods_quantity'] * 100;//订单价格
                }else{
                    $data['ord_order_price'] = 0;
                }
                $data['ord_update_time'] = date('Y-m-d H:i:s');
                $ord_unique_string = md5(md5($leadhistry['ol_shop_id'] . date('Y-m-d H:i:s') . rand(10000, 99999)) . rand(10000, 99999));
                $data['ord_unique_string'] = $ord_unique_string;
                $receivable['ord_actual_price'] = $leadhistry['ol_actual_price']; //实收金额
                $data['ord_explain'] = '';
                $data['ord_service_type'] = $service_type[$leadhistry['ol_payment_way']]['type'] ?? 1;
                $ord_id = WashOrder::insertGetId($data);
                /*-------------------------------------------同步生成应收应付------------------------------------------*/
                $receivable['recpay_cid'] = $data['ord_cid'];
                $receivable['recpay_shop_id'] = $data['ord_shop_id'];
                $receivable['recpay_shop_superior_id'] = $data['ord_superior_shop_id'];
                $receivable['recpay_type'] = '1'; //类型：1.销售订单
                $receivable['recpay_original_id'] = $ord_id; //与类型所对应的id
                $receivable['recpay_original_number'] = $data['ord_order_number']; //与类型所对应的单号
                $receivable['recpay_client_type'] = 6; //客户类型：1.会员零售 2.来往单位 3.加盟店 4会员零售(工单代收）
                $receivable['recpay_client_id'] = '0'; //会员id/来往单位id
                $receivable['recpay_client_name'] = ''; //来往单位名称
                $receivable['recpay_receivable_price'] = $data['ord_order_price']; //应收金额
                $receivable['recpay_arrears_price'] = 0; //欠收金额
                $receivable['recpay_actual_price'] = $receivable['ord_actual_price']; //实收金额
                $receivable['recpay_cost_price'] = '0'; //成本价
                $receivable['recpay_receivable_pay'] = '0'; //应付金额
                $receivable['recpay_actual_pay'] = '0'; //实付金额
                $receivable['recpay_state'] = '1'; //状态：1未确认2已确认
                $receivable['recpay_order_state'] = '1'; //订单状态：1正常2退款3取消
                $receivable['recpay_remark'] = ''; //备注
                $receivable['recpay_plus_minus'] = '1'; //盈利正负：1正值2负值
                $receivable['recpay_profit'] = '0'; //盈利金额

                ReceivablePayService::add($receivable);
                /*-------------------------------------------同步生成应收应付------------------------------------------*/

                $remaek['orre_cid'] = $data['ord_cid'];
                $remaek['orre_superior_shop_id'] = $data['ord_superior_shop_id'];
                $remaek['orre_shop_id'] = $data['ord_shop_id'];
                $remaek['orre_ord_id'] = $ord_id;
                $remaek['orre_wor_id'] = 0;
                $remaek['orre_create_adm_name'] = '系统同步';
                $remaek['orre_create_adm_id'] = 0;
                $remaek['orre_time'] = date("Y-m-d H:i:s");

                // 添加订单客户表数据
                $orcl_data = [
                    'orcl_ord_id' => $ord_id,
                    // 'orcl_business_name' => isset($request['orcl_business_name']) ? $request['orcl_business_name'] : '',//企业名称
                    // 'orcl_business_id' => isset($request['orcl_business_id']) ? $request['orcl_business_id'] : '',//企业id
                    'orcl_name' => $leadhistry['ol_user_name'] ?? '散户',
                    'orcl_phone' => $leadhistry['ol_user_phone'] ?? '',
                    'orcl_carowner_name' => $leadhistry['ol_user_name'] ?? '',
                    'orcl_carowner_phone' => $leadhistry['ol_user_phone'] ?? '',
                    'orcl_car_num' => $leadhistry['ol_car_plate'] ?? '',
                    'orcl_car_vin' => $leadhistry['ol_vin'] ?? '', //车架号 车辆识别码
                    'orcl_car_vehicle_type' => $leadhistry['ol_car_model'] ?? '', //车辆信息
                    'orcl_mem_source' => $leadhistry['ol_business_source'] ?? '', //客户来源
                    'orcl_province' => '',
                    'orcl_city' => '',
                    'orcl_county' => '',
                    'orcl_address' => '',
                    'orcl_update_time' => date('Y-m-d H:i:s'),
                ];

                // 客户下单备注
                if (!empty($request['ol_ord_remark'])) {
                    $remaek['orre_content'] = $request['ol_ord_remark'];
                    $remaek['orre_module'] = '客户留言';
                    DB::table('zptz_remarks')->insertGetId($remaek);
                    $orcl_data['orcl_cus_msg'] = $request['ol_ord_remark'];
                }
                if (!empty($leadhistry['ol_reception'])) {
                    $remaek['orre_content'] = $leadhistry['ol_reception'];
                    $remaek['orre_module'] = '接单人';
                    DB::table('zptz_remarks')->insertGetId($remaek);
                }
                if (!empty($leadhistry['ol_car_plate'])) {
                    $remaek['orre_content'] = $leadhistry['ol_car_plate'];
                    $remaek['orre_module'] = '车牌号码';
                    DB::table('zptz_remarks')->insertGetId($remaek);
                }
                if (!empty($leadhistry['ol_car_model'])) {
                    $remaek['orre_content'] = $leadhistry['ol_car_model'];
                    $remaek['orre_module'] = '车辆信息';
                    DB::table('zptz_remarks')->insertGetId($remaek);
                    $orcl_data['orcl_car_brand_series'] = $leadhistry['ol_car_model'];
                }
                if (!empty($leadhistry['ol_vin'])) {
                    $remaek['orre_content'] = $leadhistry['ol_vin'];
                    $remaek['orre_module'] = 'vin码';
                    DB::table('zptz_remarks')->insertGetId($remaek);
                }
                if (!empty($leadhistry['ol_store_name'])) {
                    $remaek['orre_content'] = $leadhistry['ol_store_name'];
                    $remaek['orre_module'] = '店铺名称';
                    DB::table('zptz_remarks')->insertGetId($remaek);
                }
                if (!empty($leadhistry['ol_start_mileage'])) {
                    $remaek['orre_content'] = $leadhistry['ol_start_mileage'];
                    $remaek['orre_module'] = '进店里程';
                    DB::table('zptz_remarks')->insertGetId($remaek);
                }
                if (!empty($leadhistry['ol_salesman'])) {
                    $remaek['orre_content'] = $leadhistry['ol_salesman'];
                    $remaek['orre_module'] = '业务人员';
                    DB::table('zptz_remarks')->insertGetId($remaek);
                }
                if (!empty($leadhistry['ol_workman'])) {
                    $remaek['orre_content'] = $leadhistry['ol_workman'];
                    $remaek['orre_module'] = '施工人员';
                    DB::table('zptz_remarks')->insertGetId($remaek);
                }
                if (!empty($leadhistry['ol_user_number'])) {
                    $remaek['orre_content'] = $leadhistry['ol_user_number'];
                    $remaek['orre_module'] = '会员卡号';
                    DB::table('zptz_remarks')->insertGetId($remaek);
                }
                if (!empty($leadhistry['ol_payment_way'])) {
                    $remaek['orre_content'] = $leadhistry['ol_payment_way'];
                    $remaek['orre_module'] = '支付方式';
                    DB::table('zptz_remarks')->insertGetId($remaek);
                }
                if (!empty($leadhistry['ol_deduction_price'])) {
                    $remaek['orre_content'] = $leadhistry['ol_deduction_price'];
                    $remaek['orre_module'] = '抵扣金额';
                    DB::table('zptz_remarks')->insertGetId($remaek);
                }
                if ($leadhistry['ol_goods_quantity'] > 0 && $leadhistry['ol_goods_quantity'] < 1) {
                    $remaek['orre_content'] = $leadhistry['ol_goods_quantity'];
                    $remaek['orre_module'] = '订单商品数量';
                    DB::table('zptz_remarks')->insertGetId($remaek);
                }
                $orcl_id = DB::table('order_client')->insertGetId($orcl_data);
                $edit_data['ord_orcl_id'] = $orcl_id;
                WashOrder::where('ord_id', $ord_id)->update($edit_data);
                // 服务类型单子，传过来的是服务 循环来商品存
                $orgo_data['orgo_ord_id'] = $ord_id;
                $orgo_data['orgo_order_number'] = $leadhistry['ol_order_num'];
                $orgo_data['orgo_goo_id'] = 660;
                $orgo_data['orgo_goo_type'] = 2;//商品类型 1正常商品2服务3会员卡
                $orgo_data['orgo_goo_inventory'] = 1;
                $orgo_data['orgo_state'] = 1;
                $orgo_data['orgo_goo_unit'] = '次';
                $orgo_data['orgo_update_time'] = date('Y-m-d H:i:s');
                $sepr_names = '';
                $sepr_quantitys = 0;
                $orgo_goo_name = '';
                if (!empty($leadhistry['ol_class_one'])) {
                    $orgo_goo_name .= $leadhistry['ol_class_one'] . "-";
                }
                if (!empty($leadhistry['ol_class_two'])) {
                    $orgo_goo_name .= $leadhistry['ol_class_two'] . "-";
                }
                if (!empty($leadhistry['ol_servise_name'])) {
                    $orgo_goo_name .= $leadhistry['ol_servise_name'];
                }
                $orgo_data['orgo_goo_name'] = $orgo_goo_name;
                $orgo_data['orgo_goo_quantity'] = $leadhistry['ol_goods_quantity'];
                $orgo_data['orgo_goo_price'] = $data['ord_order_price'];
                $orgo_data['orgo_goo_amount'] = $data['ord_order_price'];
                $orgo_data['orgo_can_assign_quantity'] = 0;
                $orgo_id = DB::table('order_goods')->insertGetId($orgo_data);
                if ($ord_id && $orcl_id && $orgo_id) {
                    $addleadhistry['ol_state'] = 2;
                    $addleadhistry['ol_state_value'] = '添加成功';
                    $addleadhistry['ol_update_time'] = date("Y-m-d H:i:s");
                    $datas = DB::table('order_leadhistry')
                        ->where("ol_id", $leadhistry['ol_id'])
                        ->update($addleadhistry);
                    if ($datas) {
                        DB::commit();
                       // return redirect('/api/b1/WashOrder/executeLead');
                        return response()->json(['code' => 200, 'msg' => '操作成功！', 'data' => []]);
                    } else {
                        DB::rollback();
                        return response()->json(['code' => 201, 'msg' => '执行异常请联系管理员', 'data' => '导入失败']);
                    }
                } else {
                    $addleadhistry['ol_state'] = 3;
                    $addleadhistry['ol_state_value'] = '添加订单失败';
                    $addleadhistry['ol_update_time'] = date("Y-m-d H:i:s");
                    $data = DB::table('order_leadhistry')
                        ->where("ol_id", $leadhistry['ol_id'])
                        ->update($addleadhistry);
                    if ($data) {
                        DB::commit();
                       // return redirect('/api/b1/WashOrder/executeLead');
                        return response()->json(['code' => 200, 'msg' => '操作失败3！', 'data' => []]);
                    } else {
                        DB::rollback();
                        return response()->json(['code' => 201, 'msg' => '执行异常请联系管理员', 'data' => '导入失败']);
                    }
                }
            }
        }else{
            return response()->json(['code' => 202, 'msg' => '已执行完毕！', 'data' => []]);
        }
    }

    /**
     * 获取表头数据
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-04-24
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function getTitle(Request $request) {
        // 验证参数
        $error_message = $this->dataService->mainValidator->getTitleValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        $user_info = LoginUserService::getUser();

        $data = DB::table('title')
            ->where('type', $request['type'])
            ->orderBy('sort')
            ->get()->toArray();
        $find_title = DB::table('custom_header')
            ->where('ch_shop_id', $user_info->adm_shop_id)
            ->where('ch_adm_id', $user_info->adm_id)
            ->where('ch_type', $request['type'])
            ->first();
        if ($find_title) {
            $ch_data = json_decode($find_title->ch_data, true);
            $id = array_column($ch_data, 'id');
            foreach ($data as $key => $value) {
                if (!in_array($value->id,$id)) {
                    $ch_data[] = $value;
                }
            }
            $data = $ch_data;
        } else {
            foreach ($data as $key => $value) {
                $data[$key]->is_selected = 1;
            }
        }
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data]);
    }

    /**
     * 设置表头
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-04-24
     * @param  Request          $request [description]
     */
    public function setTitle(Request $request) {
        // 验证参数
        $error_message = $this->dataService->mainValidator->setTitleValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        $user_info = LoginUserService::getUser();
        $find_data = DB::table('custom_header')
            ->where('ch_shop_id', $user_info->adm_shop_id)
            ->where('ch_adm_id', $user_info->adm_id)
            ->where('ch_type', $request['type'])
            ->first();
        if ($find_data) {
            $update_data['ch_data'] = json_encode($request['ch_data'], true);
            $update_data['ch_update_time'] = date('Y-m-d H:i:s');
            $res = DB::table('custom_header')->where('ch_id', $find_data->ch_id)->update($update_data);
        } else {
            $add_data['ch_shop_id'] = $user_info->adm_shop_id;
            $add_data['ch_adm_id'] = $user_info->adm_id;
            $add_data['ch_type'] = $request['type'];
            $add_data['ch_data'] = json_encode($request['ch_data'], true);
            $add_data['ch_create_time'] = date('Y-m-d H:i:s');
            $add_data['ch_create_id'] = $user_info->adm_id;
            $res = DB::table('custom_header')->insertGetId($add_data);
        }
        return response()->json(['code' => 200, 'msg' => '设置成功', 'data' =>'']);
    }

    /**
     * 订单类型
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-07-29
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function orderType(Request $request) {
        $user_info = LoginUserService::getUser();
        $res = WashOrderService::orderType($user_info,$request);
        return response()->json($res);
    }

    /**
     * 新增类型
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-07-29
     * @param  Request          $request [description]
     */
    public function addOrderType(Request $request) {
        // 验证参数
        $error_message = $this->dataService->mainValidator->addOrderTypeValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        $user_info = LoginUserService::getUser();
        $res = WashOrderService::addOrderType($user_info,$request);
        return response()->json($res);
    }

    /**
     * 编辑类型
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-07-29
     * @param  Request          $request [description]
     */
    public function editOrderType(Request $request) {
        // 验证参数
        $error_message = $this->dataService->mainValidator->editOrderTypeValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        $user_info = LoginUserService::getUser();
        $res = WashOrderService::editOrderType($user_info,$request);
        return response()->json($res);
    }

    /**
     * 启用类型
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-07-29
     * @param  Request          $request [description]
     */
    public function startOrderType(Request $request) {
        // 验证参数
        $error_message = $this->dataService->mainValidator->stateOrderTypeValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        $user_info = LoginUserService::getUser();
        $res = WashOrderService::startOrderType($user_info,$request);
        return response()->json($res);
    }

    /**
     * 启用类型
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-07-29
     * @param  Request          $request [description]
     */
    public function stopOrderType(Request $request) {
        // 验证参数
        $error_message = $this->dataService->mainValidator->stateOrderTypeValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        $user_info = LoginUserService::getUser();
        $res = WashOrderService::stopOrderType($user_info,$request);
        return response()->json($res);
    }

    /**
     * 设置默认
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2025-02-19
     * @param  Request          $request [description]
     */
    public function setUpDefault(Request $request) {
        // 验证参数
        $error_message = $this->dataService->mainValidator->stateOrderTypeValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        $user_info = LoginUserService::getUser();
        $res = WashOrderService::setUpDefault($user_info,$request);
        return response()->json($res);
    }

    /**
     * 订单挂起
     */
    public function suspended(Request $request) {
        // 验证参数
        $error_message = $this->dataService->mainValidator->suspendedValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        $user_info = LoginUserService::getUser();
        $res = WashOrderService::suspended($user_info,$request);
        return response()->json($res);
    }

    /**
     * 订单取消挂起-恢复
     */
    public function cancelSuspended(Request $request) {
        // 验证参数
        $error_message = $this->dataService->mainValidator->suspendedValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        $user_info = LoginUserService::getUser();
        $res = WashOrderService::cancelSuspended($user_info,$request);
        return response()->json($res);
    }

    /**
     * 配置基础项
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2026-01-07
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function basicSet(Request $request) {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if (!isset($request['type'])) {
            return response()->json(['code'=>500, 'msg'=>'参数错误', 'data'=>'']);
        }
        $res = WashOrderService::basicSet($user_info, $request);
        return response()->json($res);
    }

    /**
     * 开票
     */
    public function openBill(Request $request) {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if (!isset($request['ord_id'])) {
            return response()->json(['code'=>500, 'msg'=>'参数错误', 'data'=>'']);
        }

        $res = WashOrderService::openBill($user_info, $request);
        return response()->json($res);
    }

    /**
     * 同意取消
     */
    public function auditCancel(Request $request) {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if (!isset($request['ord_id'])) {
            return response()->json(['code'=>500, 'msg'=>'参数错误', 'data'=>'']);
        }
        if ($request['type'] == 1) {
            $data = DB::table('cancel_order_data')
                ->where('ord_id', $request['ord_id'])
                ->orderBy('id', 'desc')
                ->first();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }
        DB::beginTransaction();
        $res = WashOrderService::auditCancel($user_info, $request);
        if ($res['code'] ==200) {
            if($request['pass'] == 1) {
                $state_name = '通过';
            } else {
                $state_name = '驳回';
                if ($request['remark']) {
                    $orre_res = orderRemark($user_info, $request['ord_id'], '', $request['remark'], '订单列表');
                }
            }
            $orlo_res = orderLog($user_info, $request['ord_id'], '', '审核取消'.$state_name);
            OperationLog::addLog($user_info, getRealIp($request), '订单列表', '审核取消', '审核取消' .$state_name. $request['ord_order_number'] . '成功');
            DB::commit();
        } else {
            DB::rollback();
        }
        return response()->json($res);
    }
}
