# coding: utf-8
from __future__ import absolute_import, print_function, unicode_literals
import json
from django.db import models
from django.utils import timezone
from django.db.models import Q
from gm_types.gaia import MULTITOPIC_SERVICE_TYPE, MULTITOPIC_TYPE, MULTITOPIC_REVIEW_TYPE, MULTITOPIC_REVIEW_STATUS

from .tag import Tag
from .zone import Zone
from .special import Special
from .service import Service
from rpc.cache import multitopic_cache
from rpc.tool.dict_mixin import to_dict


class MultiTopic(models.Model):
    RKEY_VISIBLE = 'multitopic_visible'  # redis存储大杂烩置顶是否显示的key

    class Meta:
        verbose_name = u'大杂烩'
        verbose_name_plural = u'大杂烩'
        app_label = 'api'

    multitopic_type = models.CharField(max_length=2, choices=MULTITOPIC_TYPE, default=MULTITOPIC_TYPE.TOPIC, db_index=True,
                                  verbose_name=u'跳转的类型')
    service_type = models.CharField(max_length=1, choices=MULTITOPIC_SERVICE_TYPE, default=MULTITOPIC_SERVICE_TYPE.DEAL, verbose_name=u'业务类型')
    topic_id = models.IntegerField(verbose_name=u'指定的话题', null=True, blank=True)
    service = models.ForeignKey(Service, verbose_name=u'指定的服务', null=True, blank=True)
    diary_id = models.IntegerField(verbose_name=u'指定的日记', null=True, blank=True)
    url = models.CharField(max_length=1024, null=True, blank=True, verbose_name=u'跳转的网址')
    ordering = models.IntegerField(default=20, verbose_name=u"展示顺序", help_text=u"小的排在前，大的排在后")
    created_time = models.DateTimeField(auto_now_add=True, verbose_name=u'添加时间')
    effect_time = models.DateTimeField(null=True, verbose_name=u'生效时间', default=timezone.now)
    end_time = models.DateTimeField(null=True, verbose_name=u'下线时间', blank=True)
    is_online = models.BooleanField(default=True, help_text=u"是否上线", verbose_name=u"上线")
    tag = models.ForeignKey(Tag, verbose_name=u'指定的Tag列表', null=True, blank=True)
    special = models.ForeignKey(Special, verbose_name=u'指定的福利专题', null=True, blank=True)
    activity_id = models.IntegerField(verbose_name=u'免费活动', null=True, blank=True)
    title = models.CharField(max_length=100, verbose_name=u'名称', null=True, blank=True)
    zhiboconfig_id = models.IntegerField(verbose_name=u'直播预告', null=True, blank=True)
    # question = models.ForeignKey(Question, verbose_name=u'问题',  null=True, blank=True)
    # change at: 2017-08-03 问答社区迁移
    question_id = models.IntegerField(blank=True, null=True, verbose_name="关联问题")


    @classmethod
    def get_visible(cls):
        try:
            visible = multitopic_cache.get(cls.RKEY_VISIBLE)
            if not visible:
                return {'multitopic': True}
            else:
                return json.loads(visible)
        except:
            return {'multitopic': True}

    @classmethod
    def set_visible(cls, visible=True):
        visible_data = multitopic_cache.get(cls.RKEY_VISIBLE)
        if not visible_data:
            visible_data = {}
        else:
            visible_data = json.loads(visible_data)
        visible_data['multitopic'] = visible
        multitopic_cache.set(cls.RKEY_VISIBLE, json.dumps(visible_data))

    def to_dict_for_url(self):
        live_channel_id = ''
        if self.multitopic_type == MULTITOPIC_TYPE.ZHIBO and self.zhiboconfig_id:
            from rpc.all import get_rpc_remote_invoker
            rpc = get_rpc_remote_invoker()

            live_channel_info = rpc['mimas/live/get_channel_info_by_zhiboconfig_id'](
                zhiboconfig_id=self.zhiboconfig_id
            )
            live_channel_info = live_channel_info.unwrap()
            live_channel_id = live_channel_info.get('channel_id', '')

        tag_name = self.tag and self.tag.name or ''
        data = to_dict(self, excludes=['ordering', 'created_time', 'effect_time', 'end_time', 'is_online'])
        # Add 2017-08-03: 社区迁移
        data['question'] = data['question_id']
        data['topic'] = data['topic_id']
        data['diary'] = data['diary_id']
        data['activity'] = data['activity_id']
        data.update({'tag_name': tag_name, 'live_channel_id': live_channel_id})

        return data

    @classmethod
    def get_data(cls, count):
        if not cls.get_visible()['multitopic']:
            return []

        now = timezone.now()
        datas = cls.objects.filter(
            is_online=True,
        ).filter(
            Q(end_time__isnull=True) | Q(end_time__gte=now),
            effect_time__lte=now,
        ).order_by('ordering', '-created_time')[:count]

        re = []
        for data in datas:
            _d = {
                'id': data.id,
                'title': data.title,
                'url': data.to_dict_for_url(),
            }

            re.append(_d)
        return re


class ZoneWhiteList(models.Model):
    class Meta:
        verbose_name = u'圈子白名单'
        verbose_name_plural = u'圈子白名单'
        app_label = 'api'

    zone = models.ForeignKey(Zone, verbose_name=u'圈子', null=False)
    is_online = models.BooleanField(verbose_name=u'是否生效', default=False)


class MultiTopicReview(models.Model):
    class Meta:
        verbose_name = u'大杂烩内容审核'
        verbose_name_plural = u'大杂烩内容审核'
        app_label = 'api'
        unique_together = (('content_id', 'content_type'),)

    content_id = models.CharField(max_length=20, verbose_name=u'日记贴或问题ID', null=False)
    content_type = models.CharField(max_length=1, choices=MULTITOPIC_REVIEW_TYPE,
                                    default=MULTITOPIC_REVIEW_TYPE.PROBLEM, verbose_name=u'内容类型', null=False)
    status = models.CharField(max_length=1, choices=MULTITOPIC_REVIEW_STATUS,
                              default=MULTITOPIC_REVIEW_STATUS.WAITTING, verbose_name=u'审核状态', null=False)
