<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2019/12/5
 * Time: 17:44
 */

namespace app\api\controller;


use app\api\controller\base\Permissions;
use app\common\model\AppointmentApplication;
use app\common\model\AppointmentTicket;
use app\common\model\Feedback;
use app\common\model\Webconfig;

class User extends Permissions
{
    //个人资料
    public function info()
    {
        $user = $this->getUser();
        $info = [
            "nickname" => $user->nickname,
            "head_pic" => $user->head_pic,
            "sex" => $user->sex,
            "country" => $user->country,
            "province" => $user->province,
            "city" => $user->city
        ];
        $this->json_success('success', $info);
    }

    //预约申请
    public function application()
    {
        $post = $this->request->param();
        $validate = new \think\Validate([
            ['name|姓名', 'require|max:50'],
            ['age|年龄', 'number'],
            ['birthday|出生年月', 'max:50'],
            ['sex|性别', 'number|in:1,2'],
            ['phone|电话', 'require|max:50'],
            ['id_card|身份证', 'max:50'],
            ['problem_desc|问题描述', 'max:200'],
            ['requirement_desc|需求描述', 'max:200'],
            ['appointment_ticket_id', 'require|number'],
            ['appointment_period', 'require|number|in:1,2,3'],
            ['appointment_time|预约时间段', 'require|dateFormat:H:i - H:i'],
            ['city|来自城市', 'max:50'],
            ['job|职业', 'max:50'],
            ['education_level|受教育程度', 'number|in:0,1,2,3,4'],
            ['home_address|家庭住址', 'max:255'],
            ['marriage|婚姻情况', 'number|in:0,1,2'],
            ['problem_type|咨询问题类别', 'number|in:0,1,2,3,4,5'],
            ['childs_num_str|子女数量', 'max:255'],
        ]);
        if (!$validate->check($post)) {
            $this->json_error('提交失败：' . $validate->getError());
        }

        $model = new AppointmentApplication();

        //爽约多少次后，多少天内不能再预约
        $break_the_promise_day_range = Webconfig::getValue('break_the_promise_day_range');
        $break_the_promise_times = Webconfig::getValue('break_the_promise_times');
        $stop_appointment_day = Webconfig::getValue('stop_appointment_day');
        //
        if ($stop_appointment_day && $break_the_promise_times && $break_the_promise_day_range) {
            $break_the_promise_count = $model->where('status', AppointmentApplication::STATUS_NOT_COME)->whereTime('finish_time', "-$break_the_promise_day_range day")->count();
            if ($break_the_promise_count >= $break_the_promise_times) {
                $maxtime = $model->where('status', AppointmentApplication::STATUS_NOT_COME)->max('finish_time');
                if (time() < ($maxtime + $stop_appointment_day * 3600 * 24)) {
                    $this->json_error("此账号 $break_the_promise_day_range 天内爽约 $break_the_promise_count 次, $stop_appointment_day 天内不能再预约");
                }
            }
        }

        //检测预约号源是否可预约
        $ticket = (new AppointmentTicket())->where(['id' => $post['appointment_ticket_id'], 'status' => AppointmentTicket::STATUS_OPEN])->find();
        if (!$ticket) {
            $this->json_error("获取预约号失败");
        }

        $appoint = $ticket->appointment;
        //判断该时间段，存在于时间列表中才行
        if ($post['appointment_period'] == 1) {
            $timePeriods = $appoint->morning_time_periods;
        } elseif ($post['appointment_period'] == 2) {
            $timePeriods = $appoint->afternoon_time_periods;
        } else {
            $timePeriods = [];//晚上没有
        }

        if (!in_array($post['appointment_time'], $timePeriods)) {
            $this->json_error("该时间段不存在,请重新选择时间");
        }

        //排除过期时段
        $timerang = explode(' - ', $post['appointment_time']);
        $period_start = $timerang[0];
        $period_end = $timerang[1];

        if (time() > strtotime($ticket->appointment_daytime . ' ' . $period_end)) {
            $this->json_error("该时段已经过期,请重新选择时间");
        }

        //临近几小时不可预约
        $appointment_time_limit = Webconfig::getValue('appointment_time_limit');
        if ($appointment_time_limit > 0) {
            if (time() > strtotime($ticket->appointment_daytime . ' ' . $period_start) - $appointment_time_limit * 3600) {
                $this->json_error("临近{$appointment_time_limit}小时内不可预约,请重新选择时间");
            }
        }

        //已经预约的时间段
        $ticketPeriods = (new AppointmentApplication())->where('appointment_ticket_id', $ticket->id)->where('finish_time', 0)->column('appointment_time');
        foreach ($ticketPeriods as $period) {
            if ($period == $post['appointment_time']) {
                $this->json_error("该时段已被预约,请重新选择时间");
            }
        }

        //入库
        $data = [
            'name' => htmlspecialchars($post['name']),
            'user_id' => $this->getUserId(),
            'age' => $post['age']??0,
            'birthday' => $this->request->param('birthday', '', 'htmlspecialchars'),
            'sex' => $post['sex']??0,
            'phone' => $post['phone'],
            'id_card' => $this->request->param('id_card', '', 'htmlspecialchars'),
            'problem_desc' => $this->request->param('problem_desc', '', 'htmlspecialchars'),
            'requirement_desc' => $this->request->param('requirement_desc', '', 'htmlspecialchars'),
            'address_id' => $ticket->address_id,
            'provider_id' => $ticket->provider_id,
            'appointment_ticket_id' => $post['appointment_ticket_id'],
            'appointment_time' => $post['appointment_time'],
            'appointment_period' => $post['appointment_period'],
            'status' => AppointmentApplication::STATUS_NOT_SIGN,
            'city' => $this->request->param('city', '', 'htmlspecialchars'),
            'job' => $this->request->param('job', '', 'htmlspecialchars'),
            'education_level' => $post['education_level']??0,
            'home_address' => $this->request->param('home_address', '', 'htmlspecialchars'),
            'marriage' => $post['marriage']??0,
            'problem_type' => $post['problem_type']??0,
            'childs_num_str' => $this->request->param('childs_num_str', '', 'htmlspecialchars'),
        ];
        if (false === $model->allowField(true)->save($data)) {
            $this->json_error("预约入库失败");
        } else {
            $this->json_success("预约成功");
        }
    }


    //取消预约
    public function cancelApplication()
    {
        $post = $this->request->param();
        $validate = new \think\Validate([
            ['id', 'require|number'],
        ]);
        if (!$validate->check($post)) {
            $this->json_error('提交失败：' . $validate->getError());
        }

        $application = (new AppointmentApplication())->where(['id' => $post['id'], 'user_id' => $this->getUserId()])->find();
        if (!$application) {
            $this->json_error("预约不存在");
        }

        if ($application->finish_time > 0) {
            $this->json_error("已完成，不可取消");
        }

        // n 小时后不可取消
        $cancel_appointment_time = Webconfig::getValue('cancel_appointment_time');
        if ($cancel_appointment_time && time() > ($application->getData('create_time') + $cancel_appointment_time * 3600)) {
            $this->json_error("超过{$cancel_appointment_time}小时后，不可取消");
        }

        if (false === $application->save(['status' => AppointmentApplication::STATUS_CANCEL, 'finish_time' => time()])) {
            $this->json_error("提交失败");
        } else {
            $this->json_success("提交成功");
        }
    }


    //我的预约列表
    public function applicationList()
    {
        $post = $this->request->param();
        $validate = new \think\Validate([
            ['status', 'number'],
            ['page', 'number'],
            ['pagenum', 'number|<=:1000']
        ]);
        if (!$validate->check($post)) {
            $this->json_error('提交失败：' . $validate->getError());
        }

        $where = ['user_id' => $this->getUserId()];
        $status = $this->request->param('status', 0, 'intval');
        if ($status == 1) {
            $where['finish_time'] = 0;
        } elseif ($status == 2) {
            $where['finish_time'] = ['>', 0];
        }
        $pagenum = $this->request->param('pagenum', 20, 'intval');
        $datalist = AppointmentApplication::with('ticket')->where($where)->order('create_time desc')->paginate($pagenum, true);
        foreach ($datalist as $key => $item) {
            //专家信息
            $item->address;
            $item->specialist;
            $item->specialist->head_pic = geturl($item->specialist->head_pic, '', true);
            $item->appointment_date = $item->appointment_date;
            $item->ticke_time = $item->ticket->appointment_daytime;
            $datalist[$key] = $item;
        }
        if (empty($datalist)) {
            $this->json_error("没有数据");
        }
        $this->json_success("查询成功", $datalist);
    }


    //提交反馈接口
    public function feedback()
    {
        $post = $this->request->param();
        //验证
        $validate = new \think\Validate([
            ['content|内容', 'require|max:500'],
        ]);
        if (!$validate->check($post)) {
            $this->json_error('提交失败：' . $validate->getError());
        }

        $model = new Feedback();
        $data = [
            'user_id' => $this->getUserId(),
            'content' => $this->request->param('content', '', 'htmlspecialchars')
        ];
        if (false === $model->allowField(true)->save($data)) {
            $this->json_error("提交失败");
        } else {
            $this->json_success("提交成功");
        }
    }
}
