<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\service\OrderService;
use think\Db;
use think\Exception;

class UserCar extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = Db::name('user_car');
    }

    /**
     * 车辆列表
     * @return void
     */
    public function getList()
    {
        try {
            $userId = $this->auth->id;
            $companyId = $this->auth->company_id;
            $field = 'id,car_number,car_model';
            $where['user_id'] = $userId;
            $result = $this->model->field($field)->where($where)->order('createtime desc')->autopage()->select();
            if (!empty($result)) {
                $ids = array_column($result,'id');
                $carNos = array_column($result,'car_number');
                $params = [
                    'user_id' => $userId,
                    'company_id' => $companyId,
                    'car_id' => $ids,
                    'car_number' => $carNos,
                ];
                $orderService = new OrderService();
                $orderRes = $orderService->getCarNextDate($params);
                foreach ($result as $key => &$value) {
                    $value['next_date'] = isset($orderRes['data'][$value['car_number']]) ? $orderRes['data'][$value['car_number']]['next_date'] : '';
                }
            }
            $this->success('获取成功',$result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 车辆详情
     * @return void
     */
    public function getInfo()
    {
        try {
            $id = $this->request->param('id',0);
            $userId = $this->auth->id;
            $companyId = $this->auth->company_id;
            $field = 'id,car_number,car_model';
            $where['user_id'] = $userId;
            $where['id'] = $id;
            $result = $this->model->field($field)->where($where)->find();
            if (!empty($result)) {
                $params = [
                    'user_id' => $userId,
                    'company_id' => $companyId,
                    'car_id' => [$id],
                ];
                $orderService = new OrderService();
                $orderRes = $orderService->getCarNextDate($params);
                $result['next_date'] = isset($orderRes['data'][$result['car_number']]) ? $orderRes['data'][$result['car_number']]['next_date'] : '';
            }
            $this->success('获取成功',$result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
    
    /**
     * 保存
     * @return void
     */
    public function save()
    {
        try {
            //验证参数
            $id = $this->request->param('id',0);
            $userId = $this->auth->id;
            $scene = !empty($id) ? 'edit' : 'add';
            $validate = validate('UserCar');
            if(!$validate->check($this->request->param(),[],$scene)){
                throw new Exception($validate->getError());
            }
            $time = time();
            $data = [
                'car_number' => $this->request->param('car_number', ''),
                'car_model'  => $this->request->param('car_model', ''),
            ];
            if (empty($id)) {
                $data['user_id'] = $userId;
                $data['createtime'] = $time;
                $res = $this->model->insertGetId($data);
            } else {
                $data['updatetime'] = $time;
                $where['id'] = $id;
                $where['user_id'] = $userId;
                $res = $this->model->where($where)->update($data);
            }
            if (!$res) {
                throw new Exception('操作失败');
            }
            $this->success('操作成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 删除
     * @return void
     */
    public function del()
    {
        try {
            //验证参数
            $id = $this->request->param('id',0);
            $userId = $this->auth->id;
            $where['id'] = $id;
            $where['user_id'] = $userId;
            $userCar = $this->model->where($where)->find();
            if (empty($userCar)) {
                throw new Exception('未找到车辆信息');
            }
            $res = $this->model->where($where)->delete();
            if (!$res) {
                throw new Exception('操作失败');
            }
            $this->success('操作成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
}