# coding=utf8
from __future__ import unicode_literals, absolute_import, print_function

from datetime import datetime
from django.db.models import BooleanField, Q
from django.db.models import ForeignKey, ManyToManyField, DateTimeField, \
    DateField
from django.db.models import Model, CharField, IntegerField, TextField

from cached_property import cached_property

from gm_types.gaia import (
    POLYMER_DETAIL_TAB_TYPE,
    POLYMER_CONTENT_TYPE,
    GADGET_PAGE_TYPE,
    POLYMER_PUB_TYPE,
)

from gm_types.mimas.qa import QUESTION_TYPE
from wiki.logices.item import format_item_info
from wiki.models.item import Item
from wiki.models.collect import Collect, TopItem

from api.models.tag import Tag
from agile.models import AgileTag
from api.models.slide import HomepageOperate, Gadget
from api.models.area import City
from gm_upload import IMG_TYPE, ImgUrlField

class Polymer(Model):
    class Meta:
        verbose_name = '内容聚合'

    name = CharField('标题', max_length=32)
    description = TextField('活动详情')
    wiki_item = ForeignKey(Item, null=True)
    wiki_collect = ForeignKey(Collect, null=True)
    banner = ManyToManyField(HomepageOperate)
    gadget = ManyToManyField(Gadget, verbose_name='固定模板')
    tags = ManyToManyField(Tag, related_name='polymer')
    default_tab = IntegerField('默认tab', choices=POLYMER_DETAIL_TAB_TYPE, default=POLYMER_DETAIL_TAB_TYPE.SERVICE)
    pub_type = IntegerField('发布类型', choices=POLYMER_PUB_TYPE, default=POLYMER_PUB_TYPE.DEFAULT)
    default_classify = IntegerField('默认分类', choices=QUESTION_TYPE, default=QUESTION_TYPE.TRADE)
    question_classify = CharField('问题分类', max_length=32)
    is_online = BooleanField('是否上线', default=True)
    create_time = DateTimeField(auto_now_add=True)
    # 2018.08.06 增加，后台控制聚合页在详情页的展示，目前逻辑应用于问题详情页。
    external_display = BooleanField("是否外显", default=False)
    # v 7.7.10 增加排序字段，越小越靠前
    rank = IntegerField('展示序列', default=999)
    # 7715 new
    introduction = TextField('描述简介')
    bg_image = ImgUrlField(img_type=IMG_TYPE.POLYMER, max_length=255, verbose_name=u'背景图')

    def get_polymer_gadget(self, city_id=None):
        """
        获取聚合页关联的固定模板
        :return:
        """
        gadget_ids = list(self.gadget.values_list("id", flat=True))

        if not gadget_ids:
            return {'gadgets': [],}

        return Gadget.get_gadgets(page_type=GADGET_PAGE_TYPE.POLYMER, city_id=city_id, gadget_ids=gadget_ids)

    @cached_property
    def old_tags(self):
        tag_ids = PolymerTag.objects.filter(polymer_id=self.id).values_list("tag_id", flat=True)
        tags = Tag.objects.filter(pk__in=tag_ids, is_online=True)

        return tags

    @cached_property
    def agiletags(self):
        tag_ids = PolymerAgileTag.objects.filter(polymer_id=self.id).values_list("agile_tag_id", flat=True)
        tags = AgileTag.objects.filter(pk__in=tag_ids, is_online=True)

        return tags

    @cached_property
    def tag_list(self):
        # tags 简单获取 关联的tag，后期有用请补充
        tags = self.tags.order_by("-id").values("id", "name", "is_online", "tag_type")
        return [{"id": tag["id"], "name": tag["name"], "tag_type": tag["tag_type"]}for tag in tags if tag["is_online"]]

    @cached_property
    def agile_tag_list(self):

        agile_tag_ids = AgileTagRelationPolymer.objects.filter(polymer_id=self.id, is_online=True).values_list("agile_tag_id", flat=True)
        tags = AgileTag.objects.filter(pk__in=agile_tag_ids, is_online=True).order_by("-id").values("id", "name", "attribute")

        return [{"id": tag["id"], "name": tag["name"], "attribute": tag["attribute"]} for tag in tags]

    @cached_property
    def show_tab_list(self):
        show_tabs = self.tabs.values("enable", "tab_type")
        return [tab["tab_type"] for tab in show_tabs if tab["enable"]]

    def get_operate_recommends(self, city_id):
        """
        运营推荐信息
        :return: {"content_type": polymer_content}
        """
        recommends_dict = {}
        if city_id == "worldwide" or not city_id:  # 全国数据
            polymer_recommends = self.recommends.filter(
                is_related_city=False,
                start_time__lte=datetime.now(),
                end_time__gte=datetime.now(),
            )
        else:
            city_obj = City.objects.get(id=city_id)

            polymer_recommends = self.recommends.filter(
                Q(id__in=city_obj.polymercontent_set.all()) | Q(is_related_city=False),
                is_online=True,
                start_time__lte=datetime.now(),
                end_time__gte=datetime.now(),
            )
        polymer_recommends_data = polymer_recommends.values("id", "rank", "content_type", "content_id")
        for data in polymer_recommends_data:
            if data["content_type"] not in recommends_dict:
                recommends_dict[data["content_type"]] = []
            recommends_dict[data["content_type"]].append(dict(data))
        return recommends_dict

    @property
    def get_wiki_info(self):
        """
        获取关联的 百科信息
        """
        _wiki_data = {
            "wiki_item": {},  # 项目百科
            "wiki_collect": {},  # 项目百科聚合
        }

        if self.wiki_item_id:
            try:
                item = Item.objects.get(pk=self.wiki_item_id, is_online=True)
            except Item.DoesNotExist:
                return _wiki_data
            _wiki_data["wiki_item"] = format_item_info(item)
            return _wiki_data

        if self.wiki_collect_id:
            wiki_collect = Collect.objects.filter(pk=self.wiki_collect_id, is_online=True).values("id", "name",
                                                                                                  "description")
            if wiki_collect.exists():
                _wiki_data["wiki_collect"] = dict(wiki_collect.first())
                return _wiki_data
        return _wiki_data

    @property
    def get_question_classify(self):
        question_classify = []
        if self.question_classify:
            question_classify = self.question_classify.split(",")
        return question_classify


class PolymerTag(Model):
    """聚合页下面的老标签"""

    class Meta:
        verbose_name = u'聚合页下面的老标签'
        db_table = 'api_polymer_tag'
        unique_together = (("tag_id", "polymer_id"),)

    is_online = BooleanField(verbose_name=u"是否有效", default=True)
    create_time = DateTimeField(verbose_name=u'创建时间', auto_now_add=True)
    update_time = DateTimeField(verbose_name=u'更新时间', auto_now=True)
    tag_id = IntegerField(verbose_name=u'新标签', db_index=True)
    polymer_id = IntegerField(verbose_name=u'聚合页id', db_index=True)


class PolymerAgileTag(Model):
    """聚合页下面的新标签"""

    class Meta:
        verbose_name = u'聚合页下面的新标签'
        db_table = 'api_polymer_agiletag'
        unique_together = (("agile_tag_id", "polymer_id"),)

    is_online = BooleanField(verbose_name=u"是否有效", default=True)
    create_time = DateTimeField(verbose_name=u'创建时间', auto_now_add=True)
    update_time = DateTimeField(verbose_name=u'更新时间', auto_now=True)
    agile_tag_id = IntegerField(verbose_name=u'新标签', db_index=True)
    polymer_id = IntegerField(verbose_name=u'聚合页id', db_index=True)



class AgileTagRelationPolymer(Model):
    class Meta:
        verbose_name = u'新标签关联的内容聚合页(可多选)'
        db_table = 'api_agile_tag_relation_polymer'


    is_online = BooleanField(verbose_name=u"是否有效", default=True)
    create_time = DateTimeField(verbose_name=u'创建时间', auto_now_add=True)
    update_time = DateTimeField(verbose_name=u'更新时间', auto_now=True)
    agile_tag_id = IntegerField(verbose_name=u'新标签', db_index=True)
    polymer_id = IntegerField(verbose_name=u'聚合页id', db_index=True)



class PolymerContent(Model):
    class Meta:
        verbose_name = '运营推荐内容'

    polymer = ForeignKey(Polymer, related_name="recommends")
    rank = IntegerField('排序', default=100)
    content_type = CharField('推荐类型', max_length=30, choices=POLYMER_CONTENT_TYPE)
    content_id = CharField('内容ID', max_length=64)
    start_time = DateTimeField(verbose_name=u'开始时间', null=True)
    end_time = DateTimeField(verbose_name=u'结束时间', null=True)
    is_online = BooleanField(verbose_name=u'是否上下线', default=True)
    is_related_city = BooleanField(verbose_name=u'是否关联城市', default=False)
    cities = ManyToManyField(City, verbose_name=u'关联城市')

    def get_cities_name(self):
        return ','.join(list(self.cities.only('name').values_list('name', flat=True)))


class PolymerTab(Model):
    class Meta:
        verbose_name = '聚合tag类型是否展示'
        unique_together = (('polymer', 'tab_type'),)

    polymer = ForeignKey(Polymer, related_name="tabs")
    tab_type = IntegerField('tab类型', choices=POLYMER_DETAIL_TAB_TYPE)
    enable = BooleanField('上线', default=True)
    recommend = BooleanField('醒目推荐', default=False)


class PolymerExtra(Model):
    class Meta:
        verbose_name = '聚合页统计信息'

    polymer = ForeignKey(Polymer, related_name="extra", db_index=True)
    new_question_cnt = IntegerField('新增问题数', default=0)
    new_answer_cnt = IntegerField('新增回答数', default=0)
    new_reply_cnt = IntegerField('新增评论数', default=0)
    new_vote_cnt = IntegerField('新点赞数', default=0)
    total_cnt = IntegerField('新增指标总数', default=0)


class DeliverPolymer(Model):
    class Mate:
        verbose_name = '投稿小组'

    polymer = ForeignKey(Polymer, verbose_name='小组名称')
    rank = IntegerField(verbose_name='展示序列', default=999)
    deliver_count = IntegerField(verbose_name='投稿次数', default=0)
    is_online = BooleanField(verbose_name='是否在线', default=True)
