#coding=utf-8
import tablib
from django.conf import settings
from django.core.management import BaseCommand
from django.db.models import Sum
from gm_types.gaia import REFUND_STATUS
from helios import create_default_invoker

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


class Command(BaseCommand):
    """
    添加商户等级
    python manage.py merchant_add_level
    """
    def add_arguments(self, parser):
        parser.add_argument(
            '--start_time', type=str, help='开始时间', default= '2019-10-01 00:00:00'
        )
        parser.add_argument(
            '--end_time', type=str, help='开始时间', default= '2020-01-01 00:00:00'
        )
        parser.add_argument(
            '--month', type=float, help='月份', default= 3.0
        )


    def handle(self, start_time, end_time, month, **optioins):
        def get_level(score):
            if score < 100:
                return 'v1'
            elif score < 200:
                return 'v2'
            elif score < 400:
                return 'v3'
            elif score < 600:
                return 'v4'
            elif score < 1000:
                return 'v5'
            elif score < 2000:
                return 'v6'
            elif score >= 2000:
                return 'v7'

        dt_success = tablib.Dataset()
        dt_success.headers = (u'商户名称', u'商户id', u'验证GMV', u'商户广告消耗', u'级别(8:2)', u'级别(7:3)',u'级别(6:4)')
        data = Merchant.objects.all()
        doctor_ids = {}
        result = {}
        # 获取所有医生的id
        for i in data:
            key = i.id
            print(key)
            val = list(i.merchant_doctors.all().values_list('doctor_id'))
            doctor_ids_set = set()
            for item in val:
                doctor_ids_set.add(item[0])
            doctor_ids[str(key)] = list(doctor_ids_set)
            # 计算订单，买单，补单GMV
            # #订单
            orders = Order.objects.filter(service__doctor_id__in=doctor_ids_set, validate_time__gte=start_time, validate_time__lt=end_time, status=ORDER_STATUS.USED)
            res_dict = orders.aggregate(sum=Sum("service_price"))
            order_sum = res_dict.get("sum") if res_dict.get("sum") else 0.00
            # 买单
            res_dict = MaidanOrder.objects.filter(doctor_id__in=doctor_ids_set, payment_time__gte=start_time,
                                                  payment_time__lt=end_time,
                                                  status=ORDER_STATUS.PAID).aggregate(
                sum=Sum("maidan_price_cent"))
            maidan_sum = res_dict.get("sum") / 100 if res_dict.get("sum") else 0.00
            # 补单录入
            res_dict = BuDanLuRu.objects.filter(doctor_id__in=doctor_ids_set, 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") * 10 if res_dict.get("sum") else 0.00
            result[i.id] = (order_sum + maidan_sum + budanluru_sum) / (month * 1.0)
        # 按医生的维度获取GMV以及广告消耗
        # 初始化rpc对像
        invoker = create_default_invoker(debug=settings.DEBUG)
        rpc_client = invoker['artemis/account/accountflow/new_sum'](doctor_ids=doctor_ids,
                                                                start_time=start_time,
                                                                end_time=end_time)
        res = rpc_client.unwrap()
        # 计算商户得分
        for i in data:
            print(i.id)
            advertise_consume = res.get(str(i.id), 0.0) / (month * 1.0)
            GMV_count = result.get(i.id, 0.0)
            score1 = (GMV_count * 0.8 + advertise_consume * 0.2) * 0.00232558139534884
            score2 = (GMV_count * 0.7 + advertise_consume * 0.3) * 0.00232558139534884
            score3 = (GMV_count * 0.6 + advertise_consume * 0.4) * 0.00232558139534884
            level1, level2, level3 = get_level(score1), get_level(score2), get_level(score3)
            dt_success.append((i.name, str(i.id), GMV_count, advertise_consume, level1, level2, level3))
        get_mail('商户评级统计.xlsx', '商户GMV和广告消耗评级统计',['songzhenqi@igengmei.com', 'weiyujie@igengmei.com', 'zhangweinan@igengmei.com'], dt_success.xlsx).send()

