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

import requests
from django.views.generic.base import View

from Model.models import VodHlsSummary
from Service.CommonService import CommonService


# 业务数据
class BusinessDataView(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 == 'vodData':  # 查询设备云存储数据
            return self.query_device_vod_business(request_dict, response)
        elif operation == 'global/vodData':  # 查询全球设备云存储数据
            return self.query_global_device_vod_business(request, request_dict, response)
        else:
            return response.json(414)

    @classmethod
    def query_device_vod_business(cls, 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)
        if not all([start_time, end_time]):
            return response.json(444, {'error param': 'startTime or endTime'})
        try:
            vod_hls_summary_qs = VodHlsSummary.objects.filter(time__gte=start_time, time__lt=end_time).values()

            vod_hls_result = []
            for item in vod_hls_summary_qs:
                vod_hls_result.append({
                    'uid': item['uid'],
                    'uploadDuration': item['upload_duration'],
                    'uploadFrequency': item['upload_frequency'],
                    'playFrequency': item['play_frequency'],
                    'playDuration': item['play_duration']
                })
            upload_device_count = len(vod_hls_result)  # 上传设备数量

            res = {
                'uploadDeviceCount': upload_device_count,
                'vodData': vod_hls_result
            }
            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_device_vod_business(cls, request, request_dict, response):
        """
        查询全球设备云存储数据
        @param request:请求
        @param request_dict:请求参数
        @param response:响应对象
        @return:
        """
        page_no = request_dict.get('pageNo', None)
        page_size = request_dict.get('pageSize', None)
        if not all([page_size, page_no]):
            return response.json(444, {'error param': 'pageNo or pageSize'})
        page_no = int(page_no)
        page_size = int(page_size)
        url_list = CommonService.get_domain_name()
        try:
            headers = {
                'Authorization': request.META.get('HTTP_AUTHORIZATION')
            }
            upload_device_count = 0
            vod_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:
                    upload_device_count += int(result['result']['uploadDeviceCount'])
                    vod_list += result['result']['vodData']
                else:
                    return response.json(result['result_code'], result['result'])
            res = {
                'uploadDeviceCount': upload_device_count,
                'vodData': vod_list[(page_no - 1) * page_size:page_no * page_size]
            }
            return response.json(0, res)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
