# -*- coding: UTF-8 -*-
from django.db import models
from gm_types.gaia import WORDREL_CATEGORY
from gm_types.error import ERROR
from rpc.exceptions import GaiaRPCFaultException


class WordRel(models.Model):
    class Meta:
        app_label = 'api'

    keyword = models.CharField(u'关键字', max_length=50)
    category = models.CharField(u'分类', max_length=5, choices=WORDREL_CATEGORY)
    created_time = models.DateTimeField(verbose_name=u'创建时间', auto_now_add=True)
    updated_time = models.DateTimeField(verbose_name=u'最后更新时间', auto_now=True)

    @classmethod
    def check_constraint(cls, words, wordrel_id=None):
        check_qs = WordRelSynonym.objects.filter(word__in=words)
        if wordrel_id is not None:
            check_qs = check_qs.exclude(wordrel_id=wordrel_id)
        exist_words = check_qs.values_list('word', flat=True)
        if exist_words:
            raise GaiaRPCFaultException(
                error=ERROR.UNIVERSAL,
                message=u'[%s]已存在' % (','.join(exist_words)),
                data=None
            )

    def synonyms(self):
        return self.all_synonyms.all()

    def resembles(self):
        return self.all_resembles.all()

    def synonyms_word_list(self, exclude_keyword=False):
        synonyms = self.synonyms()
        if exclude_keyword:
            synonyms = synonyms.exclude(word=self.keyword)

        return [o.word for o in synonyms]

    def resembles_word_list(self):
        return [o.word for o in self.resembles()]

    @property
    def synonyms_string(self):
        synonym_list = self.synonyms_word_list(exclude_keyword=True)
        return u','.join(synonym_list)

    @property
    def resembles_string(self):
        return u','.join(self.resembles_word_list())

    def save_synonym_words(self, words):
        old_words = set(self.synonyms_word_list())
        new_words = set([w for w in words if w])
        add_words = new_words - old_words
        del_words = old_words - new_words
        # 新增
        for w in add_words:
            o, is_create = WordRelSynonym.objects.get_or_create(
                word=w,
                defaults={'wordrel': self}
            )
        # 删除
        self.synonyms().filter(word__in=del_words).delete()

    def save_resemble_words(self, words):
        old_words = set(self.resembles_word_list())
        new_words = set([w for w in words if w])
        add_words = new_words - old_words
        del_words = old_words - new_words
        # 新增
        WordRelResemble.objects.bulk_create([
            WordRelResemble(wordrel=self, word=w) for w in add_words
        ])
        # 删除
        self.resembles().filter(word__in=del_words).delete()


class WordRelSynonym(models.Model):
    """同义词数据表,keyword 也会保存到这个表里
    """
    class Meta:
        app_label = 'api'

    wordrel = models.ForeignKey(WordRel, related_name='all_synonyms')
    word = models.CharField(u'同义词', max_length=50, unique=True, db_index=True)


class WordRelResemble(models.Model):
    """近义词数据表
    """
    class Meta:
        app_label = 'api'

    wordrel = models.ForeignKey(WordRel, related_name='all_resembles')
    word = models.CharField(u'近义词', max_length=50, db_index=True)


class WordGroup(models.Model):
    """
    搜索词组表
    """
    class Meta:
        app_label = "api"
        db_table = 'word_group'

    id = models.AutoField(verbose_name=u"主键", primary_key=True)
    is_deleted = models.IntegerField(verbose_name=u"是否删除")
    create_time = models.DateTimeField(
        verbose_name=u"创建时间", auto_now_add=True, db_column="create_time"
    )
    update_time = models.DateTimeField(
        verbose_name=u"更新时间", auto_now=True, db_column="update_time"
    )


class RecommendWords(models.Model):
    """
    搜索关联词表
    """
    class Meta:
        app_label = "api"
        db_table = 'recommend_words'

    id = models.AutoField(verbose_name=u"主键", primary_key=True)
    word_group_id = models.IntegerField(verbose_name=u"词组id")
    thesaurus = models.CharField(
        verbose_name=u"同义词", max_length=64, default="")
    is_kernel = models.IntegerField(verbose_name=u"是否是核心词")
    is_deleted = models.IntegerField(verbose_name=u"是否删除")
    create_time = models.DateTimeField(
        verbose_name=u"创建时间", auto_now_add=True, db_column="create_time"
    )
    update_time = models.DateTimeField(
        verbose_name=u"更新时间", auto_now=True, db_column="update_time"
    )
