# -*- encoding: utf-8 -*-
"""
@File    : UserDataController.py
@Time    : 2022/8/16 10:44
@Author  : peng
@Email   : zhangdongming@asj6.wecom.work
@Software: PyCharm
"""

from django.db.models import Q, Sum
from django.views.generic.base import View
import datetime
import requests

from Model.models import OrdersSummary, DeviceInfoSummary
from Service.CommonService import CommonService


# 服务数据
class ServiceDataView(View):

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        return self.validation(request.GET, request, operation)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        return self.validation(request.POST, request, operation)

    def validation(self, request_dict, request, operation):
        token_code, user_id, response = CommonService.verify_token_get_user_id(request_dict, request)
        if token_code != 0:
            return response.json(token_code)
        if operation == 'payOrder':  # 查询付费订单数据
            return self.query_pay_order(request_dict, response)
        elif operation == 'freeOrder':  # 查询免费订单数据
            return self.query_free_order(request_dict, response)
        elif operation == 'firstPayOrder':  # 查询首次付费订单数据
            return self.query_first_pay_order(request_dict, response)
        elif operation == 'repeatPayOrder':  # 查询复购订单数据
            return self.query_repeat_pay_order(request_dict, response)
        elif operation == 'global/payOrder':  # 查询全球付费订单数据
            return self.query_global_pay_order(request, request_dict, response)
        elif operation == 'global/freeOrder':  # 查询全球免费订单数据
            return self.query_global_free_order(request, request_dict, response)
        elif operation == 'global/firstPayOrder':  # 查询全球首次付费订单数据
            return self.query_global_first_pay_order(request, request_dict, response)
        elif operation == 'global/repeatPayOrder':  # 查询全球复购订单数据
            return self.query_global_repeat_pay_order(request, request_dict, response)
        else:
            return response.json(414)

    @classmethod
    def query_pay_order(cls, request_dict, response):
        """
        查询付费订单数据
        @param request_dict:请求参数
        @request_dict startTime:开始时间
        @request_dict endTime:结束时间
        @request_dict timeUnit:时间单位
        @request_dict storeMealType:套餐类型
        @param response:响应对象
        @return:
        """
        start_time = request_dict.get('startTime', None)
        end_time = request_dict.get('endTime', None)
        time_unit = request_dict.get('timeUnit', None)
        store_meal_type = request_dict.get('storeMealType', None)
        if not all([start_time, end_time, time_unit, store_meal_type]):
            return response.json(444, {'error param': 'startTime or endTime or timeUnit or storeMealType'})
        try:
            store_meal_type = store_meal_type.split(',')
            order_qs = OrdersSummary.objects.filter(time__gte=start_time, time__lt=end_time, query_type=0,
                                                    service_type__in=store_meal_type).values('count', 'country',
                                                                                             'total',
                                                                                             'device_type',
                                                                                             'store_meal')
            all_order_qs = OrdersSummary.objects.filter(time__gte=start_time, time__lt=end_time).filter(
                Q(query_type=0) | Q(query_type=1)).values('total', 'count')
            all_order_count = 0
            all_order_cny_total = 0
            all_order_usd_total = 0
            for item in all_order_qs:
                all_order_count += item['count']
                temp_total = eval(item['total'])
                all_order_cny_total += temp_total.get('CNY', 0)
                all_order_usd_total += temp_total.get('USD', 0)
            start_time = datetime.datetime.fromtimestamp(int(start_time))
            end_time = datetime.datetime.fromtimestamp(int(end_time))
            time_list = CommonService.cutting_time(start_time, end_time, time_unit)

            # 订单数量统计
            order_list = []
            for item in time_list:
                order_temp_qs = order_qs.filter(time__gte=item[0], time__lt=item[1])
                temp_count = order_temp_qs.aggregate(count=Sum('count'))['count']
                temp_count = temp_count if temp_count else 0
                temp_cny_total = 0
                temp_usd_total = 0
                for each in order_temp_qs:
                    temp_total = eval(each['total'])
                    temp_cny_total += temp_total.get('CNY', 0)
                    temp_usd_total += temp_total.get('USD', 0)
                order_dict = {
                    'count': temp_count,
                    'cnyTotal': temp_cny_total,
                    'usdTotal': temp_usd_total,
                    'startTime': item[0],
                    'endTime': item[1]
                }
                order_list.append(order_dict)

            device_type_dict = {}
            country_dict = {}
            store_meal_dict = {}
            for each in order_qs:
                device_type_temp_dict = eval(each['device_type'])
                country_temp_dict = eval(each['country'])
                store_meal_temp_dict = eval(each['store_meal'])
                for k, v in device_type_temp_dict.items():
                    if k in device_type_dict:
                        for a, b in v.items():
                            if a not in device_type_dict[k]:
                                device_type_dict[k][a] = b
                            else:
                                device_type_dict[k][a] += b
                    else:
                        device_type_dict[k] = v
                for k, v in country_temp_dict.items():
                    if k in country_dict:
                        for a, b in v.items():
                            if a not in country_dict[k]:
                                country_dict[k][a] = b
                            else:
                                country_dict[k][a] += b
                    else:
                        country_dict[k] = v
                for k, v in store_meal_temp_dict.items():
                    if k in store_meal_dict:
                        for a, b in v.items():
                            if a not in store_meal_dict[k]:
                                store_meal_dict[k][a] = b
                            else:
                                store_meal_dict[k][a] += b
                    else:
                        store_meal_dict[k] = v
            # 设备类型订单统计
            device_type_list = []
            for k, v in device_type_dict.items():
                type_rate = round(v['数量'] / all_order_count * 100, 2) if all_order_count else 0
                cny_total_rate = round(v.get('CNY', 0) / all_order_cny_total * 100, 2) if all_order_cny_total else 0
                usd_total_rate = round(v.get('USD', 0) / all_order_usd_total * 100, 2) if all_order_usd_total else 0
                device_temp_dict = {
                    'typeName': k,
                    'count': v['数量'],
                    'typeRate': type_rate,
                    'cnyTotalMoney': v.get('CNY', 0),
                    'usdTotalMoney': v.get('USD', 0),
                    'cnyTotalRate': cny_total_rate,
                    'usdTotalRate': usd_total_rate,
                }
                device_type_list.append(device_temp_dict)

            # 区域订单统计
            region_list = []
            for k, v in country_dict.items():
                rate = round(v['数量'] / all_order_count * 100, 2) if all_order_count else 0
                cny_total_rate = round(v.get('CNY', 0) / all_order_cny_total * 100, 2) if all_order_cny_total else 0
                usd_total_rate = round(v.get('USD', 0) / all_order_usd_total * 100, 2) if all_order_usd_total else 0
                region_temp_dict = {
                    'countryName': k,
                    'count': v['数量'],
                    'rate': rate,
                    'cnyTotalMoney': v.get('CNY', 0),
                    'usdTotalMoney': v.get('USD', 0),
                    'cnyTotalRate': cny_total_rate,
                    'usdTotalRate': usd_total_rate,
                }
                region_list.append(region_temp_dict)

            # 套餐订单统计
            store_meal_list = []
            for k, v in store_meal_dict.items():
                count_rate = round(v['数量'] / all_order_count * 100, 2) if all_order_count else 0
                cny_total_rate = round(v.get('CNY', 0) / all_order_cny_total * 100, 2) if all_order_cny_total else 0
                usd_total_rate = round(v.get('USD', 0) / all_order_usd_total * 100, 2) if all_order_usd_total else 0
                store_temp_dict = {
                    'count': v['数量'],
                    'storeMealName': k,
                    'cnyTotalMoney': v.get('CNY', 0),
                    'usdTotalMoney': v.get('USD', 0),
                    'cnyTotalRate': cny_total_rate,
                    'usdTotalRate': usd_total_rate,
                    'rate': count_rate
                }
                store_meal_list.append(store_temp_dict)
            res = {
                'orders': order_list,
                'regions': region_list,
                'deviceType': device_type_list,
                'storeMeal': store_meal_list,
                'allOrderCount': all_order_count,
                'allCnyOrderTotal': all_order_cny_total,
                'allUsdOrderTotal': all_order_usd_total,
            }
            return response.json(0, res)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def query_free_order(cls, request_dict, response):
        """
        查询免费订单数据
        @param request_dict:请求参数
        @request_dict startTime:开始时间
        @request_dict endTime:结束时间
        @request_dict timeUnit:时间单位
        @request_dict storeMealType:套餐类型
        @param response:响应对象
        @return:
        """
        start_time = request_dict.get('startTime', None)
        end_time = request_dict.get('endTime', None)
        time_unit = request_dict.get('timeUnit', None)
        store_meal_type = request_dict.get('storeMealType', None)
        if not all([start_time, end_time, time_unit, store_meal_type]):
            return response.json(444, {'error param': 'startTime or endTime or timeUnit or storeMealType'})
        try:
            store_meal_type = store_meal_type.split(',')
            order_qs = OrdersSummary.objects.filter(time__gte=start_time, time__lt=end_time, query_type=1,
                                                    service_type__in=store_meal_type).values('count', 'country',
                                                                                             'device_type')
            free_order_count = order_qs.aggregate(count=Sum('count'))['count']
            free_order_count = free_order_count if free_order_count else 0  # 免费订单数量
            all_order_qs = OrdersSummary.objects.filter(time__gte=start_time, time__lt=end_time).filter(
                Q(query_type=0) | Q(query_type=1)).aggregate(count=Sum('count'))
            all_order_count = all_order_qs['count'] if all_order_qs['count'] else 0  # 所有订单数量
            device_qs = DeviceInfoSummary.objects.filter(time__gte=start_time, time__lt=end_time, query_type=0).values(
                'vod_service', 'ai_service', 'unicom_service')
            new_device_count = 0  # 销售设备数量
            start_time = datetime.datetime.fromtimestamp(int(start_time))
            end_time = datetime.datetime.fromtimestamp(int(end_time))
            time_list = CommonService.cutting_time(start_time, end_time, time_unit)
            # 转化率
            for item in device_qs:
                if store_meal_type == 0:
                    service = eval(item['vod_service'])
                elif store_meal_type == 1:
                    service = eval(item['ai_service'])
                else:
                    service = eval(item['unicom_service'])
                for each in service.values():
                    new_device_count += each
            inversion_rate = round(free_order_count / new_device_count * 100, 2) if new_device_count else 0
            # 订单数量统计
            order_list = []

            for item in time_list:
                order_temp_qs = order_qs.filter(time__gte=item[0], time__lt=item[1])
                temp_count = order_temp_qs.aggregate(count=Sum('count'))['count']
                temp_count = temp_count if temp_count else 0
                order_dict = {
                    'count': temp_count,
                    'startTime': item[0],
                    'endTime': item[1]
                }
                order_list.append(order_dict)

            device_type_dict = {}
            country_dict = {}
            for each in order_qs:
                device_type_temp_dict = eval(each['device_type'])
                for k, v in device_type_temp_dict.items():
                    if k in device_type_dict:
                        device_type_dict[k] += v
                    else:
                        device_type_dict[k] = v
                country_temp_dict = eval(each['country'])
                for k, v in country_temp_dict.items():
                    if k in country_dict:
                        country_dict[k] += v
                    else:
                        country_dict[k] = v

            # 设备类型订单统计
            device_type_list = []
            for k, v in device_type_dict.items():
                type_rate = round(v / all_order_count * 100, 2) if all_order_count else 0
                device_temp_qs = {
                    'typeName': k,
                    'count': v,
                    'typeRate': type_rate,
                }
                device_type_list.append(device_temp_qs)

            # 区域订单统计
            region_list = []
            for k, v in country_dict.items():
                rate = round(v / all_order_count * 100, 2) if all_order_count else 0
                region_temp_dict = {
                    'countryName': k,
                    'count': v,
                    'rate': rate
                }
                region_list.append(region_temp_dict)

            res = {
                'orders': order_list,
                'regions': region_list,
                'deviceType': device_type_list,
                'inversionRate': inversion_rate,
                'newDeviceCount': new_device_count,
                'allOrderCount': all_order_count
            }
            return response.json(0, res)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def query_first_pay_order(cls, request_dict, response):
        """
        查询首次付费订单数据
        @param request_dict:请求参数
        @request_dict startTime:开始时间
        @request_dict endTime:结束时间
        @request_dict timeUnit:时间单位
        @request_dict storeMealType:套餐类型
        @param response:响应对象
        @return:
        """
        start_time = request_dict.get('startTime', None)
        end_time = request_dict.get('endTime', None)
        time_unit = request_dict.get('timeUnit', None)
        store_meal_type = request_dict.get('storeMealType', None)
        if not all([start_time, end_time, time_unit, store_meal_type]):
            return response.json(444, {'error param': 'startTime or endTime or timeUnit or storeMealType'})
        try:
            store_meal_type = store_meal_type.split(',')
            order_qs = OrdersSummary.objects.filter(time__gte=start_time, time__lt=end_time, query_type=2,
                                                    service_type__in=store_meal_type).values('count', 'country',
                                                                                             'total',
                                                                                             'device_type')
            all_order_qs = OrdersSummary.objects.filter(time__gte=start_time, time__lt=end_time).filter(
                Q(query_type=0) | Q(query_type=1)).values('total', 'count')
            all_order_count = 0
            all_order_cny_total = 0
            all_order_usd_total = 0
            for item in all_order_qs:
                all_order_count += item['count']
                temp_total = eval(item['total'])
                all_order_cny_total += temp_total.get('CNY', 0)
                all_order_usd_total += temp_total.get('USD', 0)
            start_time = datetime.datetime.fromtimestamp(int(start_time))
            end_time = datetime.datetime.fromtimestamp(int(end_time))
            time_list = CommonService.cutting_time(start_time, end_time, time_unit)

            # 订单数量统计
            order_list = []
            for item in time_list:
                order_temp_qs = order_qs.filter(time__gte=item[0], time__lt=item[1])
                temp_count = order_temp_qs.aggregate(count=Sum('count'))['count']
                temp_count = temp_count if temp_count else 0
                temp_cny_total = 0
                temp_usd_total = 0
                for each in order_temp_qs:
                    temp_total = eval(each['total'])
                    temp_cny_total += temp_total.get('CNY', 0)
                    temp_usd_total += temp_total.get('USD', 0)
                order_dict = {
                    'count': temp_count,
                    'cnyTotal': temp_cny_total,
                    'usdTotal': temp_usd_total,
                    'startTime': item[0],
                    'endTime': item[1]
                }
                order_list.append(order_dict)

            country_dict = {}
            device_type_dict = {}
            for each in order_qs:
                country_temp_dict = eval(each['country'])
                device_type_temp_dict = eval(each['device_type'])
                for k, v in country_temp_dict.items():
                    if k in country_dict:
                        for a, b in v.items():
                            if a not in country_dict[k]:
                                country_dict[k][a] = b
                            else:
                                country_dict[k][a] += b
                    else:
                        country_dict[k] = v
                for k, v in device_type_temp_dict.items():
                    if k in device_type_dict:
                        for a, b in v.items():
                            if a not in device_type_dict[k]:
                                device_type_dict[k][a] = b
                            else:
                                device_type_dict[k][a] += b
                    else:
                        device_type_dict[k] = v

            # 设备类型订单统计
            device_type_list = []
            for k, v in device_type_dict.items():
                type_rate = round(v['数量'] / all_order_count * 100, 2) if all_order_count else 0
                cny_total_rate = round(v.get('CNY', 0) / all_order_cny_total * 100, 2) if all_order_cny_total else 0
                usd_total_rate = round(v.get('USD', 0) / all_order_usd_total * 100, 2) if all_order_usd_total else 0
                device_temp_qs = {
                    'typeName': k,
                    'count': v['数量'],
                    'cnyTotalRate': cny_total_rate,
                    'usdTotalRate': usd_total_rate,
                    'typeRate': type_rate,
                    'cnyTotalMoney': v.get('CNY', 0),
                    'usdTotalMoney': v.get('USD', 0),
                }
                device_type_list.append(device_temp_qs)

            # 区域订单统计
            region_list = []
            for k, v in country_dict.items():
                rate = round(v['数量'] / all_order_count * 100, 2) if all_order_count else 0
                cny_total_rate = round(v.get('CNY', 0) / all_order_cny_total * 100, 2) if all_order_cny_total else 0
                usd_total_rate = round(v.get('USD', 0) / all_order_usd_total * 100, 2) if all_order_usd_total else 0
                region_temp_dict = {
                    'countryName': k,
                    'count': v['数量'],
                    'rate': rate,
                    'cnyTotalMoney': v.get('CNY', 0),
                    'usdTotalMoney': v.get('USD', 0),
                    'cnyTotalRate': cny_total_rate,
                    'usdTotalRate': usd_total_rate,
                }
                region_list.append(region_temp_dict)

            res = {
                'orders': order_list,
                'regions': region_list,
                'deviceType': device_type_list,
                'allOrderCount': all_order_count,
                'allOrderUsdTotal': all_order_usd_total,
                'allOrderCnyTotal': all_order_cny_total,
            }
            return response.json(0, res)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def query_repeat_pay_order(cls, request_dict, response):
        """
        查询复购订单数据
        @param request_dict:请求参数
        @request_dict startTime:开始时间
        @request_dict endTime:结束时间
        @request_dict timeUnit:时间单位
        @request_dict storeMealType:套餐类型
        @param response:响应对象
        @return:
        """
        start_time = request_dict.get('startTime', None)
        end_time = request_dict.get('endTime', None)
        time_unit = request_dict.get('timeUnit', None)
        store_meal_type = request_dict.get('storeMealType', None)
        if not all([start_time, end_time, time_unit, store_meal_type]):
            return response.json(444, {'error param': 'startTime or endTime or timeUnit or storeMealType'})
        try:
            store_meal_type = store_meal_type.split(',')
            order_qs = OrdersSummary.objects.filter(time__gte=start_time, time__lt=end_time, query_type=3,
                                                    service_type__in=store_meal_type).values('count', 'country',
                                                                                             'total',
                                                                                             'device_type')
            repeat_pay_order_count = order_qs.aggregate(count=Sum('count'))['count']
            repeat_pay_order_count = repeat_pay_order_count if repeat_pay_order_count else 0
            all_order_qs = OrdersSummary.objects.filter(time__gte=start_time, time__lt=end_time).filter(
                Q(query_type=0) | Q(query_type=1)).values('total', 'count')
            all_order_count = 0  # 所有订单数量
            all_order_cny_total = 0
            all_order_usd_total = 0
            for item in all_order_qs:
                all_order_count += item['count']
                temp_total = eval(item['total'])
                all_order_cny_total += temp_total.get('CNY', 0)
                all_order_usd_total += temp_total.get('USD', 0)
            # 订单复购率
            repeat_rate = round(repeat_pay_order_count / all_order_count * 100, 2) if all_order_count else 0
            start_time = datetime.datetime.fromtimestamp(int(start_time))
            end_time = datetime.datetime.fromtimestamp(int(end_time))
            time_list = CommonService.cutting_time(start_time, end_time, time_unit)
            # 订单数量统计
            order_list = []
            for item in time_list:
                order_temp_qs = order_qs.filter(time__gte=item[0], time__lt=item[1])
                temp_count = order_temp_qs.aggregate(count=Sum('count'))['count']
                temp_count = temp_count if temp_count else 0
                temp_cny_total = 0
                temp_usd_total = 0
                for each in order_temp_qs:
                    temp_total = eval(each['total'])
                    temp_cny_total += temp_total.get('CNY', 0)
                    temp_usd_total += temp_total.get('USD', 0)
                order_dict = {
                    'count': temp_count,
                    'cnyTotal': temp_cny_total,
                    'usdTotal': temp_usd_total,
                    'startTime': item[0],
                    'endTime': item[1]
                }
                order_list.append(order_dict)
            device_type_dict = {}
            country_dict = {}
            for each in order_qs:
                country_temp_dict = eval(each['country'])
                device_type_temp_dict = eval(each['device_type'])
                for k, v in country_temp_dict.items():
                    if k in country_dict:
                        for a, b in v.items():
                            if a not in country_dict[k]:
                                country_dict[k][a] = b
                            else:
                                country_dict[k][a] += b
                    else:
                        country_dict[k] = v
                for k, v in device_type_temp_dict.items():
                    if k in device_type_dict:
                        for a, b in v.items():
                            if a not in device_type_dict[k]:
                                device_type_dict[k][a] = b
                            else:
                                device_type_dict[k][a] += b
                    else:
                        device_type_dict[k] = v

            # 设备类型订单统计
            device_type_list = []
            for k, v in device_type_dict.items():
                type_rate = round(v['数量'] / all_order_count * 100, 2) if all_order_count else 0
                cny_total_rate = round(v.get('CNY', 0) / all_order_cny_total * 100, 2) if all_order_cny_total else 0
                usd_total_rate = round(v.get('USD', 0) / all_order_usd_total * 100, 2) if all_order_usd_total else 0
                device_temp_qs = {
                    'typeName': k,
                    'count': v['数量'],
                    'typeRate': type_rate,
                    'cnyTotalMoney': v.get('CNY', 0),
                    'usdTotalMoney': v.get('USD', 0),
                    'cnyTotalRate': cny_total_rate,
                    'usdTotalRate': usd_total_rate,
                }
                device_type_list.append(device_temp_qs)

            # 区域订单统计
            region_list = []
            for k, v in country_dict.items():
                rate = round(v['数量'] / all_order_count * 100, 2) if all_order_count else 0
                cny_total_rate = round(v.get('CNY', 0) / all_order_cny_total * 100, 2) if all_order_cny_total else 0
                usd_total_rate = round(v.get('USD', 0) / all_order_usd_total * 100, 2) if all_order_usd_total else 0
                region_temp_dict = {
                    'countryName': k,
                    'count': v['数量'],
                    'rate': rate,
                    'cnyTotalMoney': v.get('CNY', 0),
                    'usdTotalMoney': v.get('USD', 0),
                    'cnyTotalRate': cny_total_rate,
                    'usdTotalRate': usd_total_rate,
                }
                region_list.append(region_temp_dict)
            res = {
                'orders': order_list,
                'regions': region_list,
                'deviceType': device_type_list,
                'repeatRate': repeat_rate,
                'repeatOrderCount': repeat_pay_order_count,
                'allOrderCount': all_order_count,
                'allOrderCnyTotal': all_order_cny_total,
                'allOrderUsdTotal': all_order_usd_total,

            }
            return response.json(0, res)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def query_global_pay_order(cls, request, request_dict, response):
        """
        查询全球付费订单数据
        @param request:请求
        @param request_dict:请求参数
        @param response:响应对象
        @return:
        """
        url_list = CommonService.get_domain_name()
        try:
            headers = {
                'Authorization': request.META.get('HTTP_AUTHORIZATION')
            }
            order_list = []
            region_list = []
            device_type_list = []
            all_order_count = 0
            all_cny_order_total = 0
            all_usd_order_total = 0
            store_meal_list = []
            for url in url_list:
                url = url + request.path.replace('global/', '')
                res = requests.get(url=url, params=request_dict, headers=headers)
                result = res.json()
                if result['result_code'] == 0:
                    # 处理订单
                    for item in result['result']['orders']:
                        flag = 0
                        for each in order_list:
                            if each['startTime'] == item['startTime'] and each['endTime'] == item['endTime']:
                                each['count'] += int(item['count'])
                                each['cnyTotal'] += item['cnyTotal']
                                each['usdTotal'] += item['usdTotal']
                                flag = 1
                                break
                        if flag == 0:
                            order_list.append(item)
                    # 处理地区
                    for item in result['result']['regions']:
                        flag = 0
                        for each in region_list:
                            if each['countryName'] == item['countryName']:
                                each['count'] += int(item['count'])
                                each['cnyTotalMoney'] += item['cnyTotalMoney']
                                each['usdTotalMoney'] += item['usdTotalMoney']
                                flag = 1
                                break
                        if flag == 0:
                            region_list.append(item)

                    # 处理设备类型
                    for item in result['result']['deviceType']:
                        flag = 0
                        for each in device_type_list:
                            if each['typeName'] == item['typeName']:
                                each['count'] += int(item['count'])
                                each['cnyTotalMoney'] += item['cnyTotalMoney']
                                each['usdTotalMoney'] += item['usdTotalMoney']
                                flag = 1
                                break
                        if flag == 0:
                            device_type_list.append(item)

                    # 处理套餐
                    for item in result['result']['storeMeal']:
                        flag = 0
                        for each in store_meal_list:
                            if each['storeMealName'] == item['storeMealName']:
                                each['count'] += int(item['count'])
                                each['cnyTotalMoney'] += item['cnyTotalMoney']
                                each['usdTotalMoney'] += item['usdTotalMoney']
                                flag = 1
                                break
                        if flag == 0:
                            store_meal_list.append(item)

                    all_cny_order_total += result['result']['allCnyOrderTotal']
                    all_usd_order_total += result['result']['allUsdOrderTotal']
                    all_order_count += result['result']['allOrderCount']
                else:
                    return response.json(result['result_code'], result['result'])
            for item in order_list:
                item['cnyTotal'] = round(item['cnyTotal'], 2)
                item['usdTotal'] = round(item['usdTotal'], 2)
            for item in region_list:
                item['rate'] = round(item['count'] / all_order_count * 100, 2) if all_order_count else 0
                item['cnyTotalMoney'] = round(item['cnyTotalMoney'], 2)
                item['usdTotalMoney'] = round(item['usdTotalMoney'], 2)
                item['cnyTotalRate'] = round(item['cnyTotalMoney'] / all_cny_order_total * 100,
                                             2) if all_cny_order_total else 0
                item['usdTotalRate'] = round(item['usdTotalMoney'] / all_usd_order_total * 100,
                                             2) if all_usd_order_total else 0
            for item in device_type_list:
                item['typeRate'] = round(item['count'] / all_order_count * 100, 2) if all_order_count else 0
                item['cnyTotalMoney'] = round(item['cnyTotalMoney'], 2)
                item['usdTotalMoney'] = round(item['usdTotalMoney'], 2)
                item['cnyTotalRate'] = round(item['cnyTotalMoney'] / all_cny_order_total * 100,
                                             2) if all_cny_order_total else 0
                item['usdTotalRate'] = round(item['usdTotalMoney'] / all_usd_order_total * 100,
                                             2) if all_usd_order_total else 0
            for item in store_meal_list:
                item['cnyTotalRate'] = round(item['cnyTotalMoney'] / all_cny_order_total * 100,
                                             2) if all_cny_order_total else 0
                item['usdTotalRate'] = round(item['usdTotalMoney'] / all_usd_order_total * 100,
                                             2) if all_usd_order_total else 0
                item['cnyTotalMoney'] = round(item['cnyTotalMoney'], 2)
                item['usdTotalMoney'] = round(item['usdTotalMoney'], 2)
                item['rate'] = round(item['count'] / all_order_count * 100, 2) if all_order_count else 0
            res = {
                'orders': order_list,
                'regions': CommonService.list_sort(region_list),
                'deviceType': CommonService.list_sort(device_type_list),
                'storeMeal': CommonService.list_sort(store_meal_list)
            }
            return response.json(0, res)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def query_global_free_order(cls, request, request_dict, response):
        """
        查询全球免费订单数据
        @param request:请求
        @param request_dict:请求参数
        @param response:响应对象
        @return:
        """
        url_list = CommonService.get_domain_name()
        try:
            headers = {
                'Authorization': request.META.get('HTTP_AUTHORIZATION')
            }
            order_list = []
            region_list = []
            free_order_count = 0
            device_type_list = []
            new_device_count = 0
            all_order_count = 0
            for url in url_list:
                url = url + request.path.replace('global/', '')
                res = requests.get(url=url, params=request_dict, headers=headers)
                result = res.json()
                if result['result_code'] == 0:
                    # 处理订单
                    for item in result['result']['orders']:
                        flag = 0
                        for each in order_list:
                            if each['startTime'] == item['startTime'] and each['endTime'] == item['endTime']:
                                each['count'] += int(item['count'])
                                flag = 1
                                break
                        if flag == 0:
                            order_list.append(item)
                    # 处理地区
                    for item in result['result']['regions']:
                        flag = 0
                        for each in region_list:
                            if each['countryName'] == item['countryName']:
                                each['count'] += int(item['count'])
                                free_order_count += int(item['count'])
                                flag = 1
                                break
                        if flag == 0:
                            region_list.append(item)
                            free_order_count += int(item['count'])

                    # 处理设备类型
                    for item in result['result']['deviceType']:
                        flag = 0
                        for each in device_type_list:
                            if each['typeName'] == item['typeName']:
                                each['count'] += int(item['count'])
                                flag = 1
                                break
                        if flag == 0:
                            device_type_list.append(item)

                    # 处理转化率
                    new_device_count += int(result['result']['newDeviceCount'])
                    all_order_count += int(result['result']['allOrderCount'])
                else:
                    return response.json(result['result_code'], result['result'])
            inversion_rate = round(free_order_count / new_device_count * 100, 2) if new_device_count else 0
            for item in region_list:
                item['rate'] = round(item['count'] / all_order_count * 100, 2) if all_order_count else 0
            for item in device_type_list:
                item['typeRate'] = round(item['count'] / all_order_count * 100, 2) if all_order_count else 0
            res = {
                'orders': order_list,
                'regions': CommonService.list_sort(region_list),
                'deviceType': CommonService.list_sort(device_type_list),
                'inversionRate': inversion_rate
            }
            return response.json(0, res)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def query_global_first_pay_order(cls, request, request_dict, response):
        """
        查询全球首次付费订单数据
        @param request:请求
        @param request_dict:请求参数
        @param response:响应对象
        @return:
        """
        url_list = CommonService.get_domain_name()
        try:
            headers = {
                'Authorization': request.META.get('HTTP_AUTHORIZATION')
            }
            order_list = []
            region_list = []
            device_type_list = []
            all_order_count = 0
            all_usd_order_total = 0
            all_cny_order_total = 0
            for url in url_list:
                url = url + request.path.replace('global/', '')
                res = requests.get(url=url, params=request_dict, headers=headers)
                result = res.json()
                if result['result_code'] == 0:
                    # 处理订单
                    for item in result['result']['orders']:
                        flag = 0
                        for each in order_list:
                            if each['startTime'] == item['startTime'] and each['endTime'] == item['endTime']:
                                each['count'] += int(item['count'])
                                each['cnyTotal'] += item['cnyTotal']
                                each['usdTotal'] += item['usdTotal']
                                flag = 1
                                break
                        if flag == 0:
                            order_list.append(item)
                    # 处理地区
                    for item in result['result']['regions']:
                        flag = 0
                        for each in region_list:
                            if each['countryName'] == item['countryName']:
                                each['count'] += int(item['count'])
                                each['cnyTotalMoney'] += item['cnyTotalMoney']
                                each['usdTotalMoney'] += item['usdTotalMoney']
                                flag = 1
                                break
                        if flag == 0:
                            region_list.append(item)

                    # 处理设备类型
                    for item in result['result']['deviceType']:
                        flag = 0
                        for each in device_type_list:
                            if each['typeName'] == item['typeName']:
                                each['count'] += int(item['count'])
                                each['cnyTotalMoney'] += item['cnyTotalMoney']
                                each['usdTotalMoney'] += item['usdTotalMoney']
                                flag = 1
                                break
                        if flag == 0:
                            device_type_list.append(item)
                    all_order_count += result['result']['allOrderCount']
                    all_cny_order_total += result['result']['allOrderCnyTotal']
                    all_usd_order_total += result['result']['allOrderUsdTotal']
                else:
                    return response.json(result['result_code'], result['result'])
            for item in order_list:
                item['cnyTotal'] = round(item['cnyTotal'], 2)
                item['usdTotal'] = round(item['usdTotal'], 2)
            for item in region_list:
                item['cnyTotalRate'] = round(item['cnyTotalMoney'] / all_cny_order_total * 100,
                                             2) if all_cny_order_total else 0
                item['usdTotalRate'] = round(item['usdTotalMoney'] / all_usd_order_total * 100,
                                             2) if all_usd_order_total else 0
                item['cnyTotalMoney'] = round(item['cnyTotalMoney'], 2)
                item['usdTotalMoney'] = round(item['usdTotalMoney'], 2)
                item['rate'] = round(item['count'] / all_order_count * 100, 2) if all_order_count else 0
            for item in device_type_list:
                item['cnyTotalRate'] = round(item['cnyTotalMoney'] / all_cny_order_total * 100,
                                             2) if all_cny_order_total else 0
                item['usdTotalRate'] = round(item['usdTotalMoney'] / all_usd_order_total * 100,
                                             2) if all_usd_order_total else 0
                item['cnyTotalMoney'] = round(item['cnyTotalMoney'], 2)
                item['usdTotalMoney'] = round(item['usdTotalMoney'], 2)
                item['typeRate'] = round(item['count'] / all_order_count * 100, 2) if all_order_count else 0
            res = {
                'orders': order_list,
                'regions': CommonService.list_sort(region_list),
                'deviceType': CommonService.list_sort(device_type_list),
            }
            return response.json(0, res)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def query_global_repeat_pay_order(cls, request, request_dict, response):
        """
        查询全球复购订单数据
        @param request:请求
        @param request_dict:请求参数
        @param response:响应对象
        @return:
        """
        url_list = CommonService.get_domain_name()
        try:
            headers = {
                'Authorization': request.META.get('HTTP_AUTHORIZATION')
            }
            order_list = []
            region_list = []
            repeat_order_count = 0
            device_type_list = []
            all_order_count = 0
            all_usd_order_total = 0
            all_cny_order_total = 0
            for url in url_list:
                url = url + request.path.replace('global/', '')
                res = requests.get(url=url, params=request_dict, headers=headers)
                result = res.json()
                if result['result_code'] == 0:
                    # 处理订单
                    for item in result['result']['orders']:
                        flag = 0
                        for each in order_list:
                            if each['startTime'] == item['startTime'] and each['endTime'] == item['endTime']:
                                each['count'] += int(item['count'])
                                each['cnyTotal'] += item['cnyTotal']
                                each['usdTotal'] += item['usdTotal']
                                flag = 1
                                break
                        if flag == 0:
                            order_list.append(item)
                    # 处理地区
                    for item in result['result']['regions']:
                        flag = 0
                        for each in region_list:
                            if each['countryName'] == item['countryName']:
                                each['count'] += int(item['count'])
                                each['cnyTotalMoney'] += item['cnyTotalMoney']
                                each['usdTotalMoney'] += item['usdTotalMoney']
                                flag = 1
                                break
                        if flag == 0:
                            region_list.append(item)

                    # 处理设备类型
                    for item in result['result']['deviceType']:
                        flag = 0
                        for each in device_type_list:
                            if each['typeName'] == item['typeName']:
                                each['count'] += int(item['count'])
                                each['cnyTotalMoney'] += item['cnyTotalMoney']
                                each['usdTotalMoney'] += item['usdTotalMoney']
                                flag = 1
                                break
                        if flag == 0:
                            device_type_list.append(item)

                    # 处理订单复购率
                    repeat_order_count += result['result']['repeatOrderCount']
                    all_order_count += result['result']['allOrderCount']
                    all_usd_order_total += result['result']['allOrderUsdTotal']
                    all_cny_order_total += result['result']['allOrderCnyTotal']
                else:
                    return response.json(result['result_code'], result['result'])
            repeat_rate = round(repeat_order_count / all_order_count * 100, 2) if all_order_count else 0
            for item in order_list:
                item['cnyTotal'] = round(item['cnyTotal'], 2)
                item['usdTotal'] = round(item['usdTotal'], 2)
            for item in device_type_list:
                item['cnyTotalRate'] = round(item['cnyTotalMoney'] / all_cny_order_total * 100,
                                             2) if all_cny_order_total else 0
                item['usdTotalRate'] = round(item['usdTotalMoney'] / all_usd_order_total * 100,
                                             2) if all_usd_order_total else 0
                item['cnyTotalMoney'] = round(item['cnyTotalMoney'], 2)
                item['usdTotalMoney'] = round(item['usdTotalMoney'], 2)
                item['typeRate'] = round(item['count'] / all_order_count * 100, 2) if all_order_count else 0
            for item in region_list:
                item['cnyTotalMoney'] = round(item['cnyTotalMoney'], 2)
                item['usdTotalMoney'] = round(item['usdTotalMoney'], 2)
                item['cnyTotalRate'] = round(item['cnyTotalMoney'] / all_cny_order_total * 100,
                                             2) if all_cny_order_total else 0
                item['usdTotalRate'] = round(item['usdTotalMoney'] / all_usd_order_total * 100,
                                             2) if all_usd_order_total else 0
                item['rate'] = round(item['count'] / all_order_count * 100, 2) if all_order_count else 0
            res = {
                'orders': order_list,
                'regions': CommonService.list_sort(region_list),
                'deviceType': CommonService.list_sort(device_type_list),
                'repeatRate': repeat_rate,
            }
            return response.json(0, res)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
