# -*- encoding: utf-8 -*-
"""
@File    : UserDataController.py
@Time    : 2024年6月7日09:27:28
@Author  : peng
@Email   : peng
@Software: PyCharm
"""

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

from Model.models import OperatingCosts, Order_Model, CountryModel, UID_Bucket
from Service.CommonService import CommonService
from Ansjer.config import CONFIG_EUR, CONFIG_INFO, CONFIG_CN, CONFIG_US
from dateutil.relativedelta import relativedelta


# 运营成本数据
class OperatingCostsDataView(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 == 'getOperatingCosts':  # 查询订单成本利润
            return self.get_operating_costs(request_dict, response)
        else:
            return response.json(414)

    @staticmethod
    def get_operating_costs(request_dict, response):
        """
        查询订单成本利润
        @param request_dict:请求参数
        @request_dict startTime:开始时间
        @request_dict endTime:结束时间
        @param response:响应对象
        @return:
        """
        start_time = request_dict.get('startTime', None)
        end_time = request_dict.get('endTime', None)
        page = request_dict.get('page', None)
        line = request_dict.get('line', None)
        try:
            if start_time and end_time:
                operating_costs_qs = OperatingCosts.objects.filter(time__gte=start_time, time__lt=end_time)
            else:
                operating_costs_qs = OperatingCosts.objects.all()
            count = operating_costs_qs.count()
            operating_qs = operating_costs_qs.values('order_id', 'uid', 'day_average_price', 'month_average_price',
                                                     'purchase_quantity', 'actual_storage', 'actual_api',
                                                     'monthly_income', 'settlement_days', 'remaining_usage_time',
                                                     'end_time', 'created_time', 'start_time', 'time', 'storage_cost',
                                                     'api_cost', 'profit', 'profit_margin', 'fee', 'flow_cost',
                                                     'real_income', 'price', 'region', 'country_name', 'actual_flow',
                                                     'order_type', 'expire')
            if page and line:
                page = int(page)
                line = int(line)
                operating_qs = operating_qs[(page - 1) * line:page * line]
            return response.json(0, {'count': count, 'res': list(operating_qs)})
        except Exception as e:
            print('error')
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
