import json

from gm_types.mimas import QUALITY_QUESTION_CLASSIFY_TYPE
from gm_upload.utils.image_utils import Picture

from qa.models import QualityClassfyQuestion, QualityQuestionClassifyRelation, QualityUserQuestion, QualityAuthorAnswer, \
    QualityAuthorAnswerImage, QualityQuestion, Answer, QualityQuestionPool
from talos.rpc import bind_context


@bind_context('mimas/question_quality_get')
def get_question_quality(ctx, question_quality_id):

    try:
        quality_classify_question = QualityClassfyQuestion.objects.get(id=question_quality_id)
    except QualityClassfyQuestion.DoesNotExist:
        return {}
    result = {
        'classify_type': quality_classify_question.classify_type,
        'tag_id': quality_classify_question.tag_id,
        'tag_group_id': quality_classify_question.tag_group_id,
        'is_online': quality_classify_question.is_online,
        'questions': [],
    }
    # 查询时保证一下顺序
    related_questions = list(QualityQuestionClassifyRelation.objects.filter(
        quality_classify_id=quality_classify_question.id
    ).order_by('id').values_list('question_id', flat=True))

    if not related_questions:
        return result

    result['questions'] = related_questions

    return result


@bind_context('mimas/question_quality_edit')
def question_quality_edit(ctx, data=None, question_quality_id=None):
    result = {
        'classify_type': int(data.get('classify_type')),
        'tag_id': data.get('tag_id'),
        'tag_group_id': data.get('tag_group_id'),
        'is_online': data.get('is_online'),
    }
    question_ids = data.get('question_ids', [])
    if not question_quality_id:
        quality_classify_question = QualityClassfyQuestion.objects.create(**result)
        for _id in question_ids:
            QualityQuestionClassifyRelation.objects.create(
                quality_classify_id=quality_classify_question.id, question_id=_id
            )
    else:
        quality_classify_question = QualityClassfyQuestion.objects.get(id=question_quality_id)
        if result['classify_type'] == QUALITY_QUESTION_CLASSIFY_TYPE.COMMON:
            result['tag_id'] = None
            result['tag_group_id'] = None
        elif result['classify_type'] == QUALITY_QUESTION_CLASSIFY_TYPE.TAG:
            result['tag_group_id'] = None
        elif result['classify_type'] == QUALITY_QUESTION_CLASSIFY_TYPE.TAG_GROUP:
            result['tag_id'] = None

        for k, v in result.items():
            setattr(quality_classify_question, k, v)
        quality_classify_question.save()
        QualityQuestionClassifyRelation.objects.filter(
            quality_classify_id=quality_classify_question.id
        ).delete()
        for _id in question_ids:
            QualityQuestionClassifyRelation.objects.create(
                quality_classify_id=quality_classify_question.id, question_id=_id
            )

    return {
        'data': quality_classify_question.id
    }


@bind_context('mimas/get_author_comments')
def get_author_comments(ctx, answer_id, question_id):
    """
    获取回答下 指定追问问题下的 所有作者回复
    :param ctx:
    :param answer_id: table api_answer
    :param question_id:  table api_quality_question_pool
    :return:
    """
    if not all([answer_id, question_id]):
        return {}
    try:
        question = QualityQuestionPool.objects.get(id=question_id)
        question_title = question.title
    except QualityQuestionPool.DoesNotExist:
        question_title = ''
    quality_question_ids = list(QualityUserQuestion.objects.filter(
        answer_id=answer_id, question_id=question_id
    ).values_list('quality_question_id', flat=True))
    if not quality_question_ids:
        return {}
    author_replies = QualityAuthorAnswer.objects.filter(
        quality_question_id__in=quality_question_ids
    ).values('id', 'content', 'is_online')
    result = []
    for reply in author_replies:
        _id = reply['id']
        images = list(QualityAuthorAnswerImage.objects.filter(
            quality_answer_id=_id
        ).values_list('url', flat=True))
        result.append({
            'content': reply['content'],
            'images': images,
            'is_online': reply['is_online'],
            'id': reply['id'],
        })

    return {
        'quality_questions': result,
        'question_title': question_title,
    }


@bind_context('mimas/quality_question/author_reply')
def hera_fake_author_comment(ctx, answer_id, question_id, data):
    """
    hera 给提问创建回复
    :param ctx:
    :param data:
    :param answer_id: table api_answer
    :param question_id:  table api_quality_question_pool
    :return:
    """
    result = {
        'data': '',
        'error': 0,
        'message': ''
    }
    content = data.get('content', '')
    images = json.loads(data.get('images', '[]'))
    if not all([answer_id, question_id, content]):
        return result
    try:
        answer = Answer.objects.get(id=answer_id)
    except Answer.DoesNotExist:
        return result

    quality_question = QualityQuestion.objects.filter(
        answer_id=answer_id, question_id=question_id
    ).first()
    if not quality_question:
        return result

    author_reply = QualityAuthorAnswer.objects.create(
        quality_question_id=quality_question.id,
        content=content,
        user_id=answer.user_id,
        is_online=True,
    )

    image_objects = []
    for image in images:
        image_info = Picture.get_image_base_info(image)
        q = QualityAuthorAnswerImage(
            quality_answer_id=author_reply.id,
            url=image,
            width=image_info.get('width'),
            height=image_info.get('height'),
        )
        image_objects.append(q)
    QualityAuthorAnswerImage.objects.bulk_create(image_objects)

    return result
