package com.test.test.service.impl;

import com.test.common.utils.DateUtils;
import com.test.test.domain.*;
import com.test.test.domain.qo.GroupIdQO;
import com.test.test.domain.vo.TestTaskDetailVO;
import com.test.test.mapper.*;
import com.test.test.service.ITestTaskService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 自动化测试Service业务层处理
 */
@Slf4j
@Service
public class TestTaskServiceImpl implements ITestTaskService {

    @Resource
    private TestTaskMapper testTaskMapper;

    @Resource
    private TestTaskCaseMapper testTaskCaseMapper;

    @Resource
    private TestCaseMapper testCaseMapper;

    @Resource
    private TestCaseStepMapper testCaseStepMapper;

    @Resource
    private TestTaskLogMapper testTaskLogMapper;

    @Autowired
    private TaskManagerService taskManagerService;

    /**
     * 查询自动化测试
     */
    @Override
    public TestTaskDetailVO selectTestTaskById(Long id) {
        TestTaskDetailVO testTaskDetailVO = new TestTaskDetailVO();
        testTaskDetailVO.setTask(testTaskMapper.selectTestTaskById(id));
        List<TestTaskDetailVO.TestCaseVo> caseList = new ArrayList<>();
        testTaskCaseMapper.selectTestTaskCaseListByTaskId(id).forEach(testTaskCase -> {
            TestTaskDetailVO.TestCaseVo testCase = new TestTaskDetailVO.TestCaseVo();
            testCase.setSort(testTaskCase.getSort());
            testCase.setTestCase(testCaseMapper.selectTestCaseById(testTaskCase.getCaseId()));
            caseList.add(testCase);
        });
        testTaskDetailVO.setCaseList(caseList);
        return testTaskDetailVO;
    }

    /**
     * 查询自动化测试列表
     */
    @Override
    public List<TestTask> selectTestTaskList(GroupIdQO qo) {
        return testTaskMapper.selectTestTaskList(qo);
    }

    /**
     * 新增自动化测试
     */
    @Override
    public int insertTestTask(TestTask testTask) {
        return testTaskMapper.insertTestTask(testTask);
    }

    /**
     * 修改自动化测试
     */
    @Override
    public int updateTestTask(TestTask testTask) {
        testTask.setUpdateTime(DateUtils.getNowDate());
        return testTaskMapper.updateTestTask(testTask);
    }

    /**
     * 批量删除自动化测试
     */
    @Override
    public int deleteTestTaskByIds(Long[] ids) {
        return testTaskMapper.deleteTestTaskByIds(ids);
    }

    /**
     * 删除自动化测试信息
     */
    @Override
    public int deleteTestTaskById(Long id) {
        return testTaskMapper.deleteTestTaskById(id);
    }

    /**
     * 根据测试任务id执行测试定时任务
     * @param id 测试定时任务id
     * @param triggerType 触发方式：1-定时任务；2-手动
     * @param environment 环境
     * @param jmeterHomePath jmeter安装路径
     * @param operUser 操作人
     * @return 是否执行完成（注：是否成功得看任务结果表）
     */
    @Override
    public boolean executeTestTaskById(Long id, Integer triggerType, String environment, String jmeterHomePath, String operUser) {
        TestTask testTask = testTaskMapper.selectTestTaskById(id);
        if (testTask == null || "2".equals(testTask.getDelFlag())) {
            log.error("定时任务已删除，不能执行！");
            return false;
        }
        TestTaskLog testTaskLog = new TestTaskLog();
        testTaskLog.setTaskId(id);
        testTaskLog.setOperType("执行");
        testTaskLog.setOperDetail("操作人：" + operUser + "提交执行了【" + testTask.getName() + "】定时任务测试用例");
        testTaskLog.setOperUser(operUser);
        testTaskLog.setOperTime(DateUtils.getNowDate());
        testTaskLogMapper.insertTestTaskLog(testTaskLog);
        TestTaskResult testTaskResult = new TestTaskResult();
        testTaskResult.setTaskId(id);
        testTaskResult.setTriggerTime(DateUtils.getNowDate());
        testTaskResult.setTriggerType(triggerType);
        testTaskResult.setEnvironment(environment);
        // 测试步骤总数
        int caseStepCount = 0;
        // 查询关联的测试用例列表
        List<TestTaskCase> testTaskCaseList = testTaskCaseMapper.selectTestTaskCaseListByTaskId(id);
        List<TestCase> testCaseList = new ArrayList<>();
        for (TestTaskCase testTaskCase : testTaskCaseList) {
            TestCase testCase = testCaseMapper.selectTestCaseById(testTaskCase.getCaseId());
            if (testCase != null) {
                testCaseList.add(testCase);
                TestCaseStep testCaseStep = new TestCaseStep();
                testCaseStep.setCaseId(testCase.getId());
                testCaseStep.setDelFlag("0");
                caseStepCount += testCaseStepMapper.selectTestCaseStepList(testCaseStep).size();
            }
        }
        // 用例总数
        int caseCount = testCaseList.size();
        testTaskResult.setCaseCount(caseCount);
        testTaskResult.setCaseStepCount(caseStepCount);
        // 开始执行定时任务逻辑。。。
        if (triggerType == 1) {
            // 添加定时任务定时执行
            taskManagerService.addTask(testTask, jmeterHomePath, testTaskCaseList, testTaskResult);
        } else {
            // 手动立即执行
            taskManagerService.executeTaskWithTestCases(testTask, jmeterHomePath, testTaskCaseList, testTaskResult);
        }
        return true;
    }
}
