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

from django.db.models import Q, Max, Min, Count
from gm_types.gaia import CASH_BACK_STATUS, SERVICE_FLAG
from gm_dataquery.db import DB
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery

from gm_types.gaia import SERVICE_SELL_TYPE
from api.models import Service


class ServiceDB(DataBuilder):

    def getval_diary(self, obj):
        return obj.diary_set.distinct().count()

    def getval_order_cashback(self, obj):
        return obj.order_set.filter(cash_back_status=CASH_BACK_STATUS.SUCCESS).count()

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

    def getval_service_type_desc(self, obj):
        return SERVICE_SELL_TYPE.getDesc(obj.service_type)

    def getval_hospital__name(self, obj):
        return obj.hospital.name if hasattr(obj, 'hospital') and obj.hospital else ''

    def getval_dr_or_hosp(self, obj):
        val = ''
        if obj.service_flag == SERVICE_FLAG.HOSPITAL:
            val = obj.hospital.name if obj.hospital else ''
        else:
            val = obj.doctor.name if obj.doctor else ''
        return val

    def getval_discount(self, obj):
        if obj.is_multiattribute:
            return obj.items.aggregate(discount=Min('discount')).get('discount')
        else:
            return obj.discount

    def getval_pre_payment_price(self, obj):
        if obj.is_multiattribute:
            preprice_min = obj.items.aggregate(pre=Min('pre_payment_price')).get('pre')
            preprice_max = obj.items.aggregate(pre=Max('pre_payment_price')).get('pre')
            return '{}~{}'.format(preprice_min, preprice_max)
        else:
            return obj.pre_payment_price

    def getval_gengmei_price(self, obj):
        if obj.is_multiattribute:
            gengmei_min = obj.items.aggregate(gm=Min('gengmei_price')).get('gm')
            gengmei_max = obj.items.aggregate(gm=Max('gengmei_price')).get('gm')
            return '{}~{}'.format(gengmei_min, gengmei_max)
        else:
            return obj.gengmei_price

    def getval_high_com_service(self, obj):
        return obj.service_type == 2


@DB
class ServiceDQ(DataSQLQuery):
        model = Service
        data_model = ServiceDB

        def build_order(self, qs, orders=None):
            if not orders:
                return qs
            order_fields = []
            order_opts = orders
            order_diary = False
            if order_opts:
                order_fields = ['-%s' % (o['name']) if o['dir'] == 'desc' else o['name']
                                for o in order_opts]
                order_fields = []
                for o in order_opts:
                    if o['name'] == 'diary':
                        order_diary = True
                        of = '-diary_count' if o['dir'] == 'desc' else 'diary_count'
                        order_fields.append(of)
                    else:
                        order_fields.append('-%s' % (o['name']) if o['dir'] == 'desc' else o['name'])
            if order_diary:
                qs = qs.annotate(diary_count=Count('diary', distinct=True))

            qs = qs.distinct().order_by(*order_fields)
            return qs

        def filter_high_com_service(self, key, value, regex=False):
            q = Q(service_type=SERVICE_SELL_TYPE.FENGXIANGGOU)
            if not int(value):
                q = ~q
            return q

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

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

        def filter_tags(self, srch_key, srch_val, regex=False):
            return Q(tags__id=srch_val)

        def filter_new_tags(self, srch_key, srch_val, regex=False):
            return Q(new_tags__id=srch_val)

        def filter_itemwiki(self, srch_key, srch_val, regex=False):
            return Q(serviceitemwiki__itemwiki_id=srch_val)
