# # -*- coding: utf-8 -*-
# # @Time    : 2021/4/20 14:05
# # @Author  :
# # @FileName: api_test_task_view.py
# # @Software: PyCharm
# from django.views.generic import View
# import json
# from django.forms import model_to_dict
# from automated_main.utils.http_format import response_success, response_failed
# from automated_main.exception.my_exception import MyException
# # from automated_main.models.api_automation.api_test_task import APITestTask, APITestResult, APITestResultAssociated
# # from automated_main.models.api_automation.api_project import APIProject
# # from automated_main.models.api_automation.api_business_test import ApiBusinessTest
# from automated_main.form.api_test_task import ApiTestTaskForm
# from automated_main.view.api_automation.api_test_task.extend.new_task_thread import TaskThread
# from django.core.paginator import Paginator
# from apscheduler.schedulers.background import BackgroundScheduler
# from apscheduler.jobstores.base import ConflictingIdError
# from django.core.exceptions import ObjectDoesNotExist
# import arrow
# import logging
#
# logger = logging.getLogger('django')
#
#
# class APITestTaskSuspended(View):
#
#     def post(self, request, *args, **kwargs):
#         """
#         暂停API任务
#         :param request:
#         :param args:
#         :param kwargs:
#         :return:
#         """
#         body = request.body
#         if not body:
#             return response_success()
#         data = json.loads(body)
#         api_task = APITestTask.objects.get(id=data["api_test_task_id"])
#         api_task.status = 2
#         api_task.save()
#
#         return response_success("暂停API任务成功")
#
#
# class ApiTestTaskView(View):
#
#     def get(self, request, api_test_task_id, *args, **kwargs):
#         """
#         获取单个API任务
#         :param request:
#         :param api_test_task_id: API任务ID
#         :param args:
#         :param kwargs:
#         :return:
#         """
#         api_test_task = APITestTask.objects.get(id=api_test_task_id)
#         return response_success(model_to_dict(api_test_task))
#
#     def delete(self, request, api_test_task_id, *args, **kwargs):
#         """
#         删除API任务
#         :param request:
#         :param api_test_task_id:任务ID
#         :param args:
#         :param kwargs:
#         :return:
#         """
#         # 移除原来的任务
#         # remove_task(str(api_test_task_id))
#         # logger.info(scheduler.get_jobs())
#         APITestTask.objects.get(id=api_test_task_id).delete()
#
#         return response_success("删除API任务成功")
#
#     def put(self, request, *args, **kwargs):
#         """
#         创建API测试任务
#         :param request:
#         :param args:
#         :param kwargs:
#         :return:
#         """
#         body = request.body
#         if not body:
#             return response_success()
#         data = json.loads(body)
#
#         form = ApiTestTaskForm(data)
#         if form.is_valid():
#             if data['api_test_task_id'] == 0:
#                 APITestTask.objects.create(**form.cleaned_data)
#                 # # 如果任务状态为False那么就暂停
#                 # if api_task.timing_task_status == "false":
#                 #     run_timing_task(api_task.id)
#                 #     pause_task(api_task.id)
#                 #     logger.info(scheduler.get_jobs())
#                 #     return response_success("创建API测试任务成功")
#                 # else:
#                 #     # 然后开启修改后的任务
#                 #     run_timing_task(str(api_task.id))
#                 #     logger.info(scheduler.get_jobs())
#                 return response_success("创建API测试任务成功")
#             # else:
#             #     return response_success("创建API测试任务失败")
#         else:
#             raise MyException()
#
#     def post(self, request, api_test_task_id, *args, **kwargs):
#         """
#         更改UI测试任务
#         :param request:
#         :param api_test_task_id: API测试任务ID
#         :param args:
#         :param kwargs:
#         :return:
#         """
#         body = request.body
#         if not body:
#             return response_success()
#         data = json.loads(body)
#         form = ApiTestTaskForm(data)
#         if form.is_valid():
#             api_task = APITestTask.objects.get(id=api_test_task_id)
#             api_task.api_test_task_name = data['api_test_task_name']
#             api_task.describe = data['describe']
#             api_task.cases = data['cases']
#             api_task.api_project_id = data['api_project_id']
#             api_task.api_send_email = data['api_send_email']
#             api_task.api_send_enterprise_wechat = data['api_send_enterprise_wechat']
#             api_task.api_environment_id = data['api_environment_id']
#             api_task.database_id = data['database_id']
#             api_task.time_interval_seconds = data['time_interval_seconds']
#             api_task.time_interval_hours = data['time_interval_hours']
#             api_task.time_interval_minutes = data['time_interval_minutes']
#             api_task.time_interval_day = data['time_interval_day']
#             api_task.end_time = data['end_time']
#             api_task.starting_time = data['starting_time']
#             api_task.timing_task_status = data['timing_task_status']
#             api_task.save()
#
#             # logger.info(scheduler.get_jobs())
#
#             # # 移除原来的任务
#             # remove_task(api_task.id)
#             # # 然后开启修改后的任务
#             # run_timing_task(api_task.id)
#             # 如果任务状态为False那么就暂停
#             # if api_task.timing_task_status == "false":
#             #     remove_task(api_task.id)
#             #     run_timing_task(api_task.id)
#             #     pause_task(api_task.id)
#             # else:
#             #     # 移除原来的任务
#             #     remove_task(api_task.id)
#             #     # 然后开启修改后的任务
#             #     run_timing_task(api_task.id)
#
#             return response_success("编辑API测试任务成功")
#         else:
#             raise MyException()
#
#
# class GetApiCaseTree(View):
#
#     def get(self, request, api_project_id, *args, **kwargs):
#         """
#         获取Api测试用例树形结构
#         :param request:
#         :param api_project_id:
#         :param args:
#         :param kwargs:
#         :return:
#         """
#         api_projects = APIProject.objects.filter(id=api_project_id)
#         data_list = []
#         for api_project in api_projects:
#             api_project_dict = {
#                 "api_project_name": api_project.api_project_name,
#                 "isParent": True
#             }
#             api_case_list = []
#             api_test_case = ApiBusinessTest.objects.filter(api_project_id=api_project.id)
#             for api_test_cases in api_test_case:
#                 api_case_dict = {
#                     "api_test_case_name": api_test_cases.api_business_test_name,
#                     "isParent": False,
#                     "api_test_cases_id": api_test_cases.id
#                 }
#                 api_case_list.append(api_case_dict)
#
#             api_project_dict["children"] = api_case_list
#             data_list.append(api_project_dict)
#         return response_success(data_list)
#
#     def post(self, request, api_test_task_id, *args, **kwargs):
#         """
#         修改API用例树形结构
#         :param request:
#         :param api_test_task_id: api任务id
#         :param args:
#         :param kwargs:
#         :return:
#         """
#
#         if api_test_task_id == "":
#             return MyException("任务id不能为空")
#         api_test_task = APITestTask.objects.get(id=api_test_task_id)
#         api_case_list_data = json.loads(api_test_task.cases)
#         api_task_data = {
#             "api_test_task_name": api_test_task.api_test_task_name,
#             "describe": api_test_task.describe
#         }
#         api_projects = APIProject.objects.all()
#         data_list = []
#         for api_project in api_projects:
#             api_project_dict = {
#                 "api_project_name": api_project.api_project_name,
#                 "isParent": True
#             }
#             ui_case_list = []
#             api_test_cases = ApiBusinessTest.objects.filter(api_project_id=api_project.id)
#             for api_test_case in api_test_cases:
#                 if api_test_case.id in api_case_list_data:
#                     ui_case_dict = {
#                         "api_test_case_name": api_test_case.ui_test_case_name,
#                         "api_test_case_id": api_test_case.id,
#                         "isParent": False,
#                         "checked": True,
#                     }
#                 else:
#                     ui_case_dict = {
#                         "api_test_case_name": api_test_case.ui_test_case_name,
#                         "api_test_case_id": api_test_case.id,
#                         "isParent": False,
#                         "checked": False,
#                     }
#                 ui_case_list.append(ui_case_dict)
#
#             api_project_dict["children"] = ui_case_list
#             data_list.append(api_project_dict)
#         api_task_data["cases"] = data_list
#         return response_success(api_task_data)
#
#
# class CheckApiResultList(View):
#
#     def get(self, request, api_test_task_id, size_page, page, *args, **kwargs):
#         """
#         查看API测试报告列表
#         :param page:
#         :param size_page:
#         :param request:
#         :param api_test_task_id:
#         :param args:
#         :param kwargs:
#         :return:
#         """
#         if api_test_task_id == "":
#             return response_failed({"status": 10102, "message": "api_test_task_id不能为空"})
#         r = APITestResult.objects.filter(api_task_id=api_test_task_id).order_by('-create_time')
#         data = []
#         for i in r:
#             result = {
#                 "id": i.id,
#                 "api_test_result_name": i.api_test_result_name,
#                 "create_time": i.create_time,
#                 "api_error_total_number": i.api_error_total_number,
#                 "api_successful_total_number": i.api_successful_total_number,
#                 "api_total_number": i.api_total_number
#
#             }
#             data.append(result)
#         api_result_total = len(data)
#         p = Paginator(data, size_page)
#
#         if int(page) > int(p.num_pages):
#             page1 = p.page(p.num_pages)
#             current_page = page1.object_list
#         else:
#             page1 = p.page(page)
#             current_page = page1.object_list
#         return response_success({'status': 10102, 'data': current_page, 'api_result_total': api_result_total})
#
#
# class CheckApiResult(View):
#     def get(self, request, api_test_result_id, size_page, page, *args, **kwargs):
#         """
#         查看任务--测试报告列表--测试结果列表
#         :param size_page: 展示条数
#         :param page: 页数
#         :param request:
#         :param api_test_result_id:
#         :param args:
#         :param kwargs:
#         :return:
#         """
#         if api_test_result_id == "":
#             return response_failed({"status": 10102, "message": "api_test_task_id不能为空"})
#         r = APITestResultAssociated.objects.filter(api_result_id=api_test_result_id)
#
#         data = []
#         for i in r:
#             result = {
#                 "id": i.id,
#                 "api_test_case_name": i.api_test_case_name,
#                 "api_task_name": i.api_task.api_test_task_name,
#                 "api_business_test_name": i.api_business_test_name,
#                 "api_error": i.api_error,
#                 "api_successful": i.api_successful,
#                 "abnormal": i.abnormal,
#                 "json_extract_variable_conversion": i.json_extract_variable_conversion,
#                 "api_assertion_results": i.api_assertion_results,
#                 "api_request_results": i.api_request_results,
#                 "api_result_id": i.api_result_id,
#                 "api_task_id": i.api_task_id,
#                 "create_time": arrow.get(str(i.create_time)).format('YYYY-MM-DD HH:mm:ss'),
#             }
#             data.append(result)
#         p = Paginator(data, size_page)
#         if int(page) > int(p.num_pages):
#             page1 = p.page(p.num_pages)
#             current_page = page1.object_list
#         else:
#             page1 = p.page(page)
#             current_page = page1.object_list
#
#         api_result = APITestResult.objects.get(id=api_test_result_id)
#
#         case_result_total = [int(api_result.api_successful_total_number), int(api_result.api_error_total_number)]
#
#         return response_success({'status': 10102, 'data': current_page, "case_result_total": case_result_total})
#
#     def post(self, request, api_test_case_result_id, *args, **kwargs):
#         """
#         查看任务--测试报告列表--测试结果列表--单独测试用例报告
#         :param request:
#         :param api_test_case_result_id:API测试结果关联表的ID
#         :param args:
#         :param kwargs:
#         :return:
#         """
#         if api_test_case_result_id == "":
#             return response_failed({"status": 10102, "message": "api_test_case_result_id不能为空"})
#         r = APITestResultAssociated.objects.filter(id=api_test_case_result_id)
#         data = []
#         for i in r:
#             result = {
#                 "id": i.id,
#                 "api_test_case_name": i.api_test_case_name,
#                 "api_task_name": i.api_task.api_test_task_name,
#                 "api_business_test_name": i.api_business_test_name,
#                 "api_error": i.api_error,
#                 "api_successful": i.api_successful,
#                 "abnormal": i.abnormal,
#                 "json_extract_variable_conversion": i.json_extract_variable_conversion,
#                 "api_assertion_results": i.api_assertion_results,
#                 "api_request_results": i.api_request_results,
#                 "api_result_id": i.api_result_id,
#                 "api_task_id": i.api_task_id,
#                 "create_time": i.create_time,
#                 "api_variable_results": i.api_variable_results,
#                 "api_header": i.api_header,
#                 "api_url": i.api_url,
#                 "api_body": i.api_body
#             }
#
#             data.append(result)
#         return response_success({'status': 10102, 'data': data})
#
#     def delete(self, request, api_test_result_id, *args, **kwargs):
#         """
#         查看任务--测试报告列表--删除测试报告
#         :param request:
#         :param api_test_result_id:API测试结果关联表的ID
#         :param args:
#         :param kwargs:
#         :return:
#         """
#         if api_test_result_id == "":
#             return response_failed({"status": 10102, "message": "api_test_result_id不能为空"})
#         APITestResult.objects.get(id=api_test_result_id).delete()
#
#         return response_success("删除测试报告成功")
#
#
# class CheckApiResultErrorList(View):
#     def get(self, request, api_test_result_id, size_page, page, *args, **kwargs):
#         """
#         查看任务--测试报告列表--测试结果列表
#         :param size_page: 展示条数
#         :param page: 页数
#         :param request:
#         :param api_test_result_id:
#         :param args:
#         :param kwargs:
#         :return:
#         """
#         if api_test_result_id == "":
#             return response_failed({"status": 10102, "message": "api_test_task_id不能为空"})
#         r = APITestResultAssociated.objects.filter(api_result_id=api_test_result_id, api_error=1)
#         data = []
#         for i in r:
#             result = {
#                 "id": i.id,
#                 "api_test_case_name": i.api_test_case_name,
#                 "api_task_name": i.api_task.api_test_task_name,
#                 "api_business_test_name": i.api_business_test_name,
#                 "api_error": i.api_error,
#                 "api_successful": i.api_successful,
#                 "abnormal": i.abnormal,
#                 "json_extract_variable_conversion": i.json_extract_variable_conversion,
#                 "api_assertion_results": i.api_assertion_results,
#                 "api_request_results": i.api_request_results,
#                 "api_result_id": i.api_result_id,
#                 "api_task_id": i.api_task_id,
#                 "create_time": arrow.get(str(i.create_time)).format('YYYY-MM-DD HH:mm:ss')
#             }
#             data.append(result)
#         p = Paginator(data, size_page)
#
#         if int(page) > int(p.num_pages):
#             page1 = p.page(p.num_pages)
#             current_page = page1.object_list
#         else:
#             page1 = p.page(page)
#             current_page = page1.object_list
#         api_result = APITestResult.objects.get(id=api_test_result_id)
#
#         case_result_total = [int(api_result.api_successful_total_number), int(api_result.api_error_total_number)]
#         return response_success({'status': 10102, 'data': current_page, "case_result_total": case_result_total})
#
#
# class PerformApiTask(View):
#
#     def post(self, request, api_test_task_id, *args, **kwargs):
#         """
#         执行当前API任务
#         :param request:
#         :param api_test_task_id:
#         :param args:
#         :param kwargs:
#         :return:
#         """
#
#         if api_test_task_id == "":
#             return response_failed({"status": 10200, "message": "api_test_task_id is null"})
#
#         # 1.在执行线程之前，判断当前任务是否在执行
#         api_tasks = APITestTask.objects.get(id=api_test_task_id)
#         if api_tasks.status == 1:
#             return response_failed({"status": 10200, "message": "当前该任务正在执行！"})
#         else:
#             # 2. 修改任务的状态为：1-执行中
#             api_tasks = APITestTask.objects.get(id=api_test_task_id)
#             api_tasks.status = 1
#             api_tasks.save()
#             # 通过多线程运行测试任务
#             TaskThread(api_test_task_id).run()
#             return response_success({"status": 10200, "message": "任务开始执行！"})
#
#     def get(self, request, *args, **kwargs):
#         """
#         执行所有API任务
#         :param request:
#         :param args:
#         :param kwargs:
#         :return:
#         """
#         api_test_task = APITestTask.objects.filter(timing_task_status="true")
#         for tasks in api_test_task:
#
#             # 1.在执行线程之前，判断当前有没有任务在执行
#             api_tasks = APITestTask.objects.get(id=tasks.id)
#             if api_tasks.status == 1:
#                 logger.info("该任务正在执行中：" + tasks.api_test_task_name)
#                 continue
#             else:
#                 # 2. 修改任务的状态为：1-执行中
#                 api_tasks = APITestTask.objects.get(id=tasks.id)
#                 api_tasks.status = 1
#                 api_tasks.save()
#                 # 通过多线程运行测试任务
#                 TaskThread(tasks.id).run()
#         return response_success({"status": 10200, "message": "任务开始执行！"})
#
#
# class ApiServiceChangesTask(View):
#
#     def post(self, request, *args, **kwargs):
#         """
#         获取YaPi项目名称
#         :param request:
#         :param args:
#         :param kwargs:
#         :return:
#         """
#         body = request.body
#         if not body:
#             return response_success()
#         data = json.loads(body)
#         for ser in data['service']:
#             # 1.在执行线程之前，判断当前任务是否在执行
#             api_tasks = APITestTask.objects.get(api_test_task_name=ser)
#             if api_tasks.status == 1:
#                 return response_failed({"status": 10200, "message": "当前该任务正在执行！"})
#             else:
#                 # 2. 修改任务的状态为：1-执行中
#                 api_tasks = APITestTask.objects.get(api_test_task_name=ser)
#                 api_tasks.status = 1
#                 api_tasks.save()
#                 # 通过多线程运行测试任务
#                 TaskThread(api_tasks.id).run()
#
#         return response_success()
#
# # def task_func(task_id):
# #     api_task = APITestTask.objects.get(id=task_id)
# #     api_task.status = 1
# #     api_task.save()
# #     TaskThread(task_id).run()
# #
# #
# # # 添加任务
# # def add_task(id, func, starting_time, end_time, days, hours, minutes, second, scheduler, kwargs):
# #     """添加一个定时任务"""
# #     """
# #     id: 任务id
# #     func： 执行的方法
# #     from_date： 起始时间
# #     interval_time： 间隔时间
# #     scheduler： 执行器  scheduler = BackgroundScheduler()
# #     kwargs： 方法需要的参数dict
# #     """
# #     if len(starting_time) != 0 or len(end_time) != 0:
# #         pass
# #     else:
# #         starting_time, end_time = None, None
# #     scheduler.add_job(func, 'interval', start_date=starting_time, end_date=end_time,
# #                       days=days, hours=hours, minutes=minutes,
# #                       seconds=second, id=id, replace_existing=True, kwargs=kwargs)
# #
# #
# # # 暂停任务
# # def pause_task(task_id):
# #     """暂停任务"""
# #     scheduler.pause_job(str(task_id))
# #
# #
# # # 恢复任务
# # def resume_task(task_id):
# #     """恢复任务"""
# #     scheduler.resume_job(str(task_id))
# #
# #
# # # 移除任务
# # def remove_task(task_id):
# #     """移除任务
# #     task_id：移除的任务id
# #     """
# #     scheduler.remove_job(str(task_id))
# #
# #
# # # 移除任务
# # def get_timing_task():
# #     """获取任务
# #     task_id：移除的任务id
# #     """
# #     scheduler.get_jobs()
# #
# #
# # # 执行任务
# # def run_timing_task(task_id):
# #     """执行定时任务"""
# #     try:
# #         api_task = APITestTask.objects.filter(id=task_id).get()
# #         add_task(str(api_task.id), task_func, api_task.starting_time, api_task.end_time,
# #                  api_task.time_interval_day, api_task.time_interval_hours, api_task.time_interval_minutes,
# #                  api_task.time_interval_seconds, scheduler, kwargs={"task_id": api_task.id})
# #     except ConflictingIdError:
# #         return response_success({"ok": "任务重复执行"})
# #     except ObjectDoesNotExist:
# #         return response_success({"ok": "任务id不存在"})
# #
# #
# # # 启动django时会把任务状态为True的任务，启动，为False的任务启动然后暂停
# # scheduler = BackgroundScheduler(timezone='Asia/Shanghai')
# # taskList = APITestTask.objects.filter(timing_task_status="true")
# # for task in taskList:
# #     # 开启定时任务
# #     run_timing_task(str(task.id))
# #     logger.info("开启了定时任务" + str(task.id))
# # taskList = APITestTask.objects.filter(timing_task_status="false")
# # for task in taskList:
# #     # 开启定时任务
# #     logger.info("暂停定时任务" + str(task.id))
# #     run_timing_task(str(task.id))
# #     pause_task(str(task.id))
# # # scheduler.start()
# #
# # # scheduler.get_jobs()
# # logger.info(scheduler.get_jobs())
# #
# # import sys, socket
# #
# # try:
# #     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# #     sock.bind(("127.0.0.1", 47200))
# # except socket.error:
# #     print("!!!scheduler already started, DO NOTHING")
# #
# # else:
# #     scheduler.start()
# #     scheduler.get_jobs()
# #     logger.info(scheduler.get_jobs())
# #     print("scheduler started")