#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
#   Author  :   RobertDing
#   E-mail  :   robertdingx@gmail.com
#   Date    :   18/04/18 14:40:47
#   Desc    :   statistic query
#

from datetime import date, timedelta

from dateutil.rrule import rrule, MONTHLY

from django.db.models import Q

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

from gm_types.hera import MONTH_RANGE

from api.models import User
from hippo.models.businessdata import MerchantStatDailyData
from hippo.models.merchant import Merchant
from themis.models import Team


class MerchantStatDB(DataBuilder):
    def getval_ad_consume(self, item):
        # XXX 因为数据组给到的 `广告消耗值` 就是负的, 代表出账
        # 我们业务上需要一个`值`，只能取正
        return - item.ad_consume


@DB
class MerchantStatDailyDQ(DataSQLQuery):
    model = MerchantStatDailyData
    data_model = MerchantStatDB

    def filter_date_type(self, field, value, regex=False):
        today = date.today()
        yesterday = today - timedelta(days=1)
        dtstart = today - timedelta(days=300)
        month_days = list(rrule(freq=MONTHLY, bymonthday=-1, dtstart=dtstart, until=yesterday))
        days = {
            MONTH_RANGE.CURRENT: [yesterday],
            MONTH_RANGE.MONTH3: month_days[-3:],
            MONTH_RANGE.MONTH6: month_days[-6:],
        }.get(value, [yesterday])
        return Q(date__in=days)

    def filter_teams_team_id(self, filed, value, regex=False):
        teams = Team.objects.filter(id__in=value)
        return self._filter_by_teams(teams)

    def filter_teams_user_id(self, key, value, regex=False):
        teams = User.objects.get(id=value).teams.all()
        return self._filter_by_teams(teams)

    def _filter_by_teams(self, teams):
        if not teams:
            return Q()
        children = sum([list(x.all_children_team) + [x] for x in teams], [])
        team_ids = [x.id for x in children]
        merchants = Merchant.objects.filter(doctor__business_group__in=team_ids)
        return Q(merchant_id__in=[x.id for x in merchants])
