# -*- coding: utf-8 -*-

import logging

from django.db.models import Sum
from django_six import CompatibilityBaseCommand, close_old_connections
from TimeConvert import TimeConvert as tc

from integral.models import SaleclerkSubmitLogInfo
from mch.models import BrandInfo, DistributorInfo, ModelInfo, SaleclerkInfo
from sales.models import SalesResponsibilityInfo, SalesResponsibilityInfoModelsSaleStatisticInfo, SuperSalesResponsibilityInfoModelsSaleStatisticInfo


logger = logging.getLogger('console')


class Command(CompatibilityBaseCommand):
    def handle(self, *args, **options):

        logger.info('Sales is dealing')

        close_old_connections()

        # year = tc.local_string(format='%Y')
        month = tc.local_string(format='%Y%m')
        day = tc.local_string(format='%Y%m%d')

        # lastyear = tc.local_string(tc.several_time_ago(years=1), format='%Y')
        lastmonth = tc.local_string(tc.several_time_ago(months=1), format='%Y%m')
        lastday = tc.local_string(tc.several_time_ago(days=1), format='%Y%m%d')

        brands = BrandInfo.objects.filter(status=True)

        for b in brands:
            SalesResponsibilityInfoModelsSaleStatisticInfo.objects.filter(brand_id=b.brand_id, ymd=day).delete()
            SuperSalesResponsibilityInfoModelsSaleStatisticInfo.objects.filter(brand_id=b.brand_id, ymd=day).delete()

            distributors = DistributorInfo.objects.filter(brand_id=b.brand_id, status=True)
            models = ModelInfo.objects.filter(brand_id=b.brand_id, status=True)
            for m in models:
                logs = SaleclerkSubmitLogInfo.objects.filter(model_pk=m.pk, dupload=False, test_sn=False, ym__gte=lastmonth, status=True)
                for d in distributors:
                    yesterday_num = 0
                    current_month = 0
                    last_month = 0
                    if logs.count() != 0:
                        saleclerks = SaleclerkInfo.objects.filter(brand_id=b.brand_id, distributor_id=d.distributor_id, status=True)
                        for saleclerk in saleclerks:
                            log = logs.filter(clerk_id=saleclerk.clerk_id)
                            yesterday_num += log.filter(ymd=lastday).count()
                            current_month += log.filter(ym=month).count()
                            last_month += log.filter(ym=lastmonth).count()

                    if m.is_important or (yesterday_num or current_month or last_month):
                        sale, _ = SalesResponsibilityInfoModelsSaleStatisticInfo.objects.get_or_create(
                            brand_id=b.brand_id,
                            sr_id=d.sr_id,
                            distributor_id=d.distributor_id,
                            model_name=m.model_uni_name,
                            ymd=day,
                        )
                        sale.distributor_name = d.distributor_name
                        sale.model_id = m.model_id
                        sale.is_important = m.is_important
                        sale.yesterday_num += yesterday_num
                        sale.current_month += current_month
                        sale.last_month += last_month
                        sale.save()

            srs = SalesResponsibilityInfo.objects.filter(brand_id=b.brand_id, status=True)
            for s in srs:
                if s.is_super:
                    continue
                sums = SalesResponsibilityInfoModelsSaleStatisticInfo.objects.filter(
                    sr_id=s.sr_id,
                    ymd=day,
                    status=True
                ).aggregate(
                    Sum('yesterday_num'),
                    Sum('current_month'),
                    Sum('last_month'),
                )
                yesterday_num = sums.get('yesterday_num__sum', 0) or 0
                current_month = sums.get('current_month__sum', 0) or 0
                last_month = sums.get('last_month__sum', 0) or 0
                SuperSalesResponsibilityInfoModelsSaleStatisticInfo.objects.create(
                    brand_id=b.brand_id,
                    sr_id=s.sr_id,
                    sr_name=s.name,
                    sr_avatar=s.avatar,
                    ymd=day,
                    yesterday_num=yesterday_num,
                    current_month=current_month,
                    last_month=last_month,
                )

        close_old_connections()
