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

from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB

from api.models import Conversation, User


class ConversationDB(DataBuilder):
    def getval_last_info(self, obj):
        return {'id': obj.id, 'last_msg_content_disp': obj.last_msg_content_disp or '-'}

    def getval_user_ids(self, obj):
        user_ids = [x.user_id for x in obj.user_status_set.all()]
        users = User.objects.filter(id__in=user_ids)
        return [{'id': user.id, 'last_name': user.last_name} for user in users]

    def getval_last_state(self, obj):
        last_user_id = obj.message_set.order_by('send_time').last().user_id
        last_user = User.objects.get(id=last_user_id)
        if getattr(last_user, 'doctor', None):
            return u'已回复'
        else:
            return u'未处理'


@DB
class ConversationDQ(DataSQLQuery):
    model = Conversation
    data_model = ConversationDB
    distinct = True
