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

from django.db.models import Q
from gm_dataquery.db import DB
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery

from api.models import PrivateMessagePush
from gm_types.gaia import PRIVATE_MESSAGE_PUSH_STATUS
import datetime


class PrivateMessagepushDB(DataBuilder):
    def getval_target_name(self, obj):
        if obj.service_id:
            return obj.service.name
        elif obj.doctor_id:
            return obj.doctor.name
        elif obj.hospital_id:
            return obj.hospital.name
        elif obj.user_list:
            return '自由添加'
        else:
            return ''

    def getval_send_status(self, obj):
        now = datetime.datetime.now()
        send_time = obj.send_time
        if obj.status == PRIVATE_MESSAGE_PUSH_STATUS.OK:
            if send_time <= now:
                return u'已发送'
            else:
                return u'撤回'
        else:
            return u'未发送'

    def getval_send_time(self, obj):
        now = datetime.datetime.now()
        send_time = obj.send_time
        if obj.status == PRIVATE_MESSAGE_PUSH_STATUS.OK and now >= send_time:
            return send_time.strftime('%Y-%m-%d %H:%M:%S')
        else:
            return '--'


@DB
class PrivateMessagepushDQ(DataSQLQuery):
    model = PrivateMessagePush
    data_model = PrivateMessagepushDB

    def filter_send_time(self, srch_key, srch_val, regex=False):
        return self._qry_time_range(srch_key, srch_val, regex)

    def filter_person__user_id(self, srch_key, srch_val, regex=False):
        return Q(person__user__id__contains=srch_val)
