<?php

namespace app\adminapi\controller\contract;

use app\adminapi\controller\BaseAdminController;
use app\api\controller\JunziqianController;
use app\common\enum\notice\NoticeEnum;
use app\common\model\contract\VehicleContract;
use app\common\model\vehicle\VehicleRent;

class VehicleContractController extends BaseAdminController
{
    //风控中心上传合同
    public function uploadContract() {
        //获取参数
        $params = $this->request->post(['id','file','cars']);
        if(empty($params['id']) || empty($params['file'])){
            return $this->fail('缺少必要参数');
        }
        //获取合同信息
        $vehicle_contract = VehicleContract::where('id',$params['id'])->findOrEmpty();
        if($vehicle_contract->isEmpty()){
            return $this->fail('合同信息错误');
        }
        if($vehicle_contract['type']==0 && $vehicle_contract['contract_logistic_id'] != 0){
            if(empty($params['cars'])){
                return $this->fail('缺少必要参数cars');
            }
            $cars = json_decode($params['cars'],true);
            if(empty($cars)){
                return $this->fail('参数cars无效');
            }
        }
        if($vehicle_contract['status'] != 0){
            return $this->fail('合同状态错误');
        }
        //更新本地
        try {
            $data = [
                'id' => $vehicle_contract['contract_logistic_id'],
                'file' => $params['file'],
                'status' => 1,
	            'update_time' => time()
            ];
            //判断合同类型
            if($vehicle_contract['type'] == 0 && $vehicle_contract['contract_logistic_id'] != 0){
                $data['cars_info'] = $params['cars'];
            }
            if(!empty($vehicle_contract['contract_logistic_id'])){
                //更新物流系统
                curl_post(env('project.logistic_domain').'/api/contractUpdate',[],$data);
            }
            unset($data['id']);
            VehicleContract::where('id', $params['id'])->update($data);

        }catch (\Exception $e){
            return $this->fail($e->getMessage());
        }
        return $this->success('上传成功', [], 1, 1);
    }

    //发送通知短信
    public function rentNoticeSms($params) {
        try {
            $scene = NoticeEnum::getSceneByTag($params['scene']);
            if (empty($scene)) {
                throw new \Exception('场景值异常');
            }
            $result = event('Notice',  [
                'scene_id' => $scene,
                'params' => $params
            ]);
            return $result[0];
        } catch (\Exception $e) {
            return false;
        }
    }

    public function lists() {
        $param = $this->request->get();
        $where = [];
        if(isset($param['company_name'])){
            $where[] = ['company_b_name','like','%'.$param['company_name'].'%'];
        }
        if(isset($param['contract_no'])){
            $where[] = ['contract_no','like','%'.$param['contract_no'].'%'];
        }
        if(isset($param['status']) && in_array($param['status'],[0,1])){
            if($param['status'] == 1){
                $where[] = ['status','in', '1,2,3'];
            }else{
                $where[] = ['status','=', $param['status']];
            }
        }else{
            $where[] = ['status','in', '0,1,2,3'];
        }
        $pageNo = !empty($param['page_no']) ? $param['page_no'] : 1;
        $pageSize = !empty($param['page_size']) ? $param['page_size'] : 15;
        $data = VehicleContract::where($where)
            ->page($pageNo, $pageSize)
            ->order('create_time desc')
            ->select()->each(function($item){
                $item['cars_info'] = json_decode($item['cars_info'],true);
            });
        return $this->success('success',['lists'=>$data->toArray(),'page_no'=>$pageNo,'page_size'=>$pageSize,'count'=>$data->count()]);
    }

    public function townRentList() {
        $param = $this->request->get();
        $where = [];
        if(isset($param['company_name'])){
            $where[] = ['company_b_name','like','%'.$param['company_name'].'%'];
        }
        if(isset($param['contract_no'])){
            $where[] = ['contract_no','like','%'.$param['contract_no'].'%'];
        }
        if(isset($param['status']) && in_array($param['status'],[0,1])){
            if($param['status'] == 1){
                $where[] = ['status','in', '1,2,3'];
            }else{
                $where[] = ['status','=', $param['status']];
            }
        }else{
            $where[] = ['status','in', '0,1,2,3'];
        }
        $pageNo = !empty($param['page_no']) ? $param['page_no'] : 1;
        $pageSize = !empty($param['page_size']) ? $param['page_size'] : 15;
        $data = VehicleContract::where($where)->where('contract_logistic_id','<>',0)
            ->page($pageNo, $pageSize)
            ->order('create_time desc')
            ->select()->each(function($item){
                $item['cars_info'] = json_decode($item['cars_info'],true);
            });
        return $this->success('success',['lists'=>$data->toArray(),'page_no'=>$pageNo,'page_size'=>$pageSize,'count'=>$data->count()]);
    }

    public function initiatingRentCarContract() {
        //获取参数
        $params = $this->request->post(['id']);
        if(empty($params['id'])){
            return $this->fail('缺少必要参数');
        }
        //获取数据
        $contract = VehicleContract::where('id',$params['id'])->findOrEmpty();
        if($contract->isEmpty()){
            return $this->fail('数据不存在');
        }
        if(!($contract['status'] == 1 || ($contract['status'] == 2 && $contract['signing_timer'] != 2))){
            return $this->fail('合同状态错误');
        }
        $signData = [
            'name' => $contract['company_a_name'] . '的合同',
            'signatories' => [
                ['fullName' => $contract['company_a_name'], 'identityType' => 12, 'identityCard' => $contract['company_a_code'], 'email' => $contract['company_a_email'], 'noNeedVerify' => 1, 'signLevel' => 1],
                ['fullName' => $contract['company_b_name'], 'identityType' => 12, 'identityCard' => $contract['company_b_code'], 'email' => $contract['company_b_email'], 'noNeedVerify' => 1, 'signLevel' => 1]
            ],
            'url' => $contract['file']
        ];
        $notify_url = '';
        if($contract['type'] == 0){
            $smsTitle = '《租赁合同》';
            if(empty($contract['contract_logistic_id'])){
                $notify_url = env('project.website_domain').'/api/index/systemCarRent';
            }else{
                $notify_url = env('project.website_domain').'/api/index/townCarRent';
            }
        }elseif($contract['type'] == 1){
            $smsTitle = '《自有车辆上传合同》';
            $notify_url = env('project.website_domain').'/api/index/selfCarRent';
        }elseif($contract['type'] == 2){
            $smsTitle = '《解约合同》';
            $notify_url = env('project.website_domain').'/api/index/cancelRent';
        }elseif($contract['type'] == 3){
            $smsTitle = '《购买合同》';
            $notify_url = env('project.website_domain').'/api/index/buyCar';
        }
        $signRes = app(JunziqianController::class)->VehicleRentSigning($signData, $params['id'],$notify_url);
        if ($signRes->success) {
            $contract->save([
                'id' => $contract['id'],
                'contract_no' => $signRes->data,
                'status' => 2,
	            'signing_timer' => 0
            ]);
            if(!empty($contract['contract_logistic_id'])){
                curl_post(env('project.logistic_domain').'/api/contractUpdate',[],[
                    'id' => $contract['contract_logistic_id'],
                    'contract_no' => $signRes->data,
                    'status' => 2,
	                'signing_timer' => 0,
	                'update_time' => time()
                ]);
            }
            $this->sendSms($params['id'],$smsTitle);
            return $this->success('合同发送成功');
        } else {
            return $this->fail($signRes->msg);
        }
    }

    public function sendSms($id,$title) {
        //获取合同数据
        $contract = VehicleContract::where('id',$id)->findOrEmpty();
        if (!$contract->isEmpty() && $contract['file'] != '') {
            //发送短信
            $data = [
                //甲方
                [
                    "applyNo" => $contract['contract_no'],
                    "fullName" => $contract['company_a_name'],
                    "identityCard" => $contract['company_a_code'],
                    "identityType" => 12,
                    "master_phone" => $contract['company_a_phone'],
                    "type"=>"party_a"
                ],
                //乙方
                [
                    "applyNo" => $contract['contract_no'],
                    "fullName" => $contract['company_b_name'],
                    "identityCard" => $contract['company_b_code'],
                    "identityType" => 12,
                    "master_phone" => $contract['company_b_phone'],
                    "type"=>"party_b"

                ],
            ];

            $url = [];
            foreach ($data as $v) {
                $res = app(JunziqianController::class)->SigningLink($v);
                if (!$res->success) {
                    return false;
                }
                if ($v['type'] == 'party_a') {
                    $url['party_a'] =$res->data;
                } else {
                    $url['party_b'] =$res->data;
                }
                //发送短信
                $sms = [
                    'mobile' => $v['master_phone'],
                    'name' => $v['fullName'],
                    'type' => $title,
                    'code' => 'api/Hetong/info?id='.$id.'&type='.$v['type'],
                    'scene' => 'WQ'
                ];
                $scene = NoticeEnum::getSceneByTag($sms['scene']);
                if (empty($scene)) {
                    throw new \Exception('场景值异常');
                }
                event('Notice',  [
                    'scene_id' => $scene,
                    'params' => $sms
                ]);
            }
            VehicleContract::where('id', $id)->update(['url' => json_encode($url)]);
            return true;
        }else{
            return false;
        }
    }

    public function detail() {
        $id = $this->request->get('id');
        if(empty($id)){
            $this->fail('参数错误');
        }
        $data = VehicleContract::where('id',$id)->findOrEmpty();
        if($data->isEmpty()){
            return $this->fail('未查找到数据');
        }
        $cars = json_decode($data['cars_info'],true);
        //判断合同类型
        if(!empty($data['contract_logistic_id']) && $data['type'] == 0){
            $carList = curl_get(env('project.logistic_domain').'/api/getAvailableVehicles');
            $data['car_list'] = $carList&&$carList['code']==1 ? $carList['data'] : [];
        }
        if(!empty($cars)){
            foreach ($cars as $k=>$v) {
                if($data['type'] == 0){
                    $cars[$k]['type'] = 0;
                }
                if($data['type'] == 1){
					if(empty($v['id'])){
						$cars[$k]['type'] = 1;
					}else{
						$rentInfo = VehicleRent::where('car_id',$v['id'])->findOrEmpty();
						if($rentInfo->isEmpty()){
							$cars[$k]['type'] = 0;
						}else{
							$cars[$k]['type'] = $rentInfo['type'];
						}
					}
                }
                if($data['type'] == 2){
                    $rentInfo = VehicleRent::where('car_id',$v['id'])->findOrEmpty();
                    if($rentInfo->isEmpty()){
                        $cars[$k]['type'] = 0;
                    }else{
                        $cars[$k]['type'] = $rentInfo['type'];
                    }
                }
                if($data['type'] == 3){
                    $rentInfo = VehicleRent::where('car_id',$v['id'])->findOrEmpty();
                    if($rentInfo->isEmpty()){
                        $cars[$k]['type'] = 2;
                    }else{
                        $cars[$k]['type'] = $rentInfo['type'];
                    }
                }
                $cars[$k]['rent_time'] = $data['update_time'];
            }
        }
        $data['cars_info'] = $cars;
        return $this->success('success',$data->toArray());
    }
}