# coding=utf8
from __future__ import unicode_literals, absolute_import, print_function
from django.db import models
from django.utils import timezone
from .tag import Tag
from .types import PLAN_TYPE, TREATMENT_TYPE, RECOVER_TIME_TYPE, FREECUSTOM_STATUS_TYPE
from api.models.person import Person
from api.models.order import Order
from datetime import timedelta


class FreeCustom(models.Model):
    class Meta:
        verbose_name = u'免费定制医美'
        verbose_name_plural = u'免费定制医美'
        db_table = 'api_freecustom'
        app_label = 'api'

    user = models.ForeignKey(Person, verbose_name=u'用户')
    phone = models.CharField(verbose_name=u'联系电话', max_length=100)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    feedback_time = models.DateTimeField(verbose_name=u'反馈时间', blank=True, null=True, default=None)
    tags = models.ManyToManyField(Tag, verbose_name=u'想做的项目', related_name="freecustoms", through="FreecustomTag")
    plan_type = models.CharField(verbose_name=u'预算范围', max_length=1, choices=PLAN_TYPE, default=PLAN_TYPE.DEFAULT)
    comments = models.CharField(verbose_name=u'用户特殊情况说明', max_length=200, null=True, blank=True, default='')
    kefu_comments = models.TextField(verbose_name=u'客服备注信息', null=True, blank=True, default='')
    operation_type = models.CharField(verbose_name=u'手术类型', max_length=8, choices=TREATMENT_TYPE,
                                      default=TREATMENT_TYPE.DEFAULT)
    recover_time = models.CharField(verbose_name=u'恢复周期', max_length=1, choices=RECOVER_TIME_TYPE,
                                    default=RECOVER_TIME_TYPE.DEFAULT)
    is_phone_connect = models.BooleanField(verbose_name=u'是否有电话联系', default=False)
    follow_status = models.CharField(verbose_name=u'跟进状态', max_length=1, choices=FREECUSTOM_STATUS_TYPE,
                                     default=FREECUSTOM_STATUS_TYPE.DEFAULT)

    @property
    def has_order(self):
        orders = Order.objects.filter(status__in=['1', '2']).filter(user_id=self.user.user_id)\
            .filter(pay_time__range=(self.create_time, self.create_time + timedelta(days=30)))
        return orders


class FreecustomTag(models.Model):
    class Meta:
        app_label = 'api'

    freecustom = models.ForeignKey(FreeCustom)
    tag = models.ForeignKey(Tag)


class FreecustomImage(models.Model):
    class Meta:
        verbose_name = u'免费定制图片'
        verbose_name_plural = u'免费定制图片'
        db_table = 'api_freecustomimage'
        app_label = 'api'

    freecustom = models.ForeignKey(FreeCustom, related_name='images')
    image_url = models.CharField(max_length=300, verbose_name=u'图片地址')
