<?php

namespace app\common\model;

use think\Exception;
use think\Model;

class Appointment extends Model
{
    protected $updateTime = false;

    const STATUS_OPEN = 1;
    const STATUS_CLOSE = 0;

    const WEEK_TEXTS = ['', '周一', '周二', '周三', '周四', '周五', '周六', '周日'];


    //morning_time_periods
    public function getMorningTimePeriodsAttr($value, $data)
    {
        return json_decode($this->morning_time_periods, true);
    }


    //afternoon_time_periods
    public function getAfternoonTimePeriodsAttr($value, $data)
    {
        return json_decode($this->afternoon_time_periods, true);
    }


    //生成工作日号源
    public static function createWeekTicketAll($daytime)
    {
        $daytimestamp = strtotime($daytime);
        if (strtotime(date('Y-m-d')) > $daytimestamp) {
            throw new Exception("该时间已过期,请重新选择时间");
        }

        $daytimeWeek = date('w', $daytimestamp);

        $appoints = (new Appointment())->where('weeks', '<>', '')->where('status', self::STATUS_OPEN)->select();
        foreach ($appoints as $appoint) {
            $weeks = explode(',', $appoint->weeks);
            if (in_array($daytimeWeek, $weeks)) {
                //生成号源记录
                if (0 == (new AppointmentTicket())->where(['appointment_id' => $appoint->id, 'appointment_daytime' => $daytimestamp])->count()) {
                    (new AppointmentTicket())->allowField(true)->save([
                        'appointment_id' => $appoint->id,
                        'appointment_daytime' => $daytimestamp,
                        'address_id' => $appoint->specialist->address_id,
                        'provider_id' => $appoint->provider_id,
                        'status' => AppointmentTicket::STATUS_OPEN
                    ]);
                }
            }
        }
    }

    //关联专家
    public function specialist()
    {
        return $this->belongsTo('Specialist', 'provider_id');
    }
}
