# -*- coding: UTF-8 -*-
from __future__ import absolute_import
from django.db.models import Q
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB

from talos.models import Report
from gm_types.gaia import REPORT_REASON, REPORT_TYPE, REPORT_ACTIONS
from talos.services.user import UserService
from . import TalosDataSQLQuery


class ReportDB(DataBuilder):
    def getval_user_name(self, obj, default=''):
        user = UserService.get_user_by_user_id(obj.user_id)
        return user.nickname

    def getval_reason_text(self, obj):
        return REPORT_REASON.getDesc(obj.reason)

    def getval_text(self, obj):
        if obj.type == REPORT_TYPE.TOPIC:
            if obj.problem and obj.problem.user_id:
                if obj.problem.user_id == 22:
                    return obj.problem.ask if obj.problem else ''
            return obj.problem.answer if obj.problem else ''
        elif obj.type in [REPORT_TYPE.REPLY, REPORT_TYPE.DIARY_REPLY]:
            return obj.topic_reply.content if obj.topic_reply else ''

    def getval_related_user(self, obj):
        if obj.type == REPORT_TYPE.TOPIC:
            return obj.problem.user_id if obj.problem and obj.problem.user_id else ''
        elif obj.type in [REPORT_TYPE.REPLY, REPORT_TYPE.DIARY_REPLY]:
            return obj.topic_reply.user_id if obj.topic_reply and obj.topic_reply.user_id else ''

    def getval_related_user_name(self, obj):
        if obj.type == REPORT_TYPE.TOPIC:
            user = UserService.get_user_by_user_id(obj.problem.user_id)
        elif obj.type in [REPORT_TYPE.REPLY, REPORT_TYPE.DIARY_REPLY]:
            user = UserService.get_user_by_user_id(obj.topic_reply.user_id)
        return user.nickname

    def getval_action_text(self, obj):
        return REPORT_ACTIONS.getDesc(obj.action) if obj.action else u'已处理'

    def getval_text_id(self, obj):
        if obj.type == REPORT_TYPE.TOPIC:
            return obj.problem.id if obj.problem else ''
        elif obj.type in [REPORT_TYPE.REPLY, REPORT_TYPE.DIARY_REPLY]:
            return obj.topic_reply.id if obj.topic_reply else ''


@DB
class ReportDQ(TalosDataSQLQuery):
    model = Report
    data_model = ReportDB

    def filter_related_user(self, srch_key, srch_val, regex=False):
        user_id = srch_val
        q = Q(problem__user_id=user_id) | Q(topic_reply__user_id=user_id)
        return q
