<?php

namespace app\api\controller;

use app\api\controller\base\Base;
use app\common\model\Address;
use app\common\model\AppointmentApplication;
use app\common\model\AppointmentTicket;
use think\Exception;

class Appointment extends Base
{

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

        $pagenum  = $this->request->param('pagenum', 20, 'intval');
        $datalist = (new Address())->where('status', Address::STATUS_YES)->paginate($pagenum, true);
        if (empty($datalist)) {
            $this->json_error("没有数据");
        }
        foreach ($datalist as $key => $item) {
            $item['thumb_url'] = geturl($item->thumb, '', true);
            $datalist[$key]    = $item;
        }
        $this->json_success("查询成功", $datalist);
    }


    //按时间获取地址列表
    public function addressListByDayTime()
    {
        $ticketModel = new AppointmentTicket();
        $post        = $this->request->param();
        $validate    = new \think\Validate([
            ['daytime', 'date|dateFormat:Y-m-d'],
            ['page', 'number'],
            ['pagenum', 'number|<=:1000'],
        ]);
        if (!$validate->check($post)) {
            $this->json_error('提交失败：' . $validate->getError());
        }

        $daytime = $this->request->param('daytime', date('Y-m-d'));

        try {
            //生成工作日号源
            \app\common\model\Appointment::createWeekTicketAll($daytime);
        } catch (Exception $e) {
            $this->json_error($e->getMessage());
        }

        $addressIds = $ticketModel->where('appointment_daytime', strtotime($daytime))->distinct(true)->column('address_id');

        $where           = [];
        $where['id']     = ['in', $addressIds];
        $where['status'] = 1;
        $pagenum         = $this->request->param('pagenum', 20, 'intval');
        $datalist        = (new Address())->where($where)->paginate($pagenum, true);
        if (empty($datalist)) {
            $this->json_error("没有数据");
        }
        foreach ($datalist as $key => $item) {
            $item['thumb_url'] = geturl($item->thumb, '', true);
            $datalist[$key]    = $item;
        }
        $this->json_success("查询成功", $datalist);
    }


    //获取号源列表
    public function getTicketByAddressId()
    {
        $post     = $this->request->param();
        $validate = new \think\Validate([
            ['address_id', 'require|number'],
            ['daytime', 'dateFormat:Y-m-d'],
        ]);
        if (!$validate->check($post)) {
            $this->json_error('提交失败：' . $validate->getError());
        }

        $address_id = $this->request->param('address_id');
        $daytime    = $this->request->param('daytime', date('Y-m-d'));

        try {
            //生成工作日号源
            \app\common\model\Appointment::createWeekTicketAll($daytime);
        } catch (Exception $e) {
            $this->json_error($e->getMessage());
        }

        $ticketModel = new AppointmentTicket();
        $tickets     = $ticketModel->where('address_id', $address_id)->where('appointment_daytime', strtotime($daytime))->select();

        foreach ($tickets as $k => $item) {
            if (empty($item->appointment) || empty($item->specialist)) {
                unset($item);
                continue;
            }
            $appoint = $item->appointment;
            //专家信息
            $item->specialist->head_pic = geturl($item->specialist->head_pic, '', true);
            //已经预约的时间段
            $ticketPeriods = (new AppointmentApplication())->where('appointment_ticket_id', $item->id)->where('finish_time', 0)->column('appointment_time');
            //预约的时间段
            $item['morning_time_period']   = $this->setPeriodStatus($appoint->morning_time_periods, $ticketPeriods);
            $item['afternoon_time_period'] = $this->setPeriodStatus($appoint->afternoon_time_periods, $ticketPeriods);
            //剩余预约号码个数
            $item['morning_remaining']   = count($item['morning_time_period']);
            $item['afternoon_remaining'] = count($item['afternoon_time_period']);
            $tickets[$k]                 = $item;
        }

        $this->json_success("查询成功", $tickets);
//        $this->json_success("查询成功", []);
    }


    /**
     * @param $timePeriods array 放号设置的时间段
     * @param $ticketPeriods array 已经预约的时间段
     * @return array
     */
    private function setPeriodStatus($timePeriods, $ticketPeriods)
    {
        $daytime = $this->request->param('daytime', date('Y-m-d'));
        $arr     = [];
        $now     = time();
        foreach ($timePeriods as $ticket => $period) {
            //排除过期时段
            $timerang   = explode('-', $period);

            $period_end = trim($timerang[1]);
            if ($now > strtotime($daytime . ' ' . $period_end)) {
                continue;
            }
            //标记预约状态
            if (in_array($period, $ticketPeriods)) {
//                $arr[] = ['period' => $period, 'status' => 1];
                continue;//排除已被预约的
            } else {
                $arr[] = ['period' => $period, 'status' => 0];
            }
        }
        return $arr;
    }


}