# -*- coding: UTF-8 -*-

from django.conf import settings
from django.db.models import Q
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from gm_types.gaia import USER_CLASSIFY

from talos.models.topic import TopicReply, ReplyHeadline
from statistic.models import ClassifyUser
from . import TalosDataSQLQuery


class TopicReplyDB(DataBuilder):
    def getval_user__last_name(self, obj):
        return obj.user.nickname

    def getval_problem_name(self, obj):
        name = obj.problem.title if obj.problem.title else obj.problem.ask
        if name:
            return name
        else:
            return u'查看详情'

    def getval_problem_info(self, obj):
        id = obj.problem.id
        name = obj.problem.title if obj.problem.title else obj.problem.ask or obj.problem.answer[:20]
        return {'id': id, 'text': name}

    def getval_diary_info(self, obj):
        id = obj.diary_id
        text = obj.diary.title
        return {'id': id, 'text': text}

    def getval_content(self, obj):
        return obj.content[:20] + '...' if len(obj.content) > 20 else obj.content

    def getval_doctor_info(self, obj):
        if getattr(obj, 'doctor', None):
            return {'id': obj.doctor.id, 'name': obj.doctor.name}
        else:
            return ''

    def getval_last_reply_time(self, obj):
        return str(obj.problem.topicreply_set.all().order_by("-id")[0].reply_date)

    def getval_is_headline(self, obj):
        return ReplyHeadline.objects.filter(reply=obj).exists()

    def getval_vote_num(self, obj):
        return obj.topicreplyvote_set.count() or 0


@DB
class TopicReplyDQ(TalosDataSQLQuery):
        model = TopicReply
        data_model = TopicReplyDB

        def filter_is_real(self, srch_key, srch_val, regex=False):
            user_ids = ClassifyUser.objects.using(
                settings.SLAVE_DB_NAME).filter(
                classify=USER_CLASSIFY.MODEL).values_list('user_id',
                                                          flat=True)
            q = Q(user_id__in=list(user_ids))
            if srch_val == u'1':
                return ~q
            else:
                return q

        def filter_problem_name(self, srch_key, srch_val, regex=False):
            return Q(problem__title__contains=srch_val) | Q(problem__ask__contains=srch_val)
