<?php

namespace app\admin\controller;

use app\admin\controller\base\Permissions;
use app\common\model\Appointment as appointmentModel;
use think\Db;
use time\DateHelper;

class Appointment extends Permissions
{
    private function getModel()
    {
        return new appointmentModel();
    }

    public function index()
    {
        $pid = $this->request->param('pid', 0, 'intval');
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $where = [
                'provider_id' => $pid
            ];
            if (isset($post['ids']) and !empty($post['ids'])) {
                $where['id'] = ['in', $post['ids']];
            }
            if (isset($post["start_time"]) and !empty($post["start_time"])) {
                $timerang = explode(' - ', $post["start_time"]);
                $min_time = strtotime($timerang[0]);
                $max_time = $timerang[0] == $timerang[1] ? $min_time + 24 * 3600 - 1 : strtotime($timerang[1]??'');
                $where["start_time"] = [['>=', $min_time], ['<=', $max_time]];
            }
            if (isset($post["create_time"]) and !empty($post["create_time"])) {
                $timerang = explode(' - ', $post["create_time"]);
                $min_time = strtotime($timerang[0]);
                $max_time = $timerang[0] == $timerang[1] ? $min_time + 24 * 3600 - 1 : strtotime($timerang[1]??'');
                $where["create_time"] = [['>=', $min_time], ['<=', $max_time]];
            }

            $model = $this->getModel();
            $count = $model->where($where)->count();
            $data = $model->where($where)->page($post['page']??0, $post['limit']??15)->order('id desc')->select();
            foreach ($data as $key => $value) {
                $value['specialist_name'] = $value->specialist->name;
                $value['appointment_date_text'] = $value->appointment_date_text;
                $data[$key] = $value;
            }
            return array('code' => 0, 'count' => $count, 'data' => $data);
        } else {
            return $this->fetch();
        }
    }


    public function publish()
    {
        $id = $this->request->param('id', 0, 'intval');
        $pid = $this->request->param('pid', 0, 'intval');
        $this->assign('pid', $pid);

        $post = $this->request->post();
        $post['provider_id'] = $pid;

        if ($this->request->isPost()) {

            if (isset($post['start_time']) && !empty($post['start_time'])) {
                $timerang = explode(' - ', $post["start_time"]);
                $min_time = strtotime(str_replace(['年', '月'], '-', $timerang[0]));
                $max_time = $timerang[0] == $timerang[1] ? $min_time + 24 * 3600 - 1 : strtotime(str_replace(['年', '月'], '-', $timerang[1]??''));
                $post['start_time'] = $min_time;
                $post['end_time'] = $max_time;
            }
            if (isset($post['morning_start_time']) && !empty($post['morning_start_time'])) {
                $timerang = explode(' - ', $post["morning_start_time"]);
                $post['morning_start_time'] = $timerang[0];
                $post['morning_end_time'] = $timerang[1];
            }
            if (isset($post['afternoon_start_time']) && !empty($post['afternoon_start_time'])) {
                $timerang = explode(' - ', $post["afternoon_start_time"]);
                $post['afternoon_start_time'] = $timerang[0];
                $post['afternoon_end_time'] = $timerang[1];
            }
            if (isset($post['night_start_time']) && !empty($post['night_start_time'])) {
                $timerang = explode(' - ', $post["night_start_time"]);
                $post['night_start_time'] = $timerang[0];
                $post['night_end_time'] = $timerang[1];
            }

            //验证
            $validate = new \think\Validate([
                ['provider_id', 'require|number'],
                ['start_time', 'number', '排号日期格式不对'],
                ['end_time', 'number', '排号日期格式不对'],
                ['morning_num|上午放号个数', 'number'],
                ['morning_start_time', 'length:8', '上午时间格式不对'],
                ['morning_end_time', 'length:8', '上午时间格式不对'],
                ['afternoon_num|下午放号个数', 'number'],
                ['afternoon_start_time', 'length:8', '下午时间格式不对'],
                ['afternoon_end_time', 'length:8', '下午时间格式不对'],
                ['night_num|晚上放号个数', 'number'],
                ['night_start_time', 'length:8', '晚上时间格式不对'],
                ['night_end_time', 'length:8', '晚上时间格式不对'],
            ]);
            if (!$validate->check($post)) {
                $this->error('提交失败：' . $validate->getError());
            }

            $weeks = $post['weeks']??[];
            $weeks = array_keys($weeks);
        }

        $model = $this->getModel();
        if ($id > 0) {
            //修改
            $this->error('不允许修改');
        } else {
            //新增
            if ($this->request->isPost()) {

                if (empty($weeks)) {
                    //按时间跨度排号
                    $exits = (new \app\common\model\AppointmentTicket())->where(['provider_id' => $pid, 'appointment_daytime' => [['>=', $post['start_time']], ['<=', $post['end_time']]]])->count();
                    if ($exits > 0) {
                        $this->error('该时间跨度内，已存在排号，请重新选择放号时间，或删除旧的排号');
                    }
                    //保存放号设置
                    if (false == $model->allowField(true)->save($post)) {
                        $this->error('添加失败');
                    } else {
                        //生成号源
                        $daylist = DateHelper::dateTimeList(date('Y-m-d', $post['start_time']), date('Y-m-d', $post['end_time']), true);
                        if (count($daylist) == 2 && end($daylist) == current($daylist)) {
                            array_pop($daylist);
                        }
                        $addressId = (new \app\common\model\Specialist())->where('id', $post['provider_id'])->value('address_id');
                        foreach ($daylist as $datetime) {
                            $data = [
                                'appointment_id' => $model->id,
                                'appointment_daytime' => strtotime($datetime),
                                'address_id' => $addressId,
                                'provider_id' => $post['provider_id'],
                                'status' => \app\common\model\AppointmentTicket::STATUS_OPEN
                            ];
                            if (false == (new \app\common\model\AppointmentTicket())->allowField(true)->save($data)) {
                                $this->error('添加失败');
                            }
                        }
                    }

                } else {
                    //按工作日排号
                    $appoints = (new \app\common\model\Appointment())->where(['provider_id' => $pid, 'weeks' => ['<>', '']])->select();
                    foreach ($appoints as $appoint) {
                        foreach ($weeks as $week) {
                            if (in_array($week, explode(',', $appoint->weeks))) {
                                $week_text = \app\common\model\Appointment::WEEK_TEXTS[$week];
                                $this->error("{$week_text} 已存在放号设置，请重新选择时间");
                            }
                        }
                    }

                    //保存放号设置
                    $post['start_time'] = 0;
                    $post['end_time'] = 0;
                    $post['weeks'] = implode(',', $weeks);
                    if (false == $model->allowField(true)->save($post)) {
                        $this->error('添加失败');
                    }
                }

                $this->success('添加成功', 'index', ['pid' => $pid]);

            } else {
                return $this->fetch();
            }
        }
    }

    public function delete()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->param('id', 0, 'intval');
            if (false == $this->getModel()->where('id', $id)->delete()) {
                $this->error('删除失败');
            } else {
                $this->success('删除成功', 'index');
            }
        }
    }

    public function deletes()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $ids = $post['ids'];
            if ($this->getModel()->where('id', 'in', $ids)->delete()) {
                $this->success('删除成功');
            }
        }
    }

    public function status()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (false == $this->getModel()->where('id', $post['id'])->update(['status' => $post['status']])) {
                $this->error('设置失败');
            } else {
                $this->success('设置成功', 'index');
            }
        }
    }
}