# -*- coding: utf-8 -*-
# @Time : 2022/5/12 14:16
# @Author : wangyinghao
# @Site : 
# @File : report_jtl.py
# @Software: PyCharm
import os
import random
import threading
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "AutomatedTestPlatform.settings")
django.setup()
from time import sleep
from automated_main.utils.jmeter_perform import create_para_jmx
from automated_main.models.performance_test.performance_script import PerformanceScript
from automated_main.models.performance_test.performance_report import PerformanceReport
from AutomatedTestPlatform import settings
from automated_main.models.performance_test.performance_report import PerformanceReport, PerformanceReportError
from functools import reduce
import pandas as pd

import time
import logging

BASE_PATH = settings.BASE_DIR.replace("\\", "/")
EXTEND_DIR = BASE_PATH + "/automated_main/view/performance_test/performance_script/extend/"
logger = logging.getLogger('django')


class TaskThread22:
    def __init__(self, get_host):
        self.host = get_host

    def run_cases(self):

        report = PerformanceReport.objects.all()
        for jtl2 in report:
            # print(jtl.performance_report_name)
            logger.info("测试报告异常数据")
            logger.info(jtl2.id)
            try:
                # 解析jtl异常问题
                df = pd.read_csv(settings.JMETER_REPORT + '/' + jtl2.performance_report_name + '/' + jtl2.performance_report_name + '.jtl')
                df_1 = pd.DataFrame(df, columns=["label", "responseCode", "responseMessage"])

                df_2 = df_1

                df_2.drop_duplicates(subset=["label", "responseCode", "responseMessage"], keep="first", inplace=True)
                df_3 = df_2.values.tolist()
                jtl_list = []
                for i in range(len(df_3)):
                    jtl_dict = {
                        "error": str(df_3[i][0]) + " " + str(df_3[i][1]) + " " + str(df_3[i][2]),
                        "code": str(df_3[i][1])
                    }
                    jtl_list.append(jtl_dict)
                jtl_error_list = []
                for jtl_error in jtl_list:
                    if jtl_error["code"] != str("200"):
                        j_dict = {
                            "jtl_error": jtl_error["error"]
                        }

                        jtl_error_list.append(j_dict)
                        run_function = lambda x, y: x if y in x else x + [y]
                        jtl_error = reduce(run_function, [[], ] + jtl_error_list)

                    else:
                        j_dict = {
                            "jtl_error": ""
                        }

                        jtl_error_list.append(j_dict)
                        run_function = lambda x, y: x if y in x else x + [y]
                        jtl_error = reduce(run_function, [[], ] + jtl_error_list)

                for jtl_error_data in jtl_error:
                    PerformanceReportError.objects.create(performance_report_error_name=jtl_error_data['jtl_error'],
                                                          performance_report_id=jtl2.id)

            except Exception as e:
                logger.info("异常了" + str(jtl2.id) + str(e))

                PerformanceReportError.objects.create(performance_report_error_name="未找到jtl文件",
                                                      performance_report_id=jtl2.id)

                continue

        logger.info("完成")

    def run_tasks(self):
        logger.info("创建性能线程任务...")
        sleep(2)
        threads = []
        t1 = threading.Thread(target=self.run_cases)
        threads.append(t1)

        for t in threads:
            t.start()

        for t in threads:
            t.join()

    def run(self):
        threads = []
        t = threading.Thread(target=self.run_tasks)
        threads.append(t)

        for t in threads:
            t.start()


if __name__ == '__main__':
    logger.info("开始")
    TaskThread22(1).run()  # 丢给线程去运行任务
    logger.info("结束")
