<?php

namespace App\Http\Controllers\Mounting\Business;

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\WashWorkService;
use App\Services\Business\WashWorkBasicService;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\LoginUserService;
use App\Models\OperationLog;
use Illuminate\Support\Facades\DB;
use App\Services\BasicManagement\MeritPayService;
use App\Services\Business\WashPayservice;
use App\Services\Shop\ShopService;
use App\Services\CommonService;

// 工单列表
class WashWorkController extends Controller
{
    public $dataService = null;

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $user_info = LoginUserService::getUser();
        $request['show_count'] = isset($request['show_count']) ?$request['show_count']:10;
        $search_data = $this->dataService->searchPage($user_info, $request->all(), $request['show_count']);
        if(isset($request['is_excel']) && $request['is_excel']==2){
            return $search_data;
        }
        $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', 2)
            ->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', 2)
                ->select('title', 'field')
                ->get()->toArray();
        }
        // if (empty($search_data)) {
        //     return $this->error('未找到数据', ErrorInc::DATA_EMPTY);
        // } else {
        // }
        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        unset($list_button[7]);
        //获取top按钮
        $sea_button_data = 'toUserPicAll,exports,batchAuditWork';
        $top_button = CommonService::getTopButton('',$sea_button_data,$list_button);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$search_data, 'list_button'=>$list_button, 'ch_data'=>$ch_data, 'top_button'=>$top_button]);
    }

    public function planIndex(Request $request)
    {
        $user_info = LoginUserService::getUser();
        $request['show_count'] = isset($request['show_count']) ?$request['show_count']:10;
        $search_data = $this->dataService->planIndex($user_info, $request->all(), $request['show_count']);
        // $request['pri_id'] = 683;
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        $sea_button_data = 'setTitle';
        $top_button = CommonService::getTopButton('',$sea_button_data,$list_button);
        if (empty($search_data)) {
            // return $this->error('未找到数据', ErrorInc::DATA_EMPTY);
            return response()->json(['code'=>500, 'msg'=>'未找到数据', 'data'=>$search_data, 'top_button'=>$top_button]);
        } else {
            // 获取当前列表下的按钮
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$search_data, 'top_button'=>$top_button]);
        }
    }

    /**
     * 设置计划任务表头
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2025-03-26
     * @param  Request          $request [description]
     */
    public function setPlanTitle(Request $request) {
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        $find_data = DB::table('shop_showset')
            ->where('shst_shop_id', $user_info->adm_shop_id)
            ->first();
        $all_data['work_data'] = [['name'=>'订单单号','field'=>'ord_order_number', 'select'=>false],['name'=>'工单单号','field'=>'wor_number', 'select'=>false],['name'=>'施工门店','field'=>'wopl_address', 'select'=>false],['name'=>'预约时间','field'=>'wopl_date', 'select'=>false],['name'=>'销售人员','field'=>'wopl_sale_name', 'select'=>false],['name'=>'施工说明','field'=>'wopl_explain', 'select'=>false],['name'=>'施工人员','field'=>'service_adm_name', 'select'=>false]];

        $all_data['goods_data'] = [['name'=>'商品名称','field'=>'orgo_goo_name', 'select'=>false],['name'=>'商品数量','field'=>'orgo_goo_quantity', 'select'=>false],['name'=>'商品单位','field'=>'orgo_goo_unit', 'select'=>false]];
        $all_data['mem_data'] = [['name'=>'姓名/电话','field'=>'mem_name', 'select'=>false],['name'=>'车牌号','field'=>'orcl_car_num', 'select'=>false],['name'=>'品牌系列','field'=>'orcl_car_brand_series', 'select'=>false],['name'=>'车辆颜色','field'=>'mem_car_color', 'select'=>false],['name'=>'客户来源','field'=>'mem_source', 'select'=>false],['name'=>'会员标签','field'=>'mem_label_name', 'select'=>false],['name'=>'会员等级','field'=>'mem_level_name', 'select'=>false],['name'=>'业务员','field'=>'mem_salesman_name', 'select'=>false]];
        if ($request['type'] == 1) {
            if (empty($find_data)) {
                $return_data['shst_state'] = 2;
                $return_data['all_data'] = $all_data;
            } else {
                if (!empty($find_data->shst_data)) {
                    $return_data['all_data'] = json_decode($find_data->shst_data, true);
                    if (empty($return_data['all_data']['work_data']) || empty($return_data['all_data']['goods_data']) || empty($return_data['all_data']['mem_data'])) {
                        $return_data['all_data'] = $all_data;
                    }
                } else {
                    $return_data['all_data'] = $all_data;
                }
                $return_data['shst_state'] = $find_data->shst_state;
            }
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$return_data]);
        } else {
            if ($find_data) {
                if ($request['shst_state'] == 1) {
                    if (!empty($request['shst_data'])) {
                        if (empty($request['shst_data']['work_data']) || empty($request['shst_data']['goods_data']) || empty($request['shst_data']['mem_data'])) {
                            return response()->json(['code'=>200, 'msg'=>'设置失败，请刷新页面后重新设置', 'data'=>'']);
                        }
                        $update_data['shst_data'] = json_encode($request['shst_data'], true);
                    }
                }
                $update_data['shst_state'] = $request['shst_state'];
                $update_res = DB::table('shop_showset')
                    ->where('shst_id', $find_data->shst_id)
                    ->update($update_data);
            } else {
                $add_data['shst_shop_id'] = $user_info->adm_shop_id;
                $add_data['shst_type'] = 'plan';
                $add_data['shst_data'] = json_encode($request['shst_data'], true);
                $add_data['shst_state'] = $request['shst_state'];
                $update_res = DB::table('shop_showset')->insert($add_data);
            }
            return response()->json(['code'=>200, 'msg'=>'设置成功', 'data'=>'']);
        }
    }

    // 工单-重新派单
    public function assign(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->assignValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        if ($request['type'] == 1) {
            $find_work = DB::table('work_order as wor')
                ->leftjoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wor.wor_id')
                ->where('wor_id', $request['wor_id'])
                ->where('wor_shop_id', $user_info->adm_shop_id)
                ->select('wor_number', 'wor_explain', 'wor_appoint_time', 'wor_address', 'wor_address_id', 'wor_address_type')
                ->first();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$find_work]);
        }
        DB::beginTransaction();
        request()->offsetSet('wor_service_adm_id', $request['service_adm_id']);
        // 提交重新派单数据
        $return_data = WashWorkService::assign($user_info, $request->all());
        if ($return_data['code'] == 500) {
            return $return_data;
        }
        if ($return_data['code'] == 200) {
            DB::commit();
            OperationLog::addLog($user_info, getRealIp($request), '工单列表', '重新派单', '重新派单成功');
            return $this->success('重新派单成功');
        } else {
            DB::rollBack();
            return $return_data;
        }
    }

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

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

    // 工单审核
    public function check(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->checkShowValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        // $performance_appraisal_method['choose']['choose_type'] = '1';
        // $performance_appraisal_method['choose']['choose_type_name'] = '按施工部位';
        // $performance_appraisal_method['choose']['vehicle_type'] = '1';
        // $performance_appraisal_method['choose']['vehicle_type_name'] = '简单车型、普通车型、复杂车型';
        // $performance_appraisal_method['choose']['inspection_items'] = '考核项id';
        // $performance_appraisal_method['choose']['inspection_items_name'] = '考核项名称';
        // $technician_data['wotp_id'] = '施工项id';
        // $construction_image[] = '施工信息图片';
        // $construction_image[] = '施工信息图片2';
        // $technician_data['construction_information']['image'] = $construction_image;
        // $quality_control['quality_item_type'] = '质检项';
        // $quality_control['quality_item_name'] = '质检项名称';
        // $quality_control['quality_item_score'] = '质检项分数';
        // $technician_data['quality_control'][] = $quality_control;
        // $rewards_punishment['type'] = '奖惩项类型1奖励2惩罚';
        // $rewards_punishment['rewards_punishment_id'] = '奖惩项id';
        // $rewards_punishment['rewards_punishment_name'] = '奖惩项名称';
        // $rewards_punishment['rewards_punishment_score'] = '奖惩项扣分或奖励金额';
        // $rewards_image[] = '奖惩图片';
        // $rewards_image[] = '奖惩图片2';
        // $rewards_punishment['rewards_punishment_image'] = $rewards_image;
        // $technician_data['rewards_punishment'][] = $rewards_punishment;
        // $performance_appraisal_method['technician'][] = $technician_data;

        // 获取用户信息
        $user_info = LoginUserService::getUser();
        if ($request['type'] == '1') {
            // 获取数据
            $return_data = WashWorkService::info($user_info, $request->all());
            return response()->json($return_data);
        }
        // 验证参数
        $error_message = $this->dataService->mainValidator->checkValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        DB::beginTransaction();
        $find_recycle = DB::table('recede_recycle')
            ->where('rec_shop_id', $user_info->adm_shop_id)
            ->where('rec_ord_id', $request['wor_id'])
            ->where('rec_state', 1)
            ->value('rec_id');
        if (!empty($find_recycle)) {
            return response()->json(['code'=>500, 'msg'=>'退换回收未入库', 'data'=>'退换回收未入库']);
        }
        // 提交审核数据
        $return_data = WashWorkService::check($user_info, $request->all());
        if ($return_data['code'] != 200) {
            DB::rollBack();
            return response()->json($return_data);
        }

        // 生成操作记录
        $orlo_res = orderLog($user_info, 0, $request['wor_id'], '工单审核');
        if ($request['remark']) {
            // 添加备注
            $orre_res = orderRemark($user_info, 0, $request['wor_id'], $request['remark'], '工单审核');
        } else {
            $orre_res = true;
        }
        // // 工单信息
        $find_wor_data = DB::table('work_order as wo')
            ->leftJoin('work_client as wc', 'wo.wor_id', '=', 'wc.wocl_wor_id')
            ->leftJoin('order as o', 'wo.wor_order_id', '=', 'o.ord_id')
            ->where('wor_id', $request['wor_id'])
            ->select('wocl_client_id', 'wor_shop_id', 'wor_order_id', 'ord_order_number', 'ord_source', 'ord_actual_price', 'ord_payment_way')
            ->first();
        $out_order_no = $find_wor_data->ord_order_number;
        $weixin_record = DB::table('weixin_record')
            ->where('out_trade_no', $out_order_no)
            ->select('were_transaction_id', 'were_sub_mchid', 'were_id', 'were_sub_ledger', 'were_unfreeze')
            ->first();
        if ($weixin_record && $weixin_record->were_sub_ledger == 2 && $weixin_record->were_unfreeze == 2) {
            $receivers[0]['type'] = 'MERCHANT_ID';
            $receivers[0]['receiver_account'] = config('apisystem.MCHID');
            $receivers[0]['amount'] = floor($find_wor_data->ord_actual_price * 0.3);
            $receivers[0]['description'] = '给服务商分账';
            $transaction_id = $weixin_record->were_transaction_id;
            $sub_mchid = $weixin_record->were_sub_mchid;
            $finish = true;
            $reqAccount = WashPayservice::reqAccount($out_order_no, $transaction_id, $sub_mchid, $receivers,$finish);
            $update_data_were['were_sub_ledger'] = 1;
            $update_data_were['were_unfreeze'] = 1;//是否解冻1是2否
            $update_data_were['were_subledger_amount'] = floor($find_wor_data->ord_actual_price * 0.3);
            $update_data_were['were_update_time'] = date('Y-m-d H:i:s');
            $update_were_res = DB::table('weixin_record')
                ->where('were_id', $weixin_record->were_id)
                ->update($update_data_were);
        }
        if ($weixin_record && $weixin_record->were_sub_ledger == 1 && $weixin_record->were_unfreeze == 2) {
            $transaction_id = $weixin_record->were_transaction_id;
            $sub_mchid = $weixin_record->were_sub_mchid;
            $description = '分账完结';
            $reqAccount = WashPayservice::finishAccount($out_order_no, $transaction_id, $sub_mchid, $description);
            $update_data_were['were_sub_ledger'] = 2;
            $update_data_were['were_subledger_amount'] = 0;
            $update_data_were['were_unfreeze'] = 1;//是否解冻1是2否
            $update_data_were['were_update_time'] = date('Y-m-d H:i:s');
            $update_were_res = DB::table('weixin_record')
                ->where('were_id', $weixin_record->were_id)
                ->update($update_data_were);
        }

        //20230724  修改订单应收应付  绩效核算
        $rece_params['recpay_original_number'] = $find_wor_data->ord_order_number;//订单id
        $all_actual = DB::table('wash_performance_work')
            ->where('pewo_ord_order_number', $find_wor_data->ord_order_number)
            ->select('pewo_performance_total_price')
            ->get()->toArray();
        $total_price = 0;
        foreach ($all_actual as $ac_key => $ac_value){
            $total_price += $ac_value->pewo_performance_total_price;
        }
        $rece_params['recpay_receivable_pay'] = $total_price / 100;//应付金额
        $rece_params['recpay_actual_pay'] = $total_price / 100;//实付金额
        $rece_params['recpay_statue_pay'] = 1;//绩效已结算
        $recpay = DB::table('receivable_pay')->where('recpay_original_number', $find_wor_data->ord_order_number)->first();
        if($recpay){
            $profit = $recpay->recpay_actual_price / 100 - $recpay->recpay_cost_price / 100 -  $total_price / 100;
            if($profit > 0){
                $minus = 1;
            }else{
                $minus = 2;
                $profit = abs($profit);
            }
            $rece_params['recpay_plus_minus'] = $minus;//盈利正负：1正值2负值
            $rece_params['recpay_profit'] = $profit;//盈利金额
            ReceivablePayService::edit($rece_params);
        }

        if ($orlo_res && $orre_res /*&& $addUserMessage_res['code'] == 200*/ /*&& $addAdminMessage_res['code'] == 200*/) {
            // 订单历史记录
            $data['wohi_primary_id'] = $find_wor_data->wor_order_id;
            $data['wohi_state_name'] = '待评价';
            $data['wohi_state'] = 4;
            $data['wohi_type'] = 1;
            addHistory($data);
            unset($data);
            DB::commit();
            OperationLog::addLog($user_info, getRealIp($request), '工单列表', '工单审核', '工单审核'.$return_data['data']['wor_number'].'成功');
            return $this->success('绩效核算成功');
        } else {
            DB::rollBack();
            return $this->error('绩效核算失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 获取绩效金额
    public function getMeritPay(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->getMeritPayValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        $return_data = WashWorkService::getMeritPay($user_info, $request->all());
        return response()->json($return_data);
    }

    // 获取整车车型
    public function getMeritPayCar(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->getMeritPayCarValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        $return_data = WashWorkService::getMeritPayCar($user_info, $request->all());
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$return_data]);
    }

    // 验证绩效金额
    public function checkMeritPay(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->checkMeritPayValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        $return_data = WashWorkService::checkMeritPay($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_work = WashWorkService::withdraw($user_info, $request->all());
        if ($return_data_work['code'] != 200) {
            DB::rollBack();
            return $return_data_work;
        }
        // 判断门店版本
        if ($user_info->shop_versions == 1) {
            // 基础版流程
            $return_data = WashWorkBasicService::cancel($user_info, $request->all());
        } else {
            // 取消工单
            $return_data = WashWorkService::cancel($user_info, $request->all());
        }
        if ($return_data['code'] != 200) {
            DB::rollBack();
            return $return_data;
        } else {
            DB::commit();
            OperationLog::addLog($user_info, getRealIp($request), '工单列表', '取消工单', '取消工单'.$return_data['data']['wor_order_number'].'成功');
            return $this->success('取消工单成功');
        }
        // // 生成操作记录
        // $orlo_res = orderLog($user_info, $return_data['data']['wor_order_id'], 0, '取消工单');
        // if ($request['remark']) {
        //     // 添加备注
        //     $orre_res = orderRemark($user_info, 0, $request['wor_id'], $request['remark'], '取消工单');
        // } else {
        //     $orre_res = true;
        // }
        // if ($orlo_res) {
        //     DB::commit();
        //     OperationLog::addLog($user_info, getRealIp($request), '工单列表', '取消工单', '取消工单'.$return_data['data']['wor_order_number'].'成功');
        //     return $this->success('取消工单成功');
        // } else {
        //     DB::rollBack();
        //     // return $this->error('取消工单失败', ErrorInc::MYSQL_FAILED);
        //     return response()->json($return_data);
        // }
    }

    // 备注
    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 = WashWorkService::remarkSearch($user_info, $request->all());
        $orre_res = orderRemark($user_info, $return_data['wor_order_id'], $request['wor_id'],  $request['remark'], '工单列表');
        if ($orre_res) {
            OperationLog::addLog($user_info, getRealIp($request), '工单列表', '备注', '工单 '.$return_data['wor_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 $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        $request->offsetSet('ip', getRealIp($request));
        DB::beginTransaction();
        $return_data = $this->dataService->appointmentSet($user_info, $request->all());
        if ($return_data['code'] != 200) {
            DB::rollBack();
            return response()->json($return_data);
        }

        // 生成操作记录
        $orlo_res = orderLog($user_info, $return_data['data']['wor_order_id'], $request['wor_id'], '预约设置');
        // 预约备注内容
        $remark_data = '预约时间：' . $request['appoint_time'];
        if (isset($request['appoint_remark']) && !empty($request['appoint_remark'])) {
            $remark_data .= ' ' . $request['appoint_remark'];
        }
        $orre_res = orderRemark($user_info, $return_data['data']['wor_order_id'], $request['wor_id'], $remark_data, '工单列表-预约设置');

        if ($orlo_res && $orre_res /*&& $addUserMessage_res['code'] == 200 && $addAdminMessage_res['code'] == 200*/) {
            DB::commit();
            OperationLog::addLog($user_info, getRealIp($request), '工单列表', '预约设置', $return_data['data']['wor_number'] . '预约设置成功');
            return $this->success('预约成功');
        } else {
            DB::rollBack();
            return $this->error('预约失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 施工历史
    public function getConstructionHistory(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->qualityTestingValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }
        // 获取用户信息
        request()->offsetSet('type', 3);
        $user_info = LoginUserService::getUser();
        $return_data = WashWorkService::qualityTesting($user_info, $request->all());
        return response()->json($return_data);
    }

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

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

        DB::beginTransaction();
        // 取消工单
        $return_data = WashWorkService::withdraw($user_info, $request->all());
        if ($return_data['code'] != 200) {
            return $return_data;
        }
        // 生成操作记录
        $orlo_res = orderLog($user_info, $return_data['data']['wor_order_id'], $request['wor_id'], '撤回工单');
        if ($request['remark']) {
            // 添加备注
            $orre_res = orderRemark($user_info, 0, $request['wor_id'], $request['remark'], '撤回工单');
        } else {
            $orre_res = true;
        }
        if ($orlo_res && $orre_res) {
            DB::commit();
            OperationLog::addLog($user_info, getRealIp($request), '工单列表', '撤回工单', '撤回工单'.$return_data['data']['wor_order_number'].'成功');
            return $this->success('撤回工单成功');
        } else {
            DB::rollBack();
            return $this->error('撤回工单失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 导出
    public function export(Request $request)
    {
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_ids = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $search_data = $request->all();
        // 取消工单
        $return_data = WashWorkService::export($user_info, $request->all());
        return $return_data;
    }

    // 根据预约排班时间获取当日可以预约数量和已预约数量
    public function appoinTimeJudge(Request $request)
    {
        $user_info = LoginUserService::getUser();
        $return_data = WashWorkService::appoinTimeJudge($user_info, $request->all());
        return response()->json($return_data);
    }

    // 验车详情
    public function validateCar(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->infoValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }

        // 获取用户信息
        $user_info = LoginUserService::getUser();
        /*$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('work_order as w', 'ovc.orvc_ord_id', '=', 'w.wor_order_id')
            ->leftJoin('admin as a', 'ovc.orvc_adm_id', '=', 'a.adm_id')
            ->where('orvc_shop_id', $user_info->adm_shop_id)
            ->where('wor_id', $request['wor_id'])
            ->select('orvc_car_interior', 'orvc_mileage', 'orvc_car_exterior', 'orcl_check_car_state', 'orcl_signature_img', 'orvc_adm_id', 'adm_name', 'adm_phone', 'wor_order_id', 'orvc_update_time')
            ->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'] = '';
            $chsu_data = [];
        } else {
            $chsu_data = DB::table('checkcar_supplement as chsu')
                ->leftJoin('admin as a', 'a.adm_id', '=', 'chsu.chsu_adm_id')
                ->where('chsu_ord_id', $find_wash_order_validate_car->wor_order_id)
                ->select('chsu_id', 'chsu_img', 'chsu_explain', 'chsu_sign', 'adm_name', 'adm_phone', 'chsu_update_time')
                ->get()->toArray();
        }*/

        // 20230821
        $validate_data = WashWorkService::washValidateCarByWorId($request['wor_id']);

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

    /**
     * 是否展示图片给客户
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-07-25
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function userPicState(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->userPicStateValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM, $error_message);
        }

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

        // 是否展示图片给客户
        $return_data = WashWorkService::userPicState($user_info, $request->all());
        
        OperationLog::addLog($user_info, getRealIp($request), '工单列表', '同步图片', '同步图片给客户成功');
        return response()->json($return_data);
    }

    /**
     * 工单图片同步给客户总开关
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-07-25
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function listWorkPic(Request $request) {
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        if ($request['type'] == 1) {
            $find_state = DB::table('shop')
                ->where('shop_id', $user_info->adm_shop_id)
                ->value('shop_user_list_workpic');
            return response()->json(['code'=>200,'msg'=>'success','data'=>$find_state]);
        }
        $res = ShopService::listWorkPic($user_info,$request);
        return response()->json($res);
    }

    /**
     * 审核施工信息
     */
    public function auditWork(Request $request) {
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        if ($request['type'] == 1) {
            $find_work_remark = DB::table('completion_info')
                ->where('coin_wor_id', $request['wor_id'])
                ->where('coin_type', 4)
                // ->where('coin_must', 1)
                ->select('coin_wor_id', 'coin_type', 'coin_data')
                ->first();
            $find_com_img = DB::table('completion_info')
                ->where('coin_wor_id', $request['wor_id'])
                ->where('coin_type', 2)
                // ->where('coin_must', 1)
                ->select('coin_wor_id', 'coin_type', 'coin_data')
                ->get()->toArray();
            $data['work_image'] = $find_com_img;
            $data['work_remark'] = $find_work_remark ? $find_work_remark->coin_data:'无';
            return response()->json(['code'=>200,'msg'=>'success','data'=>$data]);
        }
        $res = WashWorkService::auditWork($user_info,$request);
        OperationLog::addLog($user_info, getRealIp($request), '工单列表', '施工审核', '施工审核成功');
        return response()->json($res);
    }

    /**
     * 批量审核施工信息
     */
    public function batchAuditWork(Request $request) {
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        $work_data = DB::table('work_order')
            ->whereIn('wor_id', $request['wor_id'])
            ->select('wor_state', 'wor_service_state', 'wor_number', 'wor_id')
            ->get();
        $wor_number = [];
        foreach ($work_data as $key => $value) {
            if ($value->wor_state != 8) {
                $wor_number[] = $value->wor_number;
            }
        }
        if (!empty($wor_number)) {
            $return_wor_number = implode(',', $wor_number);
            return response()->json(['code'=>500, 'msg'=>$return_wor_number.'不是待审核状态']);
        }
        foreach ($work_data as $key1=>$value1) {
            $post['state'] = 1;
            $post['wor_id'] = $value1->wor_id;
            $res = WashWorkService::auditWork($user_info,$post);
            OperationLog::addLog($user_info, getRealIp($request), '工单列表', '批量施工审核', '批量施工审核成功');
        }
        return response()->json(['code'=>200, 'msg'=>'审核成功', 'data'=>'审核成功']);
    }

    /**
     * 返工
     */
    public function returnWork(Request $request) {
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        $res = WashWorkService::returnWork($user_info,$request);
        return response()->json($res);
    }
}
