<?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)
    {
        $json = json_decode($value, true);
        if (!is_array($json)) {
            return [];
        } else {
            foreach ($json as $k => $item) {
                if (empty($item))
                    unset($json[$k]);
            }
            return $json;
        }
    }


    //afternoon_time_periods
    public function getAfternoonTimePeriodsAttr($value, $data)
    {
        $json = json_decode($value, true);
        if (!is_array($json)) {
            return [];
        } else {
            foreach ($json as $k => $item) {
                if (empty($item))
                    unset($json[$k]);
            }
            return $json;
        }
    }


    //生成工作日号源
    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', '<>', '')->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()) {
                    if (empty($appoint->specialist)) {
                        continue;
                    }
                    (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');
    }
}