<?php
namespace app\api\controller;

use app\api\logic\VehicleLogic;
use app\common\model\vehicle\Vehicle;
use app\common\model\vehicle\VehicleRent;
use think\facade\Db;
use think\response\Json;

/**
 * 车辆管理
 * Class VehicleController
 * @package app\api\controller
 */
class VehicleController extends BaseApiController
{
    public array $notNeedLogin = ['getCarLocal','getCarHistory','addSelfCar','updateVehicleRent','cancelRent','delRentUseInfo','getFreeCars'];

    //获取车辆当前位置
    public function getCarLocal():Json {
        $params = $this->request->get(['car_id']);
        if(empty($params['car_id'])){
            return $this->fail('缺少必要参数');
        }
        $result = VehicleLogic::getCarLocal($params);
        //返回数据
        if($result['code'] == 1){
            return $this->success($result['msg'],$result['data']);
        }else{
            return $this->fail($result['msg']);
        }
    }

    public function getCarHistory():Json {
        //获取参数
        $params = $this->request->get(['car_id','start_time','end_time']);
        //验证参数
        if(empty($params['car_id']) || empty($params['start_time']) || empty($params['end_time'])){
            return $this->fail('缺少必要参数');
        }
        //验证时间格式
        if(!checkDateIsValid($params['start_time'],['Y-m-d H:i:s']) || !checkDateIsValid($params['end_time'],['Y-m-d H:i:s'])) {
            return $this->fail('日期格式错误');
        }
        //获取数据
        $result = VehicleLogic::getCarHistory($params);
        //返回数据
        if($result['code'] == 1){
            return $this->success($result['msg'],$result['data']);
        }else{
            return $this->fail($result['msg']);
        }
    }

    //添加自有车辆
    public function addSelfCar() {
        //获取参数
        $params = $this->request->post(['license','pic','company_id','company_name','company_user','company_phone']);
        if(empty($params['license']) || empty($params['pic']) || empty($params['company_id']) || empty($params['company_name']) || empty($params['company_user']) || empty($params['company_phone'])){
            return $this->fail('缺少必要参数');
        }
        Db::startTrans();
        try {
            //获取数据
            $vehicle = Vehicle::where('license',$params['license'])->find();
            if(!empty($vehicle)){
                return $this->fail('该车牌号的车辆已存在');
            }
            //写入数据
            $vehicle = Vehicle::create([
                'license' => $params['license'],
                'pic' => $params['pic'],
                'gps_imei' => '',
                'type' => 1,
                'status' => 2,
                'create_time' => time(),
                'update_time' => time(),
            ]);
            $vehicleRent = VehicleRent::create([
                'car_id'=> $vehicle->id,
                'contract_id' => 0,
                'company_id' => $params['company_id'],
                'company_name' => $params['company_name'],
                'company_user' => $params['company_user'],
                'company_phone' => $params['company_phone'],
                'create_time' => time(),
                'status' => 0,
                'use_user_id' => 0,
                'use_user_name' => '',
                'use_user_phone' => ''
            ]);
            if($vehicle->id && $vehicleRent->id){
                Db::commit();
                return $this->success('success',['car_id'=>$vehicle->id]);
            }else{
                Db::rollback();
                return $this->fail('error');
            }
        }catch (\Exception $e) {
            Db::rollback();
            return $this->fail($e->getMessage());
        }

    }

    public function updateVehicleRent(){
        //获取参数
        $params = $this->request->post(['car_id','use_user_id','use_user_name','use_user_phone']);
        if(empty($params['car_id']) || empty($params['use_user_id']) || empty($params['use_user_name']) || empty($params['use_user_phone'])){
            return $this->fail('参数错误');
        }
        //更新
        $vehicleRent = VehicleRent::where('car_id',$params['car_id'])->find();
        if(empty($vehicleRent)){
            return $this->fail('数据错误');
        }
        $result = VehicleRent::where('car_id',$params['car_id'])->update([
            'use_user_id' => $params['use_user_id'],
            'use_user_name' => $params['use_user_name'],
            'use_user_phone' => $params['use_user_phone'],
        ]);
        if($result){
            return $this->success('请求成功');
        }else{
            return $this->fail('失败');
        }
    }

    public function cancelRent(): Json
    {
        //获取参数
        $carIds = $this->request->post('car_ids');
        if(empty($carIds)){
            return $this->fail('参数错误');
        }
        Db::startTrans();
        try {
            //删除租赁信息
            VehicleRent::where('car_id','in',$carIds)->delete();
            //重置车辆状态
            $vehicles = Vehicle::field('id,type')->where('id','in',$carIds)->select();
            foreach ($vehicles as $v) {
                if($v['type'] == 1){
                    Vehicle::where('id',$v['id'])->delete();
                }else{
                    Vehicle::where('id',$v['id'])->update(['status'=>0]);
                }
            }
            Db::commit();
            return $this->success('请求成功');
        }catch (\Exception $e) {
            Db::rollback();
            return $this->fail($e->getMessage());
        }
    }

    public function delRentUseInfo() {
        if(!$this->request->isPost()){
            return $this->fail('请求方式错误');
        }
        $carId = $this->request->post('car_id');
        if(empty($carId)){
            return $this->fail('参数错误');
        }
        //获取车辆信息
        $carInfo = Vehicle::where('id',$carId)->findOrEmpty();
        if($carInfo->isEmpty()){
            return $this->fail('数据不存在');
        }
        if($carInfo['type'] == 0){
            //修改租赁信息
            VehicleRent::where('car_id',$carId)->update(['use_user_id'=>0,'use_user_name'=>'','use_user_phone'=>'']);
        }
        if($carInfo['type'] == 1){
            VehicleRent::where('car_id',$carId)->delete();
            Vehicle::where('id',$carInfo['id'])->delete();
        }
        return $this->success('修改成功');
    }

    //获取空闲车辆
    public function getFreeCars(): Json
    {
        if(!$this->request->isPost()){
            return $this->fail('请求方式错误');
        }
        $ids = $this->request->post('ids');
        if(!empty($ids)){
            $rentCars = Vehicle::field('id,pic,license')->where('id','in',$ids)->select()->toArray();
        }else{
            $rentCars = [];
        }
        $data = Vehicle::field('id,pic,license')->where('status',0)->where('type',0)->select()->toArray();
        return $this->success('请求成功',array_merge($rentCars,$data));
    }
}