#!/usr/bin/env python
# coding=utf-8
import datetime

from django.db import models
from django.contrib.auth.models import User

from gm_types.gaia import (
    RESERVATION_TYPE, RESERVATION_STATUS, TIME_TYPE)

from .doctor import Doctor


class DoctorAddress(models.Model):
    class Meta:
        db_table = 'api_doctoraddress'
        app_label = 'api'

    desc = models.CharField(max_length=20, verbose_name=u'简短地址')
    lng = models.FloatField(default=0, verbose_name=u'经度')
    lat = models.FloatField(default=0, verbose_name=u'纬度')
    doctor = models.ForeignKey(Doctor)
    location = models.CharField(max_length=200, verbose_name=u'具体地址')
    created_time = models.DateTimeField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now=True)


class Schedule(models.Model):
    class Meta:
        db_table = 'api_schedule'
        app_label = 'api'

    date = models.DateTimeField(verbose_name='接受预约日期')
    am_or_pm = models.CharField(max_length=1, choices=TIME_TYPE)
    start_time = models.TimeField()
    end_time = models.TimeField()
    doctor = models.ForeignKey(Doctor)
    address = models.ForeignKey(DoctorAddress)
    reservation_type = models.CharField(max_length=2, choices=RESERVATION_TYPE)


class Reservation(models.Model):
    class Meta:
        db_table = 'api_reservation'
        app_label = 'api'

    date = models.DateTimeField(verbose_name=u'预约时间')
    schedule = models.ForeignKey(Schedule)
    cancel_operator_role = models.ForeignKey(User, null=True, related_name='canceler')
    order = models.ForeignKey('Order', related_name="reservation")
    status = models.CharField(max_length=10, choices=RESERVATION_STATUS)
    user = models.ForeignKey(User)
    created_time = models.DateTimeField(auto_now_add=True)
    cancel_time = models.DateTimeField(null=True)
    cancel_reason = models.CharField(verbose_name=u'取消原因', max_length=100, null=True)
    reservation_address = models.CharField(max_length=200)
    reservation_type = models.CharField(max_length=2, choices=RESERVATION_TYPE)
    accepted_time = models.DateTimeField(null=True)

    @classmethod
    def order_latest_status(cls, order_id):
        refs = cls.objects.filter(order_id=order_id).order_by('-created_time')
        if not refs:
            return ''
        ref = refs[0]
        ref.check_expired()
        return ref.status

    @classmethod
    def check_reservation_expired(cls, user):
        now = datetime.datetime.now()
        cls.objects.filter(user=user, date__lt=now).exclude(
            status=RESERVATION_STATUS.CANCELED).update(
                status=RESERVATION_STATUS.EXPIRED)

    @classmethod
    def doctor_check_reservation_expired(cls, doctor):
        # 需求是: 只要预约过期了,就改成过期状态,不是只在医生未处理的时候更改
        now = datetime.datetime.now()
        result = cls.objects.filter(schedule__doctor=doctor, date__lt=now).exclude(
            status__in=[RESERVATION_STATUS.CANCELED, RESERVATION_STATUS.EXPIRED]).update(
                status=RESERVATION_STATUS.EXPIRED)
        return result

    def check_expired(self):
        now = datetime.datetime.now()
        if self.date < now:
            self.status = RESERVATION_STATUS.EXPIRED
            self.save()


class ScheduleTimeSlotManager(models.Manager):
    def init(self, schedule):
        doctor = schedule.doctor
        date = schedule.date
        start_hour = int(str(schedule.start_time).split(':')[0])
        end_hour = int(str(schedule.end_time).split(':')[0])
        start_dt = datetime.datetime(date.year, date.month, date.day, start_hour)
        end_dt = datetime.datetime(date.year, date.month, date.day, end_hour)
        while True:
            self.get_or_create(doctor=doctor, start_time=start_dt, date=date)
            start_dt += datetime.timedelta(minutes=20)  # 20分钟一段
            if start_dt >= end_dt:
                break


class ScheduleTimeSlot(models.Model):
    class Meta:
        db_table = 'api_scheduletimeslot'
        app_label = 'api'

    reservation = models.ForeignKey(Reservation, null=True)
    start_time = models.DateTimeField()
    doctor = models.ForeignKey(Doctor)   # TODO 是否做外键
    date = models.DateTimeField()

    objects = ScheduleTimeSlotManager()


class ScheduleTemplate(models.Model):
    """
        模板信息保存在content中，以JSON格式存储，格式如下:
        [{
            'id': 0,  # weekday
            'title': '周一时间表',
            'am': {
                'start_time': string, # 08:00
                'end_time': string,
                'address_desc': string,
                'address_id': string,
                'reservation_type': string,  #'', '0', '1', '2'
            },
            'pm': {
                'start_time': string, # 08:00
                'end_time': string,
                'address_desc': string,
                'address_id': string,
                'reservation_type': string,  #'', '0', '1', '2'
            },
        },]
    """
    class Meta:
        verbose_name = u'医生时刻模板'
        db_table = 'api_schedule_tempalte'
        app_label = 'api'

    doctor = models.ForeignKey(Doctor)
    title = models.CharField(max_length=100, null=True, verbose_name=u'名字')
    content = models.TextField(blank=True, verbose_name=u"内容")
    created_time = models.DateTimeField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now=True)
