# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, print_function
import datetime
from django.db import models

from gm_types.wiki import TREATMENT_TYPE, ANESTHESIA_TYPE, ACHE_LEVEL_NEW
from wiki.models.video import VideoLibrary
from api.models.product import ProductWiki
from .types import TAG_TYPE
from api.models.wikitag import ItemTag, WordRel_wiki, Wiki_wordrelsynonym
from api.models import TREATMENT_MEANS_CHOICES
from wiki.models.item import ItemTag as old_tag
import traceback
import logging


class NewItemWiki(models.Model):
    class Meta:
        verbose_name = u'项目新百科'
        db_table = 'wiki_item'

    id = models.IntegerField(verbose_name=u'百科ID', primary_key=True)
    name = models.CharField(u'项目名称', max_length=48)
    other_name = models.CharField(u'项目别称', max_length=48)
    description = models.TextField(u'介绍')
    use_result = models.CharField(u'使用功效', max_length=128)
    treatment_method = models.CharField(u'治疗方式', max_length=8, choices=TREATMENT_MEANS_CHOICES)
    is_online = models.BooleanField(u'是否上线', default=True)
    create_time = models.DateTimeField(verbose_name=u'创建时间', default=datetime.datetime.fromtimestamp(0))

    def get_item_tag_id_type(self):

        try:
            association_tags_id_list = list()

            query_results = ItemTag.objects.filter(item_id=self.id)

            for item in query_results:
                association_tags_id_list.append({"is_effect": item.is_effect, "tag_id": item.wordrel_id})

            logging.info("get_item_tag_id_type:%s" % association_tags_id_list)

            return association_tags_id_list


        except:

            logging.error("catch exception,get  get_item_tag_id_type :%s" % traceback.format_exc())

            return []

    def get_item_keyword_id(self, association_tags_id_list):

        try:
            association_tags_list = list()

            for tags in association_tags_id_list:

                query_results = WordRel_wiki.objects.filter(id=tags.get('tag_id'))

                for items in query_results:
                    association_tags_list.append([items.id, items.keyword, tags.get('is_effect')])

            logging.info("get_item_keyword_id:%s" % association_tags_list)

            return association_tags_list

        except:
            logging.error("catch exception,err_msg:%s" % traceback.format_exc())
            return []

    def get_item_keyword(self, association_tags_list):

        try:
            association_keywords_list = list()

            for item in association_tags_list:

                logging.info("ididid:%s" % association_tags_list)

                query_results = set(
                    Wiki_wordrelsynonym.objects.filter(wordrel_id=item[0]).values_list("word", flat=True))
                if item[2]:
                    query_results.add(item[1])
                    association_keywords_list.extend(list(query_results))

            logging.info("get_brand_keyword:%s" % association_keywords_list)

            return association_keywords_list

        except:
            logging.error("catch exception,err_msg:%s" % traceback.format_exc())
            return []

    def get_item_related_product_id(self):

        try:
            related_product_id_list = list()

            query_results = Item_Product.objects.filter(item_id=self.id)

            for item in query_results:
                related_product_id_list.append(item.product_id)

            logging.info("related_product_id_list:%s" % related_product_id_list)

            return related_product_id_list

        except:
            logging.error("get_item_related_product_id" % traceback.format_exc())
            return []

    def get_related_product_id_type_list(self, related_product_id_list, type):

        try:
            related_product = list()

            for id in related_product_id_list:

                query_results = ProductWiki.objects.filter(id=id, product_type=type)

                for items in query_results:
                    related_product.append({"id": items.id, "name": items.name})

            logging.info("get_related_product_id_type_list:%s" % related_product)

            return related_product
        except:

            logging.error("catch exception,err_msg:%s" % traceback.format_exc())

            return []

    def get_old_tag_ids(self):
        try:
            old_tags_ids = list(old_tag.objects.filter(item=self.id).values_list("tag", flat=True))
            return old_tags_ids
        except:
            logging.error("catch exception,err_msg:%s" % traceback.format_exc())
            return []

    @property
    def get_item_old_tag(self):

        try:
            old_tag_names = list(
                old_tag.objects.filter(item=self.id,
                                       tag__tag_type__in=[TAG_TYPE.BODY_PART, TAG_TYPE.BODY_PART_SUB_ITEM,
                                                          TAG_TYPE.ITEM_WIKI],
                                       ).values_list(
                    "tag__name", flat=True))
            return old_tag_names

        except:
            logging.error("catch exception,err_msg:%s" % traceback.format_exc())
            return []

    @property
    def get_item_relation_keywords(self):
        association_keywords_set = set()
        # 先找关联的所有有效的词根id
        association_tags_id_list = list(ItemTag.objects.filter(
            item_id=self.id, is_effect=True).values_list("wordrel_id", flat=True))

        # 找这些词根的词
        word_root_list = list(WordRel_wiki.objects.filter(
            id__in=association_tags_id_list).values_list("keyword", flat=True))

        # 找词根关联的所有同义词
        query_synonym_list = list(Wiki_wordrelsynonym.objects.filter(
            wordrel_id__in=association_tags_id_list).values_list("word", flat=True))

        association_keywords_set.update(word_root_list)
        association_keywords_set.update(query_synonym_list)

        return list(association_keywords_set)

    @property
    def get_is_video(self):
        """
        判断该百科是否有视频
        :return:
        """
        try:
            bol = VideoLibrary.objects.filter(source_id=self.id, video_type=5)
            if len(bol):
                return True
            else:
                return False
        except:
            logging.error("catch exception,err_msg:%s" % traceback.format_exc())


class Item_Product(models.Model):
    class Meta:
        verbose_name = u'项目相关产品百科'
        db_table = 'wiki_item_related_product'

    item_id = models.IntegerField(verbose_name=u'项目ID', primary_key=True)
    product_id = models.IntegerField(verbose_name=u'产品ID', primary_key=True)
