# -*- coding: utf-8 -*-
import json

from gm_types.error import ERROR
from gm_types.gaia import (
    AI_QA_NEXT_TYPE,
    AI_QA_ANSWER_TYPE,
)

from launch.models import (
    Theme,
    AIQuestion,
    AIAnswer,
    AIAnswerTag,
    AIQuestion2Answer,
)
from rpc.decorators import bind
from rpc.tool.error_code import gen


@bind('hera/ai_qa/theme/detail')
def modify_theme_get(theme_id=None):
    if not theme_id:
        return {}

    try:
        theme = Theme.objects.get(id=theme_id)
    except Theme.DoesNotExist:
        return gen(ERROR.THEME_NOT_FOUND)

    data = {
        'id': theme.id,
        'title': theme.title,
        'ass_uid': theme.ass_uid,
        'is_online': theme.is_online,
        'first_welcome_contents': theme.first_welcome_contents,
        'redo_welcome_contents': theme.redo_welcome_contents,
        # 'conclusion': theme.conclusion,
        'entrance_question_id': theme.entrance_question_id,
    }

    return {'data': data}


@bind('hera/ai_qa/theme/modify')
def modify_theme_edit(theme_info, theme_id=None):

    result = {
        'error': 0,
        'message': '创建成功',
        'data': ''
    }

    if theme_id:
        try:
            theme = Theme.objects.get(id=theme_id)
        except:
            return {
                'error': 1,
                'message': '创建失败，当前主题不存在',
                'data': ''
            }
        theme.title = theme_info["title"]
        theme.ass_uid = theme_info["ass_uid"]
        theme.is_online = theme_info.get("is_online", False)
        theme.first_welcome_contents = theme_info.get("first_welcome_contents", "")
        theme.redo_welcome_contents = theme_info.get("redo_welcome_contents", "")
        # theme.conclusion = theme_info.get("conclusion", None)
        theme.entrance_question_id = theme_info.get("entrance_question_id", None)
        theme.save()
    else:
        theme = Theme(
            title=theme_info["title"],
            ass_uid=theme_info["ass_uid"],
            is_online=theme_info.get("is_online", False),
            first_welcome_contents=theme_info.get("first_welcome_contents", ""),
            redo_welcome_contents=theme_info.get("redo_welcome_contents", ""),
            # conclusion=theme_info.get("conclusion", None),
            entrance_question_id=theme_info.get("entrance_question_id", None),
        )
        theme.save()

    result['data'] = theme.id

    return result


@bind('hera/ai_qa/question/detail')
def modify_question_get(question_id=None):
    if not question_id:
        return {}

    try:
        question = AIQuestion.objects.get(id=question_id)
    except Theme.DoesNotExist:
        return gen(ERROR.QUESTION_NOT_FOUND)

    data = {
        'id': question.id,
        'title': question.title,
        'question_type': question.question_type,
        "relation_answers": []
    }

    for relation in AIQuestion2Answer.objects.filter(ai_question_id=question_id).order_by("rank"):
        try:
            answer = AIAnswer.objects.get(id=relation.ai_answer_id, is_online=True)
        except:
            continue
        info = {
            "id": answer.id,
            "answer_related_tags": list(AIAnswerTag.objects.filter(ai_answer_id=answer.id).values_list("tag_id", flat=True)),
            "rank": relation.rank,
            "next_type": relation.next_type,
            "answer_content": answer.title,
            "answer_color": answer.color,
            'ai_qa_answer_type': answer.answer_type,  # 回答类型
        }
        try:
            relation_data = json.loads(relation.relation_data)
            if "reco_popup_type" not in relation_data:
                relation_data["reco_popup_type"] = int(relation_data.get("scheme_popup", False))

        except:
            relation_data = {}
        info.update(relation_data)
        data["relation_answers"].append(info)

    return {'data': data}


@bind('hera/ai_qa/question/modify')
def modify_question_edit(question_info, question_id=None):

    result = {
        'error': 0,
        'message': '创建成功',
        'data': ''
    }

    if question_id:
        try:
            question = AIQuestion.objects.get(id=question_id)
        except:
            return {
                'error': 1,
                'message': '创建失败，当前主题不存在',
                'data': ''
            }
        question.title = question_info["title"]
        question.question_type = question_info["question_type"]
        question.save()
    else:
        question = AIQuestion(
            title=question_info["title"],
            question_type=question_info["question_type"],
        )
        question.save()

    result['data'] = question.id

    return result


@bind('hera/ai_qa/answer/delete')
def modify_question_edit(answer_id):

    result = {
        'error': 0,
        'message': '删除成功',
        'data': ''
    }

    if answer_id:
        try:
            answer = AIAnswer.objects.get(id=answer_id)
        except:
            return {
                'error': 1,
                'message': '删除失败',
                'data': ''
            }
        answer.is_online = False
        answer.save()

    return result


@bind('hera/ai_qa/question/answer/modify')
def modify_question_edit(related_answers, question_id):

    result = {
        'error': 0,
        'message': '创建成功',
        'data': ''
    }

    if not question_id:
        gen(ERROR.INVALID_PARAMS)

    try:
        AIQuestion.objects.get(id=question_id)
    except:
        gen(ERROR.QUESTION_NOT_FOUND)

    for info in related_answers:
        answer_id = info["answer_id"]
        answer_content = info["answer_content"]
        answer_color = info["answer_color"]
        answer_type = info.get("ai_qa_answer_type", AI_QA_ANSWER_TYPE.NORMAL)
        if not answer_id:
            answer = AIAnswer(
                title=answer_content,
                color=answer_color,
                answer_type=answer_type
            )
            answer.save()
        else:
            try:
                answer = AIAnswer.objects.get(id=answer_id)
            except:
                gen(ERROR.ANSWER_NOT_FOUND)
            answer.color = answer_color
            answer.title = answer_content
            answer.answer_type = answer_type
            answer.save()

        # update tag
        answer_related_tags = info.get("answer_related_tags", []) or []
        answer_related_tags = list(map(int, answer_related_tags))
        tag_pks = list(AIAnswerTag.objects.filter(ai_answer_id=answer.id).values_list("tag_id", flat=True))
        creat_pks = set(answer_related_tags) - set(tag_pks)
        delete_pks = set(tag_pks) - set(answer_related_tags)
        AIAnswerTag.objects.bulk_create([
            AIAnswerTag(ai_answer_id=answer.id, tag_id=tag_id)
            for tag_id in creat_pks
        ])
        AIAnswerTag.objects.filter(ai_answer_id=answer.id, tag_id__in=delete_pks).delete()

        # update relations
        relation, _ = AIQuestion2Answer.objects.update_or_create(
            ai_question_id=question_id, ai_answer_id=answer.id, defaults={"rank":info["rank"]}
        )
        relation.next_type = int(info["next_type"])
        if relation.next_type == AI_QA_NEXT_TYPE.AI_QUESTION:
            relation.relation_data = json.dumps({
                "question_id": info.get("ai_question_id")
            })
        else:
            relation.relation_data = json.dumps({
                "reco_desc": info.get("recommend_content"),
                "follow_group_id": info.get("question_group_id"),
                "reco_card_ids": info.get("recommendcard_ids"),
                # "scheme_popup": info.get("scheme_popup", False),  # 这个字段废弃了!
                "reco_popup_type": info.get("reco_popup_type", 0) or 0,  # 方案弹窗类型
            })
        relation.save()

    result['data'] = question_id

    return result
