#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
from __future__ import absolute_import, division, with_statement
from datetime import datetime

from django.db.models import Q

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

from api.models.freerecruitment import FreeRecruitmentUser, FreeRecruitment, AssistanceUser, FreeRecruitmentDiary, \
    FreeRecruitmentDoctor, FreeRecruitmentImage


class FreeRecruitmentDB(DataBuilder):
    def getval_status(self, obj):
        now = datetime.now()
        if now < obj.start_time:
            return u'即将开始'
        elif now <= obj.end_time:
            return u'正在进行'
        else:
            return u'已经结束'

    def getval_enrolment_num(self, obj):
        return FreeRecruitmentUser.objects.filter(freerecruitment_id=obj.id).count()

    def getval_diary_id(self, obj):
        return list(FreeRecruitmentDiary.objects.filter(freerecruitment_id=obj.id).values_list('diary_id', flat=True))

    def getval_doctor_id(self, obj):
        return list(FreeRecruitmentDoctor.objects.filter(freerecruitment_id=obj.id).values_list('doctor_id', flat=True))

    def getval_banner_image(self, obj):
        return list(FreeRecruitmentImage.objects.filter(freerecruitment_id=obj.id).values_list('image', flat=True))

@DB
class FreeRecruitmentDQ(DataSQLQuery):
    model = FreeRecruitment
    data_model = FreeRecruitmentDB

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

    def filter_order_status(self, srch_key, srch_val, regex=False):
        now = datetime.now()
        srch_val = str(srch_val)
        if srch_val == '0':
            q = Q(start_time__gt=now)
        elif srch_val == '1':
            q = Q(start_time__lte=now) & Q(end_time__gte=now)
        elif srch_val == '2':
            q = Q(end_time__lt=now)
        else:
            q = Q()
        return q


class FreeRecruitmentUserDB(DataBuilder):
    pass

@DB
class FreeRecruitmentUserDQ(DataSQLQuery):
    model = FreeRecruitmentUser
    data_model = FreeRecruitmentUserDB


class AssistanceUserDB(DataBuilder):
    pass

@DB
class AssistanceUserDQ(DataSQLQuery):
    model = AssistanceUser
    data_model = AssistanceUserDB

