#!/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 gm_dataquery.dataquery import DataBuilder
from talos.models.topic import Activity, Problem
from gm_dataquery.db import DB
from . import TalosDataSQLQuery


class ActivityDB(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_topics_num(self, obj):
        return Problem.objects.filter(activity_id=obj.id).count()

    def getval_win_prize_num(self, obj):
        return obj.winners.count()

    def getval_description_richtext(self, obj, need_escape=False):
        return obj.description_richtext


@DB
class ActivityDQ(TalosDataSQLQuery):
    model = Activity
    data_model = ActivityDB

    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
