# coding=utf-8
from django.db.models import Count, Q

from api.models import ServiceReserve
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from rpc.tool.dict_mixin import to_dict


class ServiceReserveDB(DataBuilder):
    """
    ServiceReserveDB实体的返回数据格式
    """

    def build_obj_data(self, obj, fields):
        """
        obj是dict,所以可以直接赋值
        """
        if obj.get('service__sell_num_limit', None) is not None:
            if obj['service__sell_num_limit'] > 0:
                obj['service__sell_num_limit'] = u'售卖中'
            else:
                obj['service__sell_num_limit'] = u'缺货中'
        else:
            obj['service__sell_num_limit'] = u'售卖中'
        obj['created_time'] = u''
        obj['service__doctor__hospital__city__province'] = u''
        obj['service__doctor__hospital__city'] = u''
        obj['service__is_online'] = u'是' if obj['service__is_online'] else u'否'
        obj['service__sellcount_changetime'] = str(obj['service__sellcount_changetime'])[0:19] if \
            obj['service__sellcount_changetime'] else u''
        return obj

    def getval_service__is_online(self, object):
        return u'是' if object.service.is_online else u'否'

    def getval_sellcount_changetime(self, obj):
        if obj.service.sellcount_changetime:
            return str(obj.service.sellcount_changetime)[0:19]


@DB
class ServiceReserveDQ(DataSQLQuery):
    """
    ServiceReserveDB实体查询过滤
    """
    model = ServiceReserve
    data_model = ServiceReserveDB

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

    def build_queryset(self, search=None, filters=None, nfilters=None, orders=None):
        qs = super(ServiceReserveDQ, self).build_queryset(search, filters, nfilters, orders)
        qs = qs.values(
            'service__name',
            'service__id',
            'service__doctor__hospital__name',
            'service__doctor__name',
            'service__doctor__business_partener__username',
            'service__sell_num_limit',
            'service__is_online',
            'service__sellcount_changetime'
        ).annotate(count=Count('service__id'))
        return qs

    # def filter_service__sell_num_limit(self, srch_key, srch_val, regex=False):
    #     if srch_val == '1':
    #         return Q(service__sell_num_limit__lte=0)  # 小于等于0
    #     elif srch_val == '0':
    #         return Q(service__sell_num_limit__gt=0)  # 大于0
