# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, print_function

from django.db import models
from django.db.models import ForeignKey, IntegerField, CharField, TextField
from django.db.models import ManyToManyField, BooleanField, DateTimeField
from wiki.models.video import VideoLibrary

from gm_types.wiki import PRODUCT_TYPE, ATTESTATION_TYPE
from gm_types.wiki import PRODUCT_PARAMS, ANESTHESIA_TYPE, TREATMENT_TYPE
import logging, traceback
from api.models.brand import BrandWiki
from api.models.wikitag import ProductTag, WordRel_wiki, Wiki_wordrelsynonym
import datetime


class ProductWiki(models.Model):
    class Meta:
        verbose_name = u'物品百科'
        db_table = 'wiki_product'

    id = models.IntegerField(u"物品百科id", primary_key=True)
    name = models.CharField(u'物品名称', max_length=50)
    other_name = models.CharField(u'项目别称', max_length=48)
    product_type = models.CharField(u'物品类型', max_length=4)
    brand_id = models.IntegerField(u"商品id", null=True)
    description = models.TextField(u'项目描述', blank=True)
    special = models.TextField(u'特色')
    effect = models.CharField(u'功效', max_length=128)
    treatment_method = models.CharField(u'治疗方式', max_length=8, choices=TREATMENT_TYPE)
    is_online = models.BooleanField(u'是否上线', default=True)
    create_time = models.DateTimeField(verbose_name=u'创建时间', default=datetime.datetime.fromtimestamp(0))

    def get_product_params(self, params_type):
        try:
            params_message = list()

            query_results = ProductParams.objects.filter(product_id=self.id, params_type=params_type)

            for item in query_results:
                params_message.append(item.params_message)

            logging.info("get_product_params:%s" % params_message)

            return params_message

        except:

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

            return []

    def product_brand_info(self):

        try:

            related_brand_list = list()

            query_results = BrandWiki.objects.filter(id=self.brand_id)

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

            logging.info("product_brand_info:%s" % related_brand_list)

            return related_brand_list

        except:

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

            return None

    def get_product_tag_id_type(self):

        try:
            association_tags_id_list = list()

            query_results = ProductTag.objects.filter(product_id=self.id)

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

            return association_tags_id_list

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

    def get_product_keyword_id(self, association_tags_id_list):

        try:
            association_tags_list = list()

            for tags in association_tags_id_list:

                logging.info("ididid:%s" % 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')])

            return association_tags_list

        except:

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

            return []

    def get_product_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_id:%s" % association_keywords_list)

            return association_keywords_list

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

    @property
    def get_product_relation_keywords(self):
        association_keywords_set = set()
        # 先找关联的所有有效的词根id
        association_tags_id_list = list(ProductTag.objects.filter(
            product_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__in=[2, 3, 4])
            if len(bol):
                return True
            else:
                return False
        except:
            logging.error("catch exception,err_msg:%s" % traceback.format_exc())


class ProductParams(models.Model):
    class Meta:
        verbose_name = u'产品新百科物品参数'
        db_table = 'wiki_productpararms'

    product_id = models.IntegerField(u"产品新百科ID", primary_key=True)
    params_type = models.CharField(u'参数类型', max_length=8, choices=PRODUCT_PARAMS)
    params_message = CharField(u'参数内容', max_length=256, default='')
