# coding:utf-8
"""标签3.0"""

from django.db import models
from django.utils import timezone

from gm_types.gaia import TAG_TYPE_ATTR, TAG_V3_TYPE, TAG_RELATED_WIKI_TYPE


class StrategyContentTagV3(models.Model):
    class Meta:
        verbose_name = u'标签3.0'
        db_table = 'strategy_content_tagv3_info'

    content_id = models.IntegerField(verbose_name=u'内容id')
    content_type = models.CharField(verbose_name=u'内容类型', max_length=128, null=False)
    second_demands = models.CharField(verbose_name=u'二级诉求', max_length=128, default='')
    second_solutions = models.CharField(verbose_name=u'一级药品仪器耗材', max_length=128, default='')
    second_positions = models.CharField(verbose_name=u'二级部位', max_length=128, default='')
    first_demands = models.CharField(verbose_name=u'一级诉求', max_length=128, default='')
    first_solutions = models.CharField(verbose_name=u'一级方式', max_length=128, default='')
    first_positions = models.CharField(verbose_name=u'一级部位', max_length=128, default='')
    project_tags = models.CharField(verbose_name=u'项目标签', max_length=128, default='')
    project_tags_ids = models.CharField(verbose_name=u'项目标签', max_length=128, default='')
    first_classify_ids = models.CharField(verbose_name=u'一级分类id', max_length=128, default='')
    second_classify_ids = models.CharField(verbose_name=u'二级分类id', max_length=128, default='')
    first_classify_names = models.CharField(verbose_name=u'一级分类名称', max_length=128, default='')
    second_classify_names = models.CharField(verbose_name=u'二级分类名称', max_length=128, default='')
    stat_date = models.CharField(verbose_name=u'统计日期', max_length=128, null=False)


class StrategyServiceTagV3(models.Model):
    class Meta:
        verbose_name = u'标签3.0'
        db_table = 'strategy_service_tagv3_info'

    service_id = models.IntegerField(verbose_name=u'美购id')
    second_demands = models.CharField(verbose_name=u'二级诉求', max_length=128, default='')
    second_solutions = models.CharField(verbose_name=u'一级药品仪器耗材', max_length=128, default='')
    second_positions = models.CharField(verbose_name=u'二级部位', max_length=128, default='')
    first_demands = models.CharField(verbose_name=u'一级诉求', max_length=128, default='')
    first_solutions = models.CharField(verbose_name=u'一级方式', max_length=128, default='')
    first_positions = models.CharField(verbose_name=u'一级部位', max_length=128, default='')
    project_tags = models.CharField(verbose_name=u'项目标签', max_length=128, default='')
    first_classify_ids = models.CharField(verbose_name=u'一级分类id', max_length=128, default='')
    second_classify_ids = models.CharField(verbose_name=u'二级分类id', max_length=128, default='')
    first_classify_names = models.CharField(verbose_name=u'一级分类名称', max_length=128, default='')
    second_classify_names = models.CharField(verbose_name=u'二级分类名称', max_length=128, default='')
    stat_date = models.CharField(verbose_name=u'统计日期', max_length=128, null=False)

class ServiceNewTag(models.Model):
    class Meta:
        verbose_name = u'美购新标签关联表'
        db_table = 'api_servicenewtag'
    service_id = models.IntegerField(verbose_name=u'美购id')
    tag_id = models.IntegerField(verbose_name=u'标签id')

class BaseModel(models.Model):
    class Meta:
        abstract = True

    is_online = models.BooleanField(verbose_name=u"是否有效", default=True)
    create_time = models.DateTimeField(verbose_name=u'创建时间', auto_now_add=True)
    update_time = models.DateTimeField(verbose_name=u'更新时间', auto_now=True)


class TagV3(BaseModel):
    class Meta:
        verbose_name = u'标签3.0'
        unique_together = [
            ('name', 'tag_type'),
        ]
        db_table = 'api_tag_3_0'

    name = models.CharField(verbose_name=u'标签名字', max_length=128, null=False, default='')
    homoionym = models.CharField(verbose_name=u'近义词', max_length=1024, db_index=True)
    is_display = models.BooleanField(verbose_name=u"是否显示", default=True)
    tag_type = models.IntegerField(verbose_name=u'标签分类', default=TAG_V3_TYPE.NORMAL)
    doctor_display = models.BooleanField(verbose_name=u'医生后台是否可见', default=False)
    is_using_ai = models.BooleanField(verbose_name=u'用于AI', default=False)

    @property
    def children_tags(self):
        return TagV3Relation.objects.filter(parent=self, is_online=True)

    @property
    def parents_tags(self):
        return TagV3Relation.objects.filter(child=self, is_online=True)

    def child_new_tags_with_condition_is_online(self, is_online, ordering=False):
        if is_online:
            children_relations = TagV3Relation.objects.filter(parent=self, is_online=True, child__is_display=True)
            tags_list = [r.child for r in children_relations]
        else:
            children_relations = TagV3Relation.objects.filter(parent=self, child__is_display=True)
            tags_list = [r.child for r in children_relations]
        return tags_list


class TagMapTag(BaseModel):
    """
    三级标签 -- 三级其他类别标签的关联  不涉及一、二级分类
    """

    class Meta:
        verbose_name = verbose_name_plural = "标签3.0关联关系"
        unique_together = [
            ('tag_id', 'related_tag_id'),
        ]
        db_table = 'api_tag_map_tag'

    tag_id = models.IntegerField('标签ID', db_index=True)
    related_tag_id = models.IntegerField('关联的标签ID', db_index=True)


class TagV3Relation(BaseModel):
    """
    一级分类-->二级分类-->三级标签
    """

    class Meta:
        verbose_name = verbose_name_plural = "标签3.0关联关系"
        unique_together = [
            ('parent', 'child'),
        ]
        db_table = 'api_tag_v3_relation'

    parent = models.ForeignKey(TagV3, related_name='children_relations')
    child = models.ForeignKey(TagV3, related_name='parents_relations')

    @classmethod
    def add_relation(cls, parent, child):
        obj, created = cls.objects.get_or_create(parent=parent, child=child)
        if not obj.is_online:
            obj.is_online = True
            obj.save()
        return obj

    @classmethod
    def del_relation(cls, parent, child):
        cls.objects.filter(parent=parent, child=child).update(is_online=False)


class TagV3MapAttrTag(BaseModel):
    class Meta:
        verbose_name = u'标签和属性标签映射关系'
        db_table = 'api_tag_attr_tag'

    tag_id = models.IntegerField(verbose_name=u'标签ID', null=False)
    tag_attr_id = models.IntegerField(verbose_name=u"属性标签")


class TagExtra(BaseModel):
    class Meta:
        verbose_name = u'标签统计信息'
        db_table = 'api_tag_extra'

    aggregate_type = models.CharField(verbose_name=u"集合类型", max_length=3, choices=TAG_TYPE_ATTR)
    count = models.IntegerField(verbose_name=u'数量', null=False)
    tag_id = models.IntegerField(verbose_name=u'标签ID', null=False)


class TagSynonym(BaseModel):
    class Meta:
        verbose_name = u'标签集合'
        db_table = 'api_tag_aggregate'

    name = models.CharField(verbose_name=u'同义词名称', max_length=128, db_index=True)
    tag_id = models.IntegerField(verbose_name=u'标签ID', null=False)
    tag_type = models.IntegerField(verbose_name=u'分类', choices=TAG_V3_TYPE, default=TAG_V3_TYPE.NORMAL)


class TagMapOldTag(BaseModel):
    class Meta:
        verbose_name = u'新标签与老标签映射关系(可多选)'
        db_table = 'api_tag_map_oldtag'

    tag_id = models.IntegerField(verbose_name=u'标签3.0', db_index=True)
    old_tag_id = models.IntegerField(verbose_name=u'老标签', db_index=True)

    @classmethod
    def add_relation_by_id(cls, old_tag_id, tag_id):
        rel, _ = cls.objects.update_or_create(old_tag_id=old_tag_id, tag_id=tag_id, defaults={'is_online': True})
        return rel


class AttrTag(BaseModel):
    class Meta:
        verbose_name = u'属性标签'
        db_table = 'api_tag_attr'

    name = models.CharField(verbose_name=u'名称', max_length=128, null=False, db_index=True, default='')
    homoionym = models.CharField(verbose_name=u'近义词', max_length=1024, db_index=True)
    is_using_ai = models.CharField(verbose_name=u'用于AI', max_length=1024)
    aggregate_type = models.CharField(verbose_name=u"集合类型", max_length=3, choices=TAG_TYPE_ATTR,
                                      default=TAG_TYPE_ATTR.SYMPTOM)
    sub_attr_type = models.CharField(u'子属性的类型', choices=TAG_TYPE_ATTR, default=TAG_TYPE_ATTR.DRUG, max_length=3)

    @classmethod
    def get_section_tags(cls):
        """问题部位:Hera-标签管理-一级部位，过滤掉关联标签数为0的部位
            :engineer 20200225: zhengwei@igengmei.com
        """
        attrs = cls.objects.filter(aggregate_type=TAG_TYPE_ATTR.FIRST_POSITION, is_online=1)
        attr_ids = [attr.id for attr in attrs]
        links = TagV3MapAttrTag.objects.filter(tag_attr_id__in=attr_ids)
        no_zero_attrs = set()
        [no_zero_attrs.add(link.tag_attr_id) for link in links]
        section_tags = []
        for attr in attrs:
            if attr.id in no_zero_attrs:
                section_tag = {
                    "id": attr.id,
                    "name": attr.name
                }
                section_tags.append(section_tag)

        return section_tags

    @classmethod
    def get_improve_appeals(cls, section_tag_ids):
        """「改善诉求」的数据来源为：Hera-标签管理-二级诉求，过滤掉关联标签数为0的诉求，
        「改善诉求」的选项仅受「问题部位」影响，也就是取跟选中「问题部位」关联的「改善诉求」
            :engineer 20200225: zhengwei@igengmei.com
        """
        links = TagV3MapAttrTag.objects.filter(tag_attr_id__in=section_tag_ids)
        tag_ids = set()
        [tag_ids.add(link.tag_id) for link in links]
        appeal_links = TagV3MapAttrTag.objects.filter(tag_id__in=list(tag_ids))
        attr_ids = set()
        [attr_ids.add(link.tag_attr_id) for link in appeal_links]
        attrs = cls.objects.filter(id__in=list(attr_ids), aggregate_type=TAG_TYPE_ATTR.SECOND_APPEAL)
        improve_appeals = [{"id": attr.id, "name": attr.name} for attr in attrs]
        return improve_appeals

    @classmethod
    def section_tag_data(cls, section_tag_id):
        try:
            item = cls.objects.get(id=section_tag_id, aggregate_type=TAG_TYPE_ATTR.FIRST_POSITION)
            data = {
                "id": item.id,
                "name": item.name
            }
        except cls.DoesNotExist:
            data = {}
        return data

    @classmethod
    def improve_appeal_data(cls, improve_appeal_id):
        try:
            item = cls.objects.get(id=improve_appeal_id, aggregate_type=TAG_TYPE_ATTR.SECOND_APPEAL)
            data = {
                "id": item.id,
                "name": item.name
            }
        except cls.DoesNotExist:
            data = {}
        return data


class TagAttrRelation(BaseModel):
    """
    一级属性-->二级属性 关联
    """

    class Meta:
        verbose_name = verbose_name_plural = "属性关联"
        unique_together = [
            ('parent', 'child'),
        ]
        db_table = 'api_tag_attr_relation'

    parent = models.ForeignKey(AttrTag, related_name='children_relations')
    child = models.ForeignKey(AttrTag, related_name='parents_relations')

    @classmethod
    def add_relation(cls, parent, child):
        obj, created = cls.objects.get_or_create(parent=parent, child=child)
        if not obj.is_online:
            obj.is_online = True
            obj.save()
        return obj

    @classmethod
    def del_relation(cls, parent, child):
        cls.objects.filter(parent=parent, child=child).update(is_online=False)


class AttrTagSynonym(BaseModel):
    class Meta:
        verbose_name = u'属性标签同义词'
        db_table = 'api_tag_attr_synonym'

    tag_attr_id = models.IntegerField(verbose_name=u'标签ID', null=False, db_index=True)
    name = models.CharField(verbose_name=u'同义词名称', max_length=128, db_index=True)


class TagCategory(BaseModel):
    class Meta:
        verbose_name = u'标签3.0大类'
        db_table = 'api_tag_category'

    name = models.CharField(verbose_name=u'大类名称', max_length=128, db_index=True)


class TagCategoryMapTag(BaseModel):
    class Meta:
        verbose_name = u'标签3.0大类'
        db_table = 'api_tag_category_tag'

    tag_id = models.IntegerField(verbose_name=u'新标签ID', db_index=True)
    tag_category_id = models.IntegerField(verbose_name=u"标签大类id", db_index=True)


class TagV3WikiRelation(models.Model):
    """
    属性标签--百科关联
    """

    class Meta:
        db_table = 'api_tag_wiki'

    attr_tag_id = models.IntegerField(verbose_name='关联属性标签ID')
    wiki_id = models.IntegerField(verbose_name='关联百科ID')
    wiki_type = models.CharField(verbose_name='百科类型', choices=TAG_RELATED_WIKI_TYPE, max_length=2)


class TagMapCity(BaseModel):
    """ 城市标签映射 """
    class Meta:
        db_table = 'api_tag_city'

    tag_id = models.IntegerField('标签id', db_index=True)
    city_id = models.CharField('城市id', db_index=True, max_length=40)
