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

from datetime import date, timedelta

from django.db.models import Q
from gm_dataquery.db import DB
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery

from api.models import SmartRank, User
from statistic.models import StatisticServiceSmartRankV3
from ..utils import check_business, check_operate, operate_business
from ..models import UserPerm


class SmartRankDB(DataBuilder):

    def getval_smartrankv3_id(self, item):
        yesterday = date.today() - timedelta(days=1)
        q = Q(service_id=item.service_id, stat_date=yesterday)
        row = StatisticServiceSmartRankV3.objects.filter(q)
        if row.exists():
            return row.first().id
        return None


@DB
class SmartRankDQ(DataSQLQuery):
    model = SmartRank
    data_model = SmartRankDB

    def filter_is_zero(self, srch_key, srch_val, regex=False):
        q = Q(service__manualindex__index=0) | Q(service__manualindex__isnull=True)
        if srch_val == '0':
            return ~q
        else:
            return q

    def filter_check_groups(self, srch_key, srch_val, regex=False):
        user = User.objects.get(id=srch_val)
        groups = user.belong_groups.values_list('name', flat=True)
        if check_business(groups):
            # 判断是商务并且非商务leader
            members = UserPerm.members(user)
            return Q(service__doctor__business_partener__in=members)
        elif check_operate(srch_val):
            business_ids = operate_business(srch_val)
            return Q(service__doctor__business_partener__id__in=business_ids)
        else:
            return Q()
