# coding:utf-8
import json
import datetime
from django.db.models import Max, Sum

from api.models import OrderCouponInfo
from api.models.types import ORDER_STATUS, PAYMENT_TYPE
from api.tasks.export_excel_task import export_orders_excel
from django.db.models import Q
from rpc.tool.queryset_tool import queryset_dec
from gm_types.gaia import OPERATION_LOCATION_TYPE
from api.tasks.export_excel_task import export_self_support_excel
__author__ = 'Zyy'

# ##### temp feature by ceo, roll back soon  -- zcy
# dt = datetime.date(2016, 6, 1)
# check_q = Q(created_time__gte=dt)
# check_q_for_refund_cashback = Q(created_at__gte=dt)
# check_msg = u'数据不全'
# ##### end #####


class OrderAction:
    @staticmethod
    def stat_trade(orders):
        """
        统计交易额
        """
        orders = orders.exclude(service__payment_type=PAYMENT_TYPE.FREE_PAYMENT)
        orders = orders.exclude(service__payment_type=PAYMENT_TYPE.EXCHANGE_GIFT)

        # ##### temp feature #####
        # if orders.filter(check_q).exists():
        #     return {'gengmei_price': check_msg}
        # ##### end #####

        # 统计更美价最高价
        #gengmei_price_sum = 0
        #gengmei_price_sum += orders.filter(service__is_multiattribute=True)\
        #                        .annotate(p=Max('service__items__gengmei_price'))\
        #                        .aggregate(t=Sum('p')).get('t') or 0
        #gengmei_price_sum += orders.filter(service__is_multiattribute=False)\
        #                        .aggregate(t=Sum('service__gengmei_price')).get('t') or 0
        #gengmei_price_sum = orders.aggregate(t=Sum('service__fake_price')).get('t') or 0
        ##### comment, return back soon #####
        gengmei_price_sum = orders.filter(servicesnapshot__isnull=False).\
                                aggregate(t=Sum(u'servicesnapshot__max_gengmei_price')).get('t') or 0
        ##### end #####
        # 统计美购最高价ceiling_price
        # ceiling_price_sum = orders.aggregate(t=Sum('service__ceiling_price')).get('t') or 0

        return {
            "gengmei_price": gengmei_price_sum,
            # "ceiling_price": ceiling_price_sum,
        }

    @staticmethod
    def stat_pre_payment_price(orders):
        """
        统计预付款
        """

        # ##### temp feature #####
        # if orders.filter(check_q).exists():
        #     return {
        #         'pre_payment_price': check_msg,
        #         'real_payment': check_msg,
        #     }
        # ##### end #####

        # 实际付款额分两部分统计，2061-3-1以前的用payment统计，之后的按real_payment 统计
        # real_payment 扣除了美券和美分，但是在2016-3-1之后才生效
        time_point = datetime.date(2016, 3, 1)
        real_payment = 0
        real_payment += orders.filter(created_time__gte=time_point).aggregate(s=Sum('real_payment')).get('s') or 0
        real_payment += orders.filter(created_time__lt=time_point).aggregate(s=Sum('payment')).get('s') or 0
        return {
            "pre_payment_price": orders.aggregate(fee=Sum('servicesnapshot__pre_payment_price')).get('fee') or 0,
            "real_payment": real_payment,
        }

    @staticmethod
    def stat_cashback_fee(cashback_orders):
        # ##### temp feature #####
        # if cashback_orders.filter(check_q_for_refund_cashback).exists():
        #     return {
        #         'fee': check_msg,
        #     }
        # ##### end #####

        return {
            "fee": cashback_orders.aggregate(fee=Sum('fee')).get('fee'),
        }

    @staticmethod
    def stat_refund_fee(refund_orders):
        # ##### temp feature #####
        # if refund_orders.filter(check_q_for_refund_cashback).exists():
        #     return {
        #         'fee': check_msg,
        #     }
        # ##### end #####

        fees = [refund_order.fee or refund_order.estimated_fee for refund_order in refund_orders]
        return {
            "fee": sum(fees),
        }

    @staticmethod
    def stat_exact_trade(orders):
        """
        统计准确交易额
        """
        # 排除掉免费和礼品换购类型的订单
        orders = orders.exclude(service__payment_type=PAYMENT_TYPE.FREE_PAYMENT)
        orders = orders.exclude(service__payment_type=PAYMENT_TYPE.EXCHANGE_GIFT)

        # ##### temp feature #####
        # if orders.filter(check_q).exists():
        #     return {
        #         'gengmei_price': check_msg,
        #     }
        # ##### end #####


        gengmei_price = orders.filter(servicesnapshot__isnull=False).\
                            aggregate(t=Sum(u'servicesnapshot__gengmei_price')).get('t') or 0
        return {
            "gengmei_price": gengmei_price,
        }

    @staticmethod
    def stat_discount(orders):
        """
        统计抽成
        """
        # ##### temp feature #####
        # if orders.filter(check_q).exists():
        #     return {
        #         'discount': check_msg,
        #     }
        # ##### end #####

        return {
            "discount": orders.aggregate(discount=Sum('discount')).get('discount'),
        }

    @staticmethod
    def stat_settle(orders):
        """
        统计结算
        """
        # ##### temp feature #####
        # if orders.filter(check_q).exists():
        #     return {
        #         'settle_price': check_msg,
        #     }
        # ##### end #####

        discount = orders.aggregate(discount=Sum('discount')).get('discount')
        pre_payment_price_sum = orders.filter(servicesnapshot__isnull=False).aggregate(
            t=Sum('servicesnapshot__pre_payment_price')).get('t') or 0
        coupons = OrderCouponInfo.objects.filter(order_id__in=[x.id for x in orders]) or []
        coupon_doctor_value_sum = sum([x.coupon_doctor_value for x in coupons])
        return {
            "settle_price": pre_payment_price_sum - coupon_doctor_value_sum - discount,
        }

    @staticmethod
    def set_settled(orders):
        """
        标记为已结算
        """
        num = orders.count()
        orders = orders.filter(status=ORDER_STATUS.USED)
        processed = [order.id for order in orders]
        success_num = len(processed)
        try:
            orders.update(**{'is_settled': True, 'settled_time': datetime.datetime.now()})
        except:
            pass
        return {
            "processed": processed,
            "success_num": success_num,
            "fail_num": num - success_num,
        }

    @staticmethod
    def export_excel(orders, to_user_email):
        """
        导出Excel
        """
        export_orders_excel.delay(queryset_dec(orders), to_user_email)

    @staticmethod
    def set_refunded(orders):
        data = []
        for order in orders:
            data.append({
                'id': order.id,
                'payment_channel': order.payment_channel
            })
        return data

    @staticmethod
    def export_self_support_excel(orders, to_user_email):
        """
        导出自营excel
        """
        orders = orders.exclude(operation_location_type=OPERATION_LOCATION_TYPE.NORMAL)
        export_self_support_excel.delay(queryset_dec(orders), to_user_email)
