#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
#   Author  :   RobertDing
#   E-mail  :   robertdingx@gmail.com
#   Date    :   16/03/28 15:04:46
#   Desc    :   医生端活动
#
from __future__ import absolute_import, division, with_statement
from datetime import datetime

from django.db.models import Q

from doctor.models.activity import DoctorActivity, ActivityParticipate
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB


class DoctorActivityDB(DataBuilder):
    def getval_content__title(self, obj):
        return obj.content.title

    def getval_activity_status(self, obj):
        if obj.is_online:
            now = datetime.now()
            if now < obj.begin_time:
                return u'即将开始'
            elif now < obj.end_time:
                return u'正在进行'
            else:
                return u'已经结束'
        else:
            return u'下线'

    def getval_participate_num(self, obj):
        return obj.activityparticipate_set.count()


@DB
class DoctorActivityDQ(DataSQLQuery):
    model = DoctorActivity
    data_model = DoctorActivityDB


class ActivityParticipateDB(DataBuilder):
    def getval_doctor__id(self, obj):
        return obj.doctor.id

    def getval_doctor__name(self, obj):
        return obj.doctor.name

    def getval_doctor__hospital(self, obj):
        hospital = obj.doctor.hospital
        return hospital.name if hospital else ""

    def getval_doctor__business_partner(self, obj):
        partener = obj.doctor.business_partener
        return partener.name if partener else ""


@DB
class ActivityParticipateDQ(DataSQLQuery):
    model = ActivityParticipate
    data_model = ActivityParticipateDB

    def filter_doctor_has_online_services(self, srch_key, srch_val, regex):
        try:
            self.distinct = True
            q = Q(doctor__services__is_online=True)
            val = bool(int(srch_val))
            if not val:
                q = ~q
            return q
        except ValueError:
            return Q()
