#coding=utf-8
import datetime

import tablib
from django.conf import settings
from django.core.management import BaseCommand
from django.db.models import Sum
from gm_types.gaia import MERCHANT_LEVEL_NEW
from helios import create_default_invoker

from api.models import Order, ORDER_STATUS, BuDanLuRu, BUDAN_LURU_STATUS, BUDAN_LURU_TYPE
from hera.management.commands.utils import get_mail
from hippo.models import Merchant
from maidan.models import MaidanOrder
from themis.models import Team


class Command(BaseCommand):
    """
    商户抽成
    python manage.py export_merchant_discount_advertise
    """
    def add_arguments(self, parser):
        parser.add_argument(
            '--begin_time', type=str, help='开始时间', default= '2019-09-01 00:00:00'
        )
        parser.add_argument(
            '--end_time', type=str, help='开始时间', default= '2020-03-01 00:00:00'
        )
        parser.add_argument(
            '--month', type=float, help='月份', default= 6.0
        )

    def handle(self, begin_time, end_time, month, **optioins):
        dt_success = tablib.Dataset()
        start_time = datetime.datetime.strptime(begin_time, '%Y-%m-%d %H:%M:%S')
        discount_months = []
        advertise_discount_months = []
        k = 1
        discount_month = start_time.month
        for i in range(int(month)):
            if discount_month < 13:
                discount_months.append(u'抽成{}-{}'.format(start_time.year, discount_month))
                advertise_discount_months.append(u'广告消耗{}-{}'.format(start_time.year, discount_month))
                discount_month += 1
            else:
                discount_months.append(u'抽成{}-{}'.format(start_time.year + 1, k))
                advertise_discount_months.append(u'广告消耗{}-{}'.format(start_time.year + 1, k))
                discount_month += 1
                k += 1
        title = (u'商户名称', u'商户id' ,u'BD', u'BD组') + tuple(discount_months) + tuple(advertise_discount_months) + (u'商家等级', )
        dt_success.headers = title
        merchants = Merchant.objects.only('id')
        invoker = create_default_invoker(debug=settings.DEBUG)
        # 获取所有医生的id
        for merchant in merchants:
            key = merchant.id
            print(key)
            doctor_ids = list(merchant.merchant_doctors.all().values_list('doctor_id', flat=True))
            start_time = datetime.datetime.strptime(begin_time, '%Y-%m-%d %H:%M:%S')
            #按照月份循环查询，通过起始时间于结束时间选定单个月份
            discount_amount_ls = []
            for i in range(int(month)):
                if start_time.month < 12:
                    end_time = datetime.datetime(start_time.year, start_time.month + 1, start_time.day, 0, 0, 0)
                else:
                    end_time = datetime.datetime(start_time.year + 1, start_time.month - 11, start_time.day, 0, 0, 0)
                # 计算订单，买单，补单GMV
                #订单
                orders = Order.objects.filter(service__doctor_id__in=doctor_ids, validate_time__gte=start_time, validate_time__lt=end_time, status=ORDER_STATUS.USED)
                res_dict = orders.aggregate(sum=Sum("discount"))
                order_sum = res_dict.get("sum") if res_dict.get("sum") else 0.00
                # 买单
                res_dict = MaidanOrder.objects.filter(doctor_id__in=doctor_ids, payment_time__gte=start_time,
                                                      payment_time__lt=end_time,
                                                      status=ORDER_STATUS.PAID).aggregate(
                    sum=Sum("discount_cent"))
                maidan_sum = res_dict.get("sum") / 100.0 if res_dict.get("sum") else 0.00
                # 补单录入
                res_dict = BuDanLuRu.objects.filter(doctor_id__in=doctor_ids, created_time__gte=start_time,
                                                    created_time__lt=end_time, status=BUDAN_LURU_STATUS.ENTERED,
                                                    type=BUDAN_LURU_TYPE.COMMON).aggregate(sum=Sum("amount"))
                budanluru_sum = res_dict.get("sum") if res_dict.get("sum") else 0.00
                total_amount = order_sum + maidan_sum + budanluru_sum
                discount_amount_ls.append(total_amount)
                start_time = end_time
            try:
                user = merchant.doctor.business_partener
                business = user.username if not user.last_name or '***' in user.last_name else user.last_name
            except:
                business = ''
            try:
                team_name = Team.objects.get(id=merchant.doctor.business_group).name
            except:
                team_name = ''
            #广告消耗分月汇总
            rpc_client = invoker['artemis/account/accountflow/month_sum'](doctor_ids=doctor_ids, start_time=begin_time, month=month)
            res = rpc_client.unwrap()
            row_data = (merchant.name, str(merchant.id), business, team_name) + tuple(discount_amount_ls) + tuple(res) + (MERCHANT_LEVEL_NEW.getDesc(merchant.merchant_level), )
            dt_success.append(row_data)
        get_mail(u'商户抽成及广告消耗统计统计.xls', u'商户订单、买单、补单抽成以及广告消耗',[u'songzhenqi@igengmei.com', u'weiyujie@igengmei.com'], dt_success.xls).send()

