<?php

namespace App\Services\Business;

use Illuminate\Support\Facades\Request;
use Illuminate\Database\Eloquent\Model;
use App\Models\Business\WashWork;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Models\Common;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Validators\Business\WashWorkValidator;
use BlueCity\Core\Inc\ErrorInc;
use App\Http\Models\Services\OrderManage\WorkOrders;
use App\Http\Models\Api\CashierDesk;
use App\Http\Models\Api\Export;
use App\Http\Enum\Business\WorkOrderEnum;

// 工单
class WashWorkBasicService extends Service
{
    public static $instance;
    public $modelMain = null;
    public $mainValidator = null;

    public function __construct()
    {
        $this->modelMain = new WashWork();
        $this->mainValidator = new WashWorkValidator();
    }

    /**
     * @return mixed
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }

    // 提交施工
    public static function submitConstruction($user_info, $request)
    {
        // 查询当前工单的商品是否发货，没有发货的不能开始施工
        $dispatch_bill = DB::table('dispatch_bill')
            ->where('dego_wor_id', $request['wor_id'])
            ->where('dego_order_type', 2)
            ->where('dego_type', 1)
            ->first();
        if (!empty($dispatch_bill)) {
            return ['code'=>500, 'msg'=>'请取货后再开始施工！', 'data'=>'请取货后再开始施工！'];
        }
        $find_work = DB::table('work_order as wor')
            ->where('wor_id', $request['wor_id'])
            ->where('wor_shop_id', $user_info->adm_shop_id)
            ->select('wor_number', 'wor_state', 'wor_work_type', 'wor_order_id', 'wor_order_number', 'wor_service_adm_id', 'wor_appoint_time', 'wor_create_time')
            ->first();
        if (empty($find_work)) {
            return ['code'=>ErrorInc::DATA_EMPTY, 'msg'=>'当前工单不存在', 'data'=>''];
        }
        if ($find_work->wor_state != 7) {
            return ['code'=>ErrorInc::DATA_EMPTY, 'msg'=>'当前工单不是待施工状态', 'data'=>''];
        }
        
        $add_data['woch_shop_id'] = $user_info->adm_shop_id;
        $add_data['woch_adm_id'] = $user_info->adm_id;
        $add_data['woch_wor_id'] = $request['wor_id'];
        $add_data['woch_part_data'] = $request['woch_part_data'];//施工数据
        $add_data['woch_check_res'] = 2;//质检结果1提交/未质检2通过3返工
        $update_data['wotp_submit_state'] = 2;//提交状态:0未提交1提交待审核2通过3返工
        // if ($find_work->wor_service_adm_id == $user_info->adm_id) {//判断是否是组长
        // } else {
        //     $add_data['woch_check_res'] = 1;//质检结果1提交/未质检2通过3返工
        //     $update_data['wotp_submit_state'] = 1;//提交状态:0未提交1提交待审核2返工3通过
        // }
        $add_data['woch_create_time'] = date('Y-m-d H:i:s');
        if ($find_work->wor_service_adm_id == $user_info->adm_id) {
            // 组长修改施工信息不用添加施工历史
            $add_data_res = true;
        } else {
            $add_data_res = DB::table('wash_work_check_history')->insertGetId($add_data);
        }
        $update_data['wotp_service_data'] = $request['woch_part_data'];//施工数据
        $update_data['wotp_update_time'] = date('Y-m-d H:i:s');
        $update_res = DB::table('wash_work_technician_part')
            ->where('wotp_shop_id', $user_info->adm_shop_id)
            ->where('wotp_wor_id', $request['wor_id'])
            ->where('wotp_service_adm_id', $user_info->adm_id)
            ->update($update_data);
        // 智配贴装的订单状态改为已完成，不用评价
        if ($find_work->wor_work_type == 2) {
            $ord_edit_data['ord_wor_state'] = 20;
        } else {
            $ord_edit_data['ord_wor_state'] = 4;
        }
        $ord_edit_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_edit_res = DB::table('order')
            ->where('ord_id', $find_work->wor_order_id)
            ->update($ord_edit_data);

        $wor_edit_data['wor_service_state'] = 8;
        $wor_edit_data['wor_state'] = 10;
        $wor_edit_data['wor_update_time'] = date('Y-m-d H:i:s');
        $wor_edit_res = WashWork::where('wor_id', $request['wor_id'])->update($wor_edit_data);

        // 同步智配贴装提交信息
        if ($find_work->wor_work_type == 2) {
            $find_service_adm = DB::table('admin')
                ->where('adm_id', $find_work->wor_service_adm_id)
                ->select('adm_name', 'adm_phone')
                ->first();
            $order_data = DB::table('order')
                ->where('ord_id', $find_work->wor_order_id)
                ->select('ord_other_system_number')
                ->first();
            $wotp_service_data = json_decode($request['woch_part_data'], true);
            
            $server = config('apisystem.server_name') . '/';
            $find_image_upload = [];
            $image_key = 0;
            foreach ($wotp_service_data as $key => $value) {
                if ($value['pic']) {
                    foreach ($value['pic'] as $pic_key => $pic_value) {
                        $find_image_upload[$image_key]['imup_path'] = $server . $pic_value;
                        $find_image_upload[$image_key]['imup_image_name'] = $value['wotp_service_part'];
                        $image_key++;
                    }
                }
            }
            $url = config('apiconnect.ZPTZ_URL') . '/index.php/api/supplychain/SupplyMz/installLine';
            $param['state'] = 5;
            $param['time'] = date('Y-m-d H:i:s');
            $param['ip'] = Request::getClientIp();
            $param['filePic'] = $find_image_upload; //图片
            $param['token'] = md5(md5($param['time'] . config('apiconnect.ZPTZ_TOKEN'))); //token
            $param['serial_number'] = $order_data->ord_other_system_number; //第三方工单号
            $param['install_name'] = $find_service_adm->adm_name;
            $param['install_phone'] = $find_service_adm->adm_phone;
            $param['app_achieve_time'] = date('Y-m-d H:i:s'); //完成提交时间
            $param_return = doPost($param, $url, 2);
            $param_return = json_decode($param_return, true);
            if ($param_return['code'] != 200) {
                return ['code'=>500, 'msg'=>'完成提交同步失败', 'data'=>''];
            }
        }

        if ($ord_edit_res && $wor_edit_res && $update_res) {
            // $return_data['wor_number'] = $find_work->wor_number; //工单单号
            // $return_data['wocl_car_num'] = $find_work->wocl_car_num; //工单单号
            // 工单的历史记录
            $data['wohi_primary_id'] = $request['wor_id'];
            $data['wohi_state_name'] = '已完成';
            $data['wohi_state'] = 5;//服务状态：5已完成
            $data['wohi_type'] = 2;//1订单2工单
            addHistory($data);
            unset($data);
            return ['code'=>200, 'msg'=>'提交施工成功', 'data'=>''];
        } else {
            return ['code'=>500, 'msg'=>'提交施工失败', 'data'=>''];
        }
    }

    // 取消工单
    public static function cancel($user_info, $request)
    {
        // 查询信息
        $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_state', 'wor_order_id', 'wor_goo_amount', 'wor_type', 'wor_actual_price', 'wor_ware_id', 'wor_remark', 'wor_pass', 'wor_service_type', 'wor_type', 'wocl_client_id', 'wocl_sd_virtual_type', 'wocl_wor_type', 'wor_order_number', 'wor_delete')
            ->first();

        if (empty($find_work)) {
            return ['code'=>ErrorInc::REQUEST_INAPTNESS, 'msg'=>'当前工单不存在，无法取消工单！', 'data'=>''];
        }
        if (!in_array($find_work->wor_state, [1, 2, 3, 7])) {
            return ['code'=>ErrorInc::REQUEST_INAPTNESS, 'msg'=>'当前工单不是施工中状态，无法取消工单！', 'data'=>''];
        }
        if ($find_work->wor_pass == 4) {
            return ['code'=>ErrorInc::REQUEST_INAPTNESS, 'msg'=>'当前工单已经锁定，无法取消工单！', 'data'=>''];
        }
        if ($find_work->wor_delete != 1) {
            return ['code'=>ErrorInc::REQUEST_INAPTNESS, 'msg'=>'当前工单已经取消！', 'data'=>''];
        }

        $work_order = new WorkOrders();
        $return_data = $work_order->deletes($user_info, $request, $find_work);
        if ($return_data['code'] == 200) {
            $data['wor_order_id'] = $find_work->wor_order_id;
            $data['wor_order_number'] = $find_work->wor_order_number;
            return ['code'=>200, 'msg'=>'取消工单成功', 'data'=>$data];
        } else {
            return $return_data;
        }
    }
}
