# -*- coding: utf-8 -*-
"""
@Time ： 2021/6/18 11:24
@Auth ： WangYingHao
@File ：system_home_page_list_view.py
@IDE ：PyCharm

"""

from django.views.generic import View
from automated_main.utils.http_format import response_success
from automated_main.models.api_automation.api_interfaces_case import ApiInterfacesCase

from automated_main.models.api_automation.api_environment import APIEnvironment
from automated_main.models.ui_automation.ui_test_case import UITestCase
from automated_main.models.api_automation.api_test_plan import APITestPlanResult

from automated_main.models.performance_test.performance_script import PerformanceScript
import datetime
import json


class SystemHomePageListView(View):

    # 8.15弃用
    # def get(self, request, *args, **kwargs):
    #     """
    #     代表获取所有项目测试用例
    #     :param request:
    #     :param args:
    #     :param kwargs:
    #     :return:
    #     """
    #
    #     api_test_case = ApiTestCase.objects.all()
    #     api_test_case_number = len(api_test_case)
    #
    #     ui_test_case = UITestCase.objects.all()
    #     ui_test_case_number = len(ui_test_case)
    #
    #     performance_script = PerformanceScript.objects.all()
    #     performance_script_number = len(performance_script)
    #
    #     return response_success({"api_test_case_number": api_test_case_number,
    #                              "ui_test_case_number": ui_test_case_number,
    #                              "performance_script_number": performance_script_number}
    #                             )

    def get(self, request, *args, **kwargs):
        """
        代表获取所有项目测试用例
        :param request:
        :param args:
        :param kwargs:
        :return:
        """

        api_test_case_number = ApiInterfacesCase.objects.all().count()

        ui_test_case_number = UITestCase.objects.all().count()

        performance_script_number = PerformanceScript.objects.all().count()

        return response_success({"api_test_case_number": api_test_case_number,
                                 "ui_test_case_number": ui_test_case_number,
                                 "performance_script_number": performance_script_number}
                                )


class SystemHomePageAPIListView(View):
    def post(self, request, *args, **kwargs):
        """
        代表获取API统计
        :param request:
        :param args:
        :param kwargs:
        :return:
        """

        body = request.body

        data = json.loads(body)
        print(data['time_scope_data'][0])

        api_environment = APIEnvironment.objects.all()
        charts_dict = {
            "title": {
                "text": "API接口自动化动态",
                "left": "center"
            },
            "tooltip": {
                "trigger": "axis"
            },

            "legend": {
                "show": bool(True),
                "top": "8%",
                "data": []
            },
            "grid": {
                "left": "3%",
                "right": "5%",
                "bottom": "3%",
                "containLabel": bool(True)
            },
            "toolbox": {
                "feature": {
                    "saveAsImage": {}
                }
            },
            "xAxis": {
                "type": 'category',
                # "boundaryGap":  bool(False),
                "data": ['2022-5-11', '2022-5-12', '2022-5-13', '2022-5-14', '2022-5-15', '2022-5-16', '2022-5-17']
            },
            "yAxis": {
                "type": 'value'
            },
            "series": []
        }

        # 图表标签
        legend = []
        series_list = []
        for api_environment_name in api_environment:
            legend.append(api_environment_name.api_environment_name)
            series_dict = {

                "name": api_environment_name.api_environment_name,
                "type": 'line',
                "connectNulls": bool(True),
                "data": []

            }
            series_list.append(series_dict)
        charts_dict['series'] = series_list

        charts_dict['legend']['data'] = legend

        begin_date_str = data['time_scope_data'][0]
        end_date_str = data['time_scope_data'][1]
        date_list = []
        begin_date = datetime.datetime.strptime(begin_date_str, "%Y-%m-%d")
        end_date = datetime.datetime.strptime(end_date_str, "%Y-%m-%d")
        while begin_date <= end_date:
            date_str = begin_date.strftime("%Y-%m-%d")
            date_list.append(date_str)
            begin_date += datetime.timedelta(days=1)

            for environment_name in charts_dict['series']:
                api_environment_data = APIEnvironment.objects.get(api_environment_name=environment_name['name'])

                api_test_result = APITestPlanResult.objects.filter(create_time__startswith=date_str,
                                                                   api_environment_id=api_environment_data.id)
                error_total = 0
                if len(api_test_result) > 0:
                    for api_test_result_data in api_test_result:
                        error_total = error_total + int(api_test_result_data.api_error_total_number)
                else:
                    pass

                environment_name['data'].append(error_total)

        charts_dict['xAxis']['data'] = date_list

        return response_success({"api_charts": charts_dict})
