# coding=utf8

from __future__ import unicode_literals, absolute_import, print_function

from django.db import models
from django.utils import timezone
from gm_dataquery.dict_mixin import to_dict
from gm_types.gaia import ACTIVITY_PARTICIPATE_REASON, ACTIVITY_TYPE_SOC
from gm_upload import ImgUrlField, IMG_TYPE

from talos.libs.datetime_utils import get_timestamp_or_none
from talos.libs.image_utils import get_full_path
from talos.rpc import logging_exception
from talos.services import UserService
from talos.services.doctor import DoctorService
from talos.services import UserConvertService


class Activity(models.Model):
    class Meta:
        verbose_name = u'免费活动'
        db_table = 'api_activity'
        app_label = 'talos'

    title = models.CharField(max_length=128, null=False, verbose_name=u'活动名称')
    banner = ImgUrlField(img_type=IMG_TYPE.BANNER, max_length=128, null=False, verbose_name='bannerl')
    description = models.TextField(max_length=2000, verbose_name=u'详细描述')
    points = models.IntegerField(verbose_name=u'参加活动需要的美分')
    start_time = models.DateTimeField(verbose_name=u'起始时间', default=timezone.now)
    end_time = models.DateTimeField(verbose_name=u'结束时间', null=True, blank=True)
    is_online = models.BooleanField(default=True, verbose_name=u'上线')
    show_win_list = models.BooleanField(default=True, verbose_name=u'展示中奖名单')
    win_limit = models.IntegerField(verbose_name=u'可中奖人数', default=0)
    show_topics = models.BooleanField(default=True, verbose_name=u'展示活动帖子')
    participate_limit = models.IntegerField(verbose_name=u'每人可参与次数', default=1)
    participants = models.IntegerField(verbose_name=u'已报名人数', default=0)
    doctor_id = models.CharField(max_length=100, null=True, blank=True, default=None, verbose_name=u'关联医生的外键id')
    # 富文本编辑器
    description_richtext = models.TextField(default='', blank=True, max_length=2000, verbose_name=u'详细描述')
    must_image = models.BooleanField(default=False, verbose_name=u'图片是否为空')
    act_type = models.CharField(
        choices=ACTIVITY_TYPE_SOC,
        default=ACTIVITY_TYPE_SOC.NORMAL,
        max_length=16,
        verbose_name=u'活动类型'
    )

    def can_participate(self, user_id, user_points=0):  # TODO CR 这段逻辑应该挪到 person 中去
        # activity should be online
        if not self.is_online:
            return False, ACTIVITY_PARTICIPATE_REASON.CLOSED

        # start_time <= now <=end_time
        now = timezone.now()
        if self.start_time > now:
            return False, ACTIVITY_PARTICIPATE_REASON.NOT_STARTED

        if self.end_time < now:
            return False, ACTIVITY_PARTICIPATE_REASON.CLOSED

        # 去掉免费活动参加门槛
        # if self.points > user_points:
        #     return False, ACTIVITY_PARTICIPATE_REASON.NOT_ENOUGH_POINTS

        # check paticipate limit
        from talos.models.topic.topic import Problem
        # TODO CR 拆activity的时候拆 现在先这样
        activity_topics = Problem.objects.filter(user_id=user_id, activity=self).count()
        if activity_topics >= self.participate_limit:
            return False, ACTIVITY_PARTICIPATE_REASON.PARTICIPATE_LIMIT

        return True, ACTIVITY_PARTICIPATE_REASON.OK

    def to_dict(self, simple=True):
        """convert to dict for jsonify.

        args:
            simple: True just return following fields, False return all fields
              - banner
              - participants
              - id
              - status_text
              - act_type

        NOTE:
            if show_win_list is true and simple is False, return extra fields
            winners.
        """
        if simple:
            data = to_dict(
                self,
                fields=['id', 'banner', 'participants', 'is_online', 'act_type'],
            )

        else:
            data = to_dict(self)

            try:
                data['winners'] = []
                if self.show_win_list:
                    person_ids = list(set(self.winners.values_list('person_id', flat=True)))
                    users = UserConvertService.get_user_info_by_person_ids(person_ids=person_ids)
                    for person_id in person_ids:
                        user = users.get(person_id)
                        data['winners'].append({
                            'id': user["person_id"],
                            'user_id': user["user_id"],
                            'phone': '',
                            'doctor_id': user["doctor_id"],
                            'doctor_type': user["doctor_type"],
                            'hospital_id': user["hospital_id"],
                            'nickname': user["user_name"],
                            'portrait': user["portrait"] or get_full_path(u'img%2Fuser_portrait.png', '-thumb'),
                        })
            except:
                logging_exception()

        # convert datetime field to timestamp
        data['start_time'] = get_timestamp_or_none(self.start_time)
        data['end_time'] = get_timestamp_or_none(self.end_time)
        data['mk_description'] = self.description
        data['rich_text'] = self.description_richtext
        data["title"] = self.title
        return data

    @property
    def doctor(self):
        return DoctorService.get_doctor_from_doctor_id(self.doctor_id)


class ActivityWinlist(models.Model):
    class Meta:
        verbose_name = u'免费活动中奖名单'
        db_table = 'api_activitywinlist'
        app_label = 'talos'

    activity = models.ForeignKey(Activity, verbose_name=u'免费活动', related_name='winners')
    person_id = models.CharField(verbose_name=u'用户外键id', max_length=64)
    topic = models.IntegerField(verbose_name=u'中奖帖子')
    created_at = models.DateTimeField(verbose_name=u'中奖时间', default=timezone.now)


class ActivityAlert(models.Model):
    class Meta:
        verbose_name = u'活动提醒名单'
        db_table = 'api_activity_alert'
        app_label = 'talos'

    activity = models.ForeignKey(Activity, verbose_name=u'免费活动')
    person_id = models.CharField(verbose_name=u'用户外键id', max_length=64)
    is_online = models.BooleanField(default=True, verbose_name=u'上线')
    create_time = models.DateTimeField(verbose_name=u'创建时间', default=timezone.now)
    update_time = models.DateTimeField(verbose_name=u'更新时间', auto_now=True)

