# coding=utf-8

import json
from django.db.models import Q

from gm_dataquery.client import rpc

from qa.models import (
    KolQuestion,
    KolAnswer,
    Question,
    Answer,
    TouTiaoTag,
    ToutiaoRelation,
    KolAnswerRelationTag,
)
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from gm_types.mimas import ASSESSMENT_TYPE

from ..views.common import get_tag_id_by_name


class KolQuestionDB(DataBuilder):
    def getval_is_review(self, obj):
        if obj.question_id:
            return True
        else:
            return False

    def getval_vast_name(self, obj):
        if obj.question_id:
            return Question.objects.get(id=obj.question_id).user.nickname
        return ''

@DB
class KolQuestionDQ(DataSQLQuery):
    model = KolQuestion
    data_model = KolQuestionDB

    def update(self, updates, **kwargs):
        kol_obj = KolQuestion.objects.get(**kwargs)
        kolanswer = KolAnswer.objects.get(kol_question_id=kol_obj.original_id)
        kolanswer.question_id = updates['question_id']
        kolanswer.save()
        return super().update(updates, **kwargs)

    def filter_catch_time(self, srch_key, srch_val, regex=False):
        return self._qry_time_range(srch_key, srch_val, regex)

    def filter_is_review(self, srch_key, srch_val, regex=False):
        q = Q(question_id__isnull=False)
        if srch_val == '0':
            return ~q
        else:
            return q

    def filter_user_id(self, srch_key, srch_val, regex=False):
        vast_id = Question.objects.filter(user__nickname=srch_val).value_list('user_id', flat=True)
        return Q(vast_id__in=vast_id)


class KolAnswerDB(DataBuilder):

    def get_new_related_tag(self, kol_answer_id):
        tag_ids = KolAnswerRelationTag.objects.filter(
            kol_answer_id=kol_answer_id).values_list("tag_id", flat=True)
        return list(tag_ids)

    def get_related_tag(self, tag_list):
        """
        根据抓取标签,去映射标签库获取对应标签库的id
        :param tag_list:
        :return:
        """
        tag_id_list = []
        for tag_name in tag_list:
            try:
                related_tag_ids = list(
                    TouTiaoTag.objects.get(toutiao=tag_name, is_online=True).relationtags.values_list('tag', flat=True)
                )
            except Exception:
                related_tag_ids = []
            tag_id_list.extend(related_tag_ids)
        return list(set(tag_id_list))

    def getval_is_review(self, obj):
        if obj.answer_id or obj.article_id:
            return True
        else:
            return False

    def getval_vast_name(self, obj):
        user = rpc.gaia.user
        user.fields = ['id', 'last_name']
        return user.get(id=obj.vast_id)['last_name']

    def getval_question_title(self, obj):
        return KolQuestion.objects.get(original_id=obj.kol_question_id, platform=obj.platform).title

    def getval_content(self, obj, need_escape=False):
        return obj.content

    def getval_tags_id(self, obj):
        # if obj.tags:
        #     tags = json.loads(obj.tags)
        #     tag_id_list = self.get_related_tag(tags)
        #     return tag_id_list
        # return []
        return self.get_new_related_tag(obj.id)

    def getval_kolanswer_has_title(self, obj):
        if obj.title or obj.kol_question_id or obj.question_id:
            return True
        else:
            return False

    def getval_kol_source_question(self, obj):
        try:
            title = KolQuestion.objects.get(original_id=obj.kol_question_id).title
        except:
            title = ''
        return title


@DB
class KolAnswerDQ(DataSQLQuery):
    model = KolAnswer
    data_model = KolAnswerDB

    def filter_catch_time(self, srch_key, srch_val, regex=False):
        return self._qry_time_range(srch_key, srch_val, regex)

    def filter_is_review(self, srch_key, srch_val, regex=False):
        q = Q(question_id__isnull=False) | Q(article_id__isnull=False)
        if srch_val == '0':
            return ~q
        else:
            return q

    def filter_kolanswer_has_title(self, srch_key, srch_bal, regex=False):
        q = Q(title__isnull=False) | Q(kol_question_id__isnull=False) | Q(question_id__isnull=False)
        if srch_bal == "0":
            return ~q
        else:
            return q

    def filter_question_title(self, srch_key, srch_val, regex=False):
        questions = KolQuestion.objects.filter(title__contains=srch_val)
        return Q(kol_question_id__in=[x.original_id for x in questions])

    def filter_tags_id(self, srch_key, srch_val, regex=False):
        kol_answer_ids = KolAnswerRelationTag.objects.filter(tag_id=int(srch_val)).values_list('kol_answer_id', flat=True)
        return Q(id__in=kol_answer_ids)

    def update(self, updates, **kwargs):
        answer_id = updates.pop('answer_id', None)
        image = updates.get('image', None)
        tags_id = updates.pop('tags_id', None)
        is_star = updates.pop('is_star', None)
        check_type = updates.get('check_type', '0')
        article_id = updates.pop('article_id', None)
        vast_id = updates.get('vast_id')
        obj = KolAnswer.objects.get(**kwargs)

        if tags_id:
            old_tags = set(KolAnswerRelationTag.objects.filter(kol_answer_id=obj.id).values_list('tag_id', flat=True))
            new_tags = set(map(int, tags_id))

            for tag in (new_tags - old_tags):
                KolAnswerRelationTag.objects.get_or_create(
                    kol_answer_id=obj.id,
                    tag_id=tag
                )
            KolAnswerRelationTag.objects.filter(
                kol_answer_id=obj.id,
                tag_id__in=(old_tags - new_tags)
            ).delete()

        if check_type == ASSESSMENT_TYPE.SPECIALCOLUMN:
            obj.check_type = check_type
            obj.vast_id = vast_id
            obj.article_id = article_id   # 专栏类型 审核通过保存专栏ID
            obj.save()
            return {'article_id': article_id, 'type': check_type}
        else:
            obj.check_type = check_type
            obj.vast_id = vast_id
            obj.save()
            return {'answer_id': obj.answer_id, 'type': check_type}
