# -*- coding: utf-8 -*-
# @Time : 2021/12/21 17:12
# @Author : wangyinghao
# @Site : 
# @File : performance_task_thread.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
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 TaskThread:

    def __init__(self, task_id, get_host):
        self.tid = task_id
        self.host = get_host

    def run_cases(self):

        performance_script = PerformanceScript.objects.get(id=self.tid)
        performance_script_path = settings.JMETER_ROOT + "/" + os.path.basename(
            performance_script.performance_script)
        logger.info("脚本路径" + performance_script_path)
        fn = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
        fn = str(performance_script.id) + "-" + fn + '-%d' % random.randint(0, 100)

        logger.info("性能脚本名称" + fn)

        ENV_PROFILE = os.getenv("ENV")
        if ENV_PROFILE == "SERVER":
            jmeter = 'jmeter.sh'
        elif ENV_PROFILE == "1":
            jmeter = 'jmeter'
        jmx = create_para_jmx(performance_script_path, performance_script.performance_threads,
                              performance_script.performance_loop_count,
                              str(performance_script.performance_duration),
                              performance_script.performance_ramp_up_time_seconds,
                              performance_script.performance_scheduler,
                              performance_script.loop_count_forever,
                              performance_script.data_set, performance_script.performance_data_script)
        jmeter_script = jmeter + ' -n -t ' + jmx + ' -l ' + settings.JMETER_REPORT + '/' + fn + '/' + fn + '.jtl'

        logger.info("性能脚本命令：" + jmeter_script)
        os.system(jmeter_script)
        jmeter_script_html = jmeter + " -g " + settings.JMETER_REPORT + "/" + fn + "/" + fn + ".jtl" + " -e -o " + settings.JMETER_REPORT + "/" + fn + "/" + fn
        logger.info("性能脚本报告命令" + jmeter_script_html)
        os.system(jmeter_script_html)

        PerformanceReport.objects.create(performance_report_name=fn, performance_script_id=self.tid,
                                         file="http://" + self.host + "/api/jmeter_report/Report/" + fn + "/" + fn + "/" + "index.html")
        performance_script.performance_status = 2
        performance_script.save()

    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("开始")
    # run()  # 丢给线程去运行任务
    TaskThread(16).run()
    logger.info("结束")
