# -*- coding: utf-8 -*-
# @Time : 2021/11/23 11:21
# @Author : wangyinghao
# @Site : 
# @File : test_plan_thread.py
# @Software: PyCharm
import os
import json
import threading
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "AutomatedTestPlatform.settings")
django.setup()
from time import sleep
from automated_main.models.api_automation.api_scenarios_case import ApiScenariosCase, ApiScenariosCaseAssociated
from automated_main.models.api_automation.api_test_plan import ApiTestPlan
from automated_main.models.api_automation.api_test_plan import APITestPlanResult
from automated_main.models.api_automation.api_interfaces_case import ApiInterfacesCase, ApiInterfacesParameterExtraction, ApiInterfacesParameterData

from automated_main.models.api_automation.api_test_plan import APITestPlanResultAssociated
from automated_main.utils.send_email import SendEmail
from automated_main.utils.send_enterprise_wechat import SendEnterpriseWechatMsg
from AutomatedTestPlatform import settings
from automated_main.view.api_automation.api_test_plan.extend.run_test_plan_task import new_test_run_cases
import time
import logging

BASE_PATH = settings.BASE_DIR.replace("\\", "/")
EXTEND_DIR = BASE_PATH + "/automated_main/view/api_automation/api_test_plan/extend/"
# EXTEND_DIR = BASE_PATH + "\\automated_main\\view\\api_automation\\api_test_task\\extend\\"
logger = logging.getLogger('django')


class TaskThread:

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

    def run_cases(self):
        logger.info("运行某一个任务下面的所有测试用例")

        api_task = ApiTestPlan.objects.get(id=self.tid)
        # 1. 拿到任务对应用例的列表
        api_case_list = json.loads(api_task.cases)

        logger.info("拿到任务对应用例的列表" + api_task.cases)
        now = time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time()))
        api_result = APITestPlanResult.objects.create(
            api_test_plan_id=self.tid,
            api_test_result_name=now,
            api_environment_id=api_task.api_environment.id
        )
        api_result_id = api_result.id
        # 2. 获取API用例数据
        for sid in api_case_list:
            logger.info(sid)
            api_scenarios_case = ApiScenariosCase.objects.get(id=sid)
            api_associated = ApiScenariosCaseAssociated.objects.filter(sid_id=sid)
            data_list = []
            for api_associates in api_associated:
                api_test_case = ApiInterfacesCase.objects.get(id=api_associates.interfaces_case_id)
                api_parameter_extraction = ApiInterfacesParameterExtraction.objects.filter(
                    api_test_case_id=api_associates.interfaces_case_id)

                parameter_data = ApiInterfacesParameterData.objects.filter(api_test_case_id=api_associates.interfaces_case_id)

                api_parameter_extraction_list = []
                api_parameter_dict = {}

                for api_parameters in parameter_data:
                    if api_parameters.api_must_parameter == "true":
                        api_parameter_dict.update(
                            {api_parameters.api_parameter_name: api_parameters.api_parameter_value})
                    else:
                        pass
                for api_parameter_extractions in api_parameter_extraction:
                    api_parameter_extraction_dict = {
                        "api_value_variable": api_parameter_extractions.api_value_variable,
                        "api_key_variable": api_parameter_extractions.api_key_variable,
                        "api_variable_results": api_parameter_extractions.api_variable_results,

                    }
                    api_parameter_extraction_list.append(api_parameter_extraction_dict)

                api_associated_dict = {
                    "api_scenarios_case_name": api_scenarios_case.api_scenarios_case_name,
                    "api_result_id": api_result.id,
                    "api_task_id": self.tid,
                    "api_test_case_id": api_associates.interfaces_case_id,
                    "api_test_case_name": api_test_case.api_interfaces_case_name,
                    "api_method": api_test_case.api_method,
                    "dataBase_id": api_task.database_id,
                    "database_sql": api_test_case.database_sql,
                    "api_url": api_task.api_environment.api_title + api_test_case.api_url,
                    "api_parameter_types": api_test_case.api_parameter_types,
                    "api_headers": api_test_case.api_headers,
                    "parameter_data": api_parameter_dict,
                    "api_parameter_body": api_test_case.api_parameter_body,
                    "api_assert_type": api_test_case.api_assert_type,
                    "api_assert_text": api_test_case.api_assert_text,
                    "api_parameter_extraction": api_parameter_extraction_list,
                    "api_environment_id": api_task.api_environment.id,
                    "case_steps": int(api_associates.case_steps)
                }
                data_list.append(api_associated_dict)

            data_list_sorting = sorted(data_list, key=lambda x: x['case_steps'])
            # 3.这里就可以获取到业务测试用例 data_list_sorting 赋值到 new_test_run_cases中
            new_test_run_cases(data_list_sorting)

        api_total_number = APITestPlanResultAssociated.objects.filter(api_result_id=api_result.id).count()
        api_error_total_number = APITestPlanResultAssociated.objects.filter(api_result_id=api_result.id,
                                                                        api_error=1).count()
        api_successful_total_number = APITestPlanResultAssociated.objects.filter(api_result_id=api_result.id,
                                                                             api_successful=1).count()
        api_test_result = APITestPlanResult.objects.get(id=api_result.id)
        api_test_result.api_error_total_number = api_error_total_number
        api_test_result.api_successful_total_number = api_successful_total_number
        api_test_result.api_total_number = api_total_number
        api_test_result.save()
        # 4. 修改任务的状态，执行完成
        api_task.status = 2
        api_task.save()

        # 取小数后2位,通过率
        pass_result = "%.2f%%" % (api_successful_total_number / api_total_number * 100)
        fail_result = "%.2f%%" % (api_error_total_number / api_total_number * 100)
        user_list = api_task.api_send_email
        sub = "接口自动化测试报告-%s" % api_task.api_test_plan_name

        api_result = APITestPlanResultAssociated.objects.filter(api_result_id=api_result.id, api_error=1)
        content = "这次一共测试%s个接口,通过个数为%s,失败个数为%s,通过率为%s,失败率为%s \n" % (
            api_total_number, api_successful_total_number, api_error_total_number, pass_result, fail_result)
        error_case = ""
        for a in api_result:
            case_result = "业务测试用例名称：" + a.api_business_test_name + ", 测试用例名称:" + a.api_test_case_name + \
                          ", 断言结果：" + a.api_assertion_results

            error_case += case_result + ",\n"

        # 5.发送邮件
        if api_task.api_send_email == "" or None:
            logger.info("该任务无需发送邮件，未填写邮箱")
        else:
            sen = SendEmail()
            sen.send_mail(user_list, sub, content + error_case)

        # 6 发送企业微信
        if api_error_total_number > 0:
            if api_task.api_send_enterprise_wechat == 1:
                ENV_PROFILE = os.getenv("ENV")
                if ENV_PROFILE == "SERVER":
                    result_host = 'http://172.16.0.82:8089'
                elif ENV_PROFILE == "1":
                    result_host = 'http://localhost:8080'
                api_task_result = result_host + "/#/api_test_plan_result?apiResultId=" + str(api_result_id)
                wx_url = ""
                # 发送企业微信
                # a = SendEnterpriseWechatMsg()
                # a.send_msg(wx_url, api_total_number, pass_result, api_successful_total_number, api_error_total_number,
                #            api_task_result)

            elif api_task.api_send_enterprise_wechat == 2 or 0:
                pass

    def run_tasks(self):
        logger.info("创建API线程任务...")
        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("结束")
