<?php

namespace app\api\controller;

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

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

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

    /**
     * 列表
     * @return void
     */
    public function getList(){
        try {
            $preOrderStatus = input('pre_order_status','');

            $po = 'pre_order';
            $st = 'servicetype';
            $o  = 'order';
            $where[$po.'.user_id'] = $this->auth->id;
            if ($preOrderStatus != '') {
                $where[$po.'.pre_order_status'] = $preOrderStatus;
            }
            $field = $po.'.id,name,mobile,address,remark,'.$po.'.car_id,'.$po.'.car_number,pre_time,order_time,'.$po.'.cancel_time,'.
                $po.'.cancel_reason,'.$st.'.title,pre_order_status,'.$o.'.id as `order_id`,'.$o.'.server_time';
            $result = $this->model->alias($po)->field($field)
                ->join($st,$st.'.id = '.$po.'.servicetype_id','LEFT')
                ->join($o,$o.'.pre_order_id = '.$po.'.id','LEFT')
                ->where($where)->order($po.'.createtime desc')->autopage()->select();
            if (!empty($result)) {
                $model = model('PreOrder');
                $statusArr = $model->getPreOrderStatusList();
                $timeArr = ['pre_time','order_time','cancel_time','server_time'];
                foreach ($result as $key => &$value) {
                    foreach ($timeArr as $k => $v) {
                        $value[$v] = !empty($value[$v]) ? date('Y年m月d日 H:i:s', $value[$v]) : '';
                    }
                    $value['order_id'] = empty($value['order_id']) ? 0 : $value['order_id'];
                    $value['pre_order_status_text'] = isset($statusArr[$value['pre_order_status']]) ? $statusArr[$value['pre_order_status']] : '';
                }
            }

            $this->success('获取成功', $result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 保存
     * @return void
     */
    public function save()
    {
        try {
            //验证参数
            $id = $this->request->param('id',0);
            $carId = $this->request->param('car_id',0);
            $preTime = $this->request->param('pre_time','');
            $userId = $this->auth->id;
            $companyId = $this->auth->company_id;
            $scene = !empty($id) ? 'edit' : 'add';
            $validate = validate('PreOrder');
            if(!$validate->check($this->request->param(),[],$scene)){
                throw new Exception($validate->getError());
            }
            $preTime = strtotime($preTime);
            //获取车辆信息
            $userCarWhere['user_id'] = $userId;
            $userCarWhere['id'] = $carId;
            $userCar = Db::name('user_car')->where($userCarWhere)->find();
            if (empty($userCar)) {
                throw new Exception('未找到车辆信息');
            }
            $time = time();
            $data = [
                'name'           => $this->request->param('name', ''),
                'mobile'         => $this->request->param('mobile', ''),
                'address'         => $this->request->param('address', ''),
                'remark'         => $this->request->param('remark', ''),
                'car_id'         => $carId,
                'car_number'     => isset($userCar['car_number']) ? $userCar['car_number'] : '',
                'servicetype_id' => $this->request->param('servicetype_id', 0),
                'pre_time'       => $preTime,
            ];
            if (empty($id)) {
                $data['company_id'] = $companyId;
                $data['pre_order_no'] = createUniqueNo('PO',$userId);
                $data['user_id'] = $userId;
                $data['createtime'] = $time;
                $res = $this->model->insertGetId($data);
                $id = $res;
            } else {
                $data['updatetime'] = $time;
                $where['id'] = $id;
                $where['user_id'] = $userId;
                $res = $this->model->where($where)->update($data);
            }
            if (!$res) {
                throw new Exception('操作失败');
            }
            $result = [
                'pre_order_id' => $id,
                'template_ids' => config('param.wechat_template_ids'),//微信消息模版ID
            ];
            $this->success('操作成功',$result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 微信消息通知
     * @return void
     */
    public function wxMessage()
    {
        try {
            $preOrderId = $this->request->param('pre_order_id',0);
            $userService = new UserService();
            $params = ['pre_order_id' => $preOrderId];
            $wechatMsgRes = $userService->wechatMessageSend($params);
            if (!$wechatMsgRes['status']) {
                throw new Exception($wechatMsgRes['msg']);
            }
            $this->success('操作成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 详情
     * @return void
     */
    public function getInfo()
    {
        try {
            $id = $this->request->param('id',0);
            $po = 'pre_order';
            $st = 'servicetype';
            $o  = 'order';
            $where[$po.'.user_id'] = $this->auth->id;
            $where[$po.'.id'] = $id;
            $field = $po.'.id,name,mobile,address,remark,'.$po.'.car_id,'.$po.'.car_number,pre_time,order_time,'.
                $po.'.cancel_time,'.$po.'.cancel_reason,'.$po.'.createtime,'.$po.'.servicetype_id,'.$st.
                '.title as `servicetype_title`,pre_order_status,'.$o.'.id as `order_id`';
            $result = $this->model->alias($po)->field($field)
                ->join($st,$st.'.id = '.$po.'.servicetype_id','LEFT')
                ->join($o,$o.'.pre_order_id = '.$po.'.id','LEFT')
                ->where($where)->order($po.'.createtime desc')->find();
            if (!empty($result)) {
                $model = model('PreOrder');
                $statusArr = $model->getPreOrderStatusList();
                $timeArr = ['pre_time','order_time','cancel_time','createtime'];
                foreach ($timeArr as $k => $v) {
                    $result[$v] = !empty($result[$v]) ? date('Y年m月d日 H:i:s', $result[$v]) : '';
                }
                $result['order_id'] = empty($result['order_id']) ? 0 : $result['order_id'];
                $result['pre_order_status_text'] = isset($statusArr[$result['pre_order_status']]) ? $statusArr[$result['pre_order_status']] : '';
            }
            $this->success('获取成功',$result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 取消
     * @return void
     */
    public function cancel()
    {
        try {
            $id = $this->request->param('id',0);
            $cancelReason = $this->request->param('cancel_reason','');
            $time = time();
            $where['user_id'] = $this->auth->id;
            $where['id'] = $id;
            $modelData = model('PreOrder')->where($where)->find();
            if (empty($modelData)) {
                throw new Exception('未找到预约信息');
            }
            if ($modelData['pre_order_status'] != 1) {
                throw new Exception('该预约单无法取消或已取消');
            }
            $modelData->pre_order_status = 0;
            $modelData->cancel_reason = $cancelReason;
            $modelData->cancel_time = $time;
            $res = $modelData->save();
            if (!$res) {
                throw new Exception('操作失败');
            }
            $this->success('操作成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
}