# -*- coding: UTF-8 -*-

from collections import defaultdict

from django.db.models import Q

from api.services.face.plastic import page_instance
from api.models.wordrel import WordRel, WordRelSynonym, RecommendWords, WordGroup

from rpc.decorators import bind


@bind('api/keywords/iter')
def get_keywords(last_max_id=-1, count=10):
    word_objs = list(WordRel.objects.filter(id__gt=last_max_id).order_by('id')[:(count + 1)])

    result = dict()
    result['keywords'] = []
    result['has_next'] = len(word_objs) == (count + 1)

    word_objs = word_objs[:count]

    for obj in word_objs:
        item = {
            'id': obj.id,
            'keyword': obj.keyword,
            'resembles': list(obj.all_resembles.all().values_list('word', flat=True))
        }

        result['keywords'].append(item)

    return result


@bind('api/wordrel/synonym')
def get_keywords(word):
    """
    通过一个词获取它的所有同义词
    :param word:
    :return:
    """
    if WordRelSynonym.objects.filter(word=word).exists():
        keyword = WordRelSynonym.objects.filter(word=word).first().wordrel
        data = keyword.synonyms_word_list()
    else:
        data = []
    return data


@bind('api/tag/add_word_group')
def add_word_group(recommend_words=None, kernel_recommend_word=None, word_group_id=None):
    """增加词组 如果有词组id，则增加词组联想词"""
    if not word_group_id:
        word_group = WordGroup()
        word_group.is_deleted = 0
        word_group.save()
        word_group_id = word_group.id

    if isinstance(recommend_words, list):
        for recommend_word in recommend_words:
            rw = RecommendWords.objects.filter(
                word_group_id=word_group_id,
                thesaurus=recommend_word,
                is_kernel=0
            ).first()
            if not rw:
                rw = RecommendWords()
                rw.word_group_id = word_group_id
                rw.thesaurus = recommend_word
                rw.is_kernel = 0
            rw.is_deleted = 0
            rw.save()

    if kernel_recommend_word:
        rw = RecommendWords.objects.filter(
            word_group_id=word_group_id,
            thesaurus=kernel_recommend_word
        ).first()

        rw_kernel = RecommendWords.objects.filter(
            word_group_id=word_group_id,
            is_kernel=1
        ).first()
        if not rw and not rw_kernel:
            rw = RecommendWords()
            rw.word_group_id = word_group_id
            rw.thesaurus = kernel_recommend_word
            rw.is_deleted = 0
            rw.is_kernel = 1
            rw.save()
        elif rw and not rw_kernel:
            rw.is_kernel = 1
            rw.is_deleted = 0
            rw.save()
        elif not rw and rw_kernel:
            rw_kernel.thesaurus = kernel_recommend_word
            rw_kernel.is_deleted = 0
            rw_kernel.save()
        else:
            if rw.id == rw_kernel.id:
                rw.is_deleted = 0
                rw.save()
            else:
                rw.is_kernel = 1
                rw.is_deleted = 0
                rw.save()
                rw_kernel.is_kernel = 0
                rw_kernel.is_deleted = 0
                rw_kernel.save()

    return {"id": word_group_id}


@bind('api/tag/delete_word_group')
def delete_word_group(word_group_ids, recommend_words_ids):
    """删除词组，或者词组下面对应的联想词"""
    if len(word_group_ids) == 1 and recommend_words_ids:
        # 只批量删除某个词组下面的联想词
        RecommendWords.objects.filter(
            word_group_id=word_group_ids[0],
            id__in=recommend_words_ids
        ).update(is_deleted=1)
    else:
        # 批量删除词组
        WordGroup.objects.filter(id__in=word_group_ids).update(is_deleted=1)
        RecommendWords.objects.filter(word_group_id__in=word_group_ids).update(is_deleted=1)
    return word_group_ids


@bind('api/tag/get_word_group')
def get_word_group(search_word=None, page=1, page_size=10):
    """获取词组列表"""
    recommend_word_group_ids = None
    if search_word:
        recommend_words = RecommendWords.objects.filter(
            thesaurus__contains=search_word, is_deleted=0
        )
        recommend_word_group_ids = set([rw.word_group_id for rw in recommend_words])

    filters = [Q(is_deleted=0)]
    if recommend_word_group_ids:
        filters.append(Q(id__in=list(recommend_word_group_ids)))

    word_group_objs = WordGroup.objects.filter(*filters)
    word_group_info = page_instance(word_group_objs, page, page_size)
    page_info = {
        "page": page,
        "page_size": word_group_info["page_size"],
        "total_count": word_group_info["total_count"],
        "total_page_num": word_group_info["total_page_num"],
    }

    word_group_ids = []
    for wg in word_group_info["data"]:
        word_group_ids.append(wg.id)

    groups_recommend_words = RecommendWords.objects.filter(word_group_id__in=word_group_ids, is_deleted=0)
    word_groups_dict = defaultdict(list)
    kernel_word_groups_dict = defaultdict(list)
    for grw in groups_recommend_words:
        if grw.is_kernel:
            kernel_word_groups_dict[grw.word_group_id].append(grw.thesaurus)
        else:
            word_groups_dict[grw.word_group_id].append(grw.thesaurus)

    word_groups = list()
    for wid in word_group_ids:
        rws = ",".join(word_groups_dict.get(wid, []))
        krws = ",".join(kernel_word_groups_dict.get(wid, []))
        word_groups.append(
            {
                "id": wid,
                "recommend_words": rws,
                "kernel_recommend_words": krws,
            }
        )

    return {"page_info": page_info, "word_group": word_groups}


@bind('api/tag/get_recommend_words')
def get_recommend_words(word_group_id, page=1, page_size=10):
    """获取联想词列表"""
    recommend_words = RecommendWords.objects.filter(
        word_group_id=word_group_id, is_deleted=0
    )

    recommend_words_info = page_instance(recommend_words, page, page_size)
    page_info = {
        "page": page,
        "page_size": recommend_words_info["page_size"],
        "total_count": recommend_words_info["total_count"],
        "total_page_num": recommend_words_info["total_page_num"],
    }

    recommend_words_result = list()
    for word in recommend_words_info["data"]:
        recommend_words_result.append(
            {
                "id": word.id,
                "thesaurus": word.thesaurus,
                "is_kernel": word.is_kernel
            }
        )
    return {"page_info": page_info, "recommend_words": recommend_words_result}


# 搜索页面根据搜索词获取推荐词
@bind('api/search/recommend_words')
def get_recommend_words(search_word):
    recommend_words = RecommendWords.objects.filter(
        thesaurus=search_word, is_deleted=0, is_kernel=1
    )
    words = []
    word_group_ids = []
    for rw in recommend_words:
        word_group_ids.append(rw.word_group_id)

    group_recommend_words = RecommendWords.objects.filter(
        word_group_id__in=word_group_ids,
        is_deleted=0
    )
    for rw in group_recommend_words:
        if rw.thesaurus == search_word:
            continue

        words.append({
            "id": rw.id,
            "thesaurus": rw.thesaurus
        })
    return words
