from django.db.models import Q
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from gm_types.mimas import QUALITY_QUESTION_CLASSIFY_TYPE
from gm_upload.utils.image_utils import Picture

from qa.models import QualityQuestionPool, QualityClassfyQuestion, QualityQuestionClassifyRelation, QualityUserQuestion, \
    QualityAuthorAnswer, QualityReply, QualityReplyImage
from talos.services import TagV3Service


class QualityQuestionPoolDB(DataBuilder):
    pass


@DB
class QualityQuestionPoolDQ(DataSQLQuery):
    model = QualityQuestionPool
    data_model = QualityQuestionPoolDB


class QualityClassfyQuestionDB(DataBuilder):

    def getval_classify_type(self, obj):
        return QUALITY_QUESTION_CLASSIFY_TYPE.getDesc(obj.classify_type)

    def getval_question_id(self, obj):
        classify_ids = list(QualityQuestionClassifyRelation.objects.filter(
            quality_classify_id=obj.id
        ).values_list('question_id', flat=True))
        titles = list(QualityQuestionPool.objects.filter(id__in=classify_ids).values_list('title', flat=True))
        return titles

    def getval_tag_id(self, obj):
        tag_id = obj.tag_id
        tag = TagV3Service.get_tags_by_tag_v3_ids([tag_id])
        tag_v3_info = TagV3Service.format_tag_v3(tag.get(tag_id))

        return tag_v3_info['name']


@DB
class QualityClassfyQuestionDQ(DataSQLQuery):
    model = QualityClassfyQuestion
    data_model = QualityClassfyQuestionDB

    def filter_tag_group_id(self, srch_key, srch_val, regex=False):
        return Q(tag_group_id=int(srch_val))

    def filter_tag_id(self, srch_key, srch_val, regex=False):
        return Q(tag_id=int(srch_val))

    def filter_question_id(self, srch_key, srch_val, regex=False):
        _ids = list(QualityQuestionPool.objects.filter(
            title__contains=srch_val
        ).values_list('id', flat=True))
        valid_ids = list(QualityQuestionClassifyRelation.objects.filter(
            question_id__in=_ids
        ).values_list('quality_classify_id', flat=True))
        return Q(id__in=valid_ids)


class QualityUserQuestionDB(DataBuilder):

    def getval_question_title(self, obj):
        quality_question = QualityQuestionPool.objects.filter(id=obj.question_id).first()
        title = quality_question and quality_question.title or ''
        return title

    def getval_author_reply_count(self, obj):       # 作者回复数
        return QualityAuthorAnswer.objects.filter(quality_question_id=obj.quality_question_id).count()

    def getval_reply_count(self, obj):              # 评论数
        return QualityReply.objects.filter(quality_question_id=obj.quality_question_id).count()


@DB
class QualityUserQuestionDQ(DataSQLQuery):
    model = QualityUserQuestion
    data_model = QualityUserQuestionDB

    def filter_question_title(self, srch_key, srch_val, regex=False):
        q_ids = list(QualityQuestionPool.objects.filter(
            title__contains=srch_val).values_list('id', flat=True)
                 )
        return Q(question_id__in=q_ids)


class QualityReplyDB(DataBuilder):

    def getval_quality_answer_content(self, obj):
        q = QualityAuthorAnswer.objects.filter(id=obj.quality_answer_id).first()

        return q and q.content or ''


@DB
class QualityReplyDQ(DataSQLQuery):
    model = QualityReply
    data_model = QualityReplyDB

    def filter_quality_answer_content(self, srch_key, srch_val, regex=False):
        q_ids = list(QualityAuthorAnswer.objects.filter(
            content__contains=srch_val
                 ).values_list('id', flat=True))
        return Q(quality_answer_id__in=q_ids)

    def filter_content(self, srch_key, srch_val, regex=False):
        return Q(content__contains=srch_val)

    @classmethod
    def create(cls, **kwargs):
        images = []
        user_id = kwargs.get('user_id')
        content = kwargs.get('content')
        quality_answer_id = kwargs.get('quality_answer_id')
        try:
            quality_question = QualityAuthorAnswer.objects.get(id=quality_answer_id)
        except QualityAuthorAnswer.DoesNotExist:
            return {
                'id': ''
            }

        is_online = kwargs.get('is_online')
        image1 = kwargs.get('image1')
        if image1:
            images.append(image1)
        image2 = kwargs.get('image2')
        if image2:
            images.append(image2)
        image3 = kwargs.get('image3')
        if image3:
            images.append(image3)

        quality_reply = QualityReply.objects.create(
            quality_answer_id=quality_answer_id,
            user_id=user_id,
            content=content,
            quality_question_id=quality_question.quality_question_id,
            is_online=is_online,
        )

        image_objects = []
        for image in images:
            try:
                image_info = Picture.get_image_base_info(image)
            except:
                image_info = {}
            qm = QualityReplyImage(
                quality_reply_id=quality_reply.id,
                url=image,
                width=image_info.get('width'),
                height=image_info.get('height'),
            )
            image_objects.append(qm)
        QualityReplyImage.objects.bulk_create(image_objects)

        return {
            'id': quality_reply.id
        }

    def update(self, updates, **kwargs):
        first_reply_id = kwargs.get('id')
        if not first_reply_id:
            return
        is_online = updates.get('is_online')
        if is_online is False or is_online is True:
            QualityReply.objects.filter(id=first_reply_id).update(is_online=is_online)
            return {
                'id': first_reply_id
            }

        images = []
        reply_user_id = updates.get('reply_user')
        reply_content = updates.get('reply_content')
        quality_answer_id = updates.get('quality_answer_id')
        quality_question_id = updates.get('quality_question_id')
        image1 = updates.get('image1')
        if image1:
            images.append(image1)
        image2 = updates.get('image2')
        if image2:
            images.append(image2)
        image3 = updates.get('image3')
        if image3:
            images.append(image3)
        quality_reply = QualityReply.objects.create(
            quality_answer_id=quality_answer_id,
            replied_id=first_reply_id,
            user_id=reply_user_id,
            content=reply_content,
            quality_question_id=quality_question_id,
        )

        image_objects = []
        for image in images:
            try:
                image_info = Picture.get_image_base_info(image)
            except:
                image_info = {}
            qm = QualityReplyImage(
                quality_reply_id=quality_reply.id,
                url=image,
                width=image_info.get('width'),
                height=image_info.get('height'),
            )
            image_objects.append(qm)
        QualityReplyImage.objects.bulk_create(image_objects)

        return {
            'id': quality_reply.id
        }


class QualityAuthorAnswerDB(DataBuilder):
    pass


@DB
class QualityAuthorAnswerDQ(DataSQLQuery):
    model = QualityAuthorAnswer
    data_model = QualityAuthorAnswerDB
