package com.test.test.controller;

import com.test.common.annotation.Log;
import com.test.common.core.controller.BaseController;
import com.test.common.core.domain.AjaxResult;
import com.test.common.core.page.TableDataInfo;
import com.test.common.enums.BusinessType;
import com.test.common.utils.DateUtils;
import com.test.common.utils.SecurityUtils;
import com.test.test.domain.TestTask;
import com.test.test.domain.TestTaskLog;
import com.test.test.domain.TestTaskResult;
import com.test.test.domain.qo.GroupIdQO;
import com.test.test.domain.qo.IDQO;
import com.test.test.service.ITestTaskLogService;
import com.test.test.service.ITestTaskResultService;
import com.test.test.service.ITestTaskService;
import com.test.test.task.TestTaskManager;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 定时任务Controller
 */
@RestController
@RequestMapping("/test/task")
public class TestTaskController extends BaseController {

    @Value("${test.jmeterHomePath:/opt/apache-jmeter}")
    private String jmeterHomePath;

    @Resource
    private ITestTaskService testTaskService;

    @Resource
    private ITestTaskResultService testTaskResultService;

    @Resource
    private ITestTaskLogService taskLogService;

    @Resource
    private TestTaskManager testTaskManager;

    /**
     * 查询定时任务列表
     */
    @GetMapping("/list")
    public TableDataInfo list(@Validated GroupIdQO qo) {
        startPage();
        List<TestTask> list = testTaskService.selectTestTaskList(qo);
        return getDataTable(list);
    }

    /**
     * 查询定时任务执行记录列表
     */
    @GetMapping("/taskResultListByTaskId")
    public TableDataInfo taskResultListByTaskId(@Validated IDQO qo) {
        startPage();
        TestTaskResult testTaskResult = new TestTaskResult();
        testTaskResult.setTaskId(qo.getId());
        List<TestTaskResult> list = testTaskResultService.selectTestTaskResultList(testTaskResult);
        return getDataTable(list);
    }

    /**
     * 查询定时任务操作记录列表
     */
    @GetMapping("/taskLogListByTaskId")
    public TableDataInfo taskLogListByTaskId(@Validated IDQO qo) {
        startPage();
        TestTaskLog testTaskLog = new TestTaskLog();
        testTaskLog.setTaskId(qo.getId());
        List<TestTaskLog> list = taskLogService.selectTestTaskLogList(testTaskLog);
        return getDataTable(list);
    }

    /**
     * 获取定时任务详细信息
     */
    @PostMapping(value = "/detail")
    public AjaxResult getInfo(@RequestBody IDQO qo) {
        return success(testTaskService.selectTestTaskById(qo.getId()));
    }

    /**
     * 新增定时任务
     */
    @Log(title = "定时任务", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody TestTask testTask) {
        try {
            testTask.setCreateBy(getLoginUser().getUsername());
            testTask.setCreateTime(DateUtils.getNowDate());
            int result = testTaskService.insertTestTask(testTask);
            
            // 如果任务状态是启用且没有被删除，则添加到定时任务管理器
            if (testTask.getStatus() == 0 && "0".equals(testTask.getDelFlag())) {
                testTaskManager.addNewTask(testTask);
            }
            
            return toAjax(result);
        } catch (Exception e) {
            return error("新增失败：" + e.getMessage());
        }
    }

    /**
     * 修改定时任务
     */
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody TestTask testTask) {
        try {
            // 获取原任务信息
            TestTask originalTask = testTaskService.selectTestTaskById(testTask.getId()).getTask();
            
            // 更新任务
            int result = testTaskService.updateTestTask(testTask);
            
            // 如果状态或crontab发生变化，更新定时任务
            if (testTask.getStatus() != originalTask.getStatus() || 
                !testTask.getCrontab().equals(originalTask.getCrontab())) {
                testTaskManager.updateTask(testTask);
            }
            
            return toAjax(result);
        } catch (Exception e) {
            return error("修改失败：" + e.getMessage());
        }
    }

    /**
     * 删除定时任务
     */
    @Log(title = "定时任务", businessType = BusinessType.DELETE)
    @PostMapping("/del")
    public AjaxResult remove(@RequestBody IDQO qo) {
        try {
            // 先从定时任务管理器中移除
            testTaskManager.removeTask(qo.getId());
            // 再删除数据库记录
            return toAjax(testTaskService.deleteTestTaskById(qo.getId()));
        } catch (Exception e) {
            return error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 执行任务
     */
    @Log(title = "任务", businessType = BusinessType.OTHER)
    @PostMapping("/run")
    public AjaxResult run(@RequestBody IDQO qo) {
        // 异步执行任务
        String username = SecurityUtils.getUsername();
        CompletableFuture.runAsync(() -> {
            testTaskService.executeTestTaskById(qo.getId(), 2, null, jmeterHomePath, username);
        });
        return toAjax(true);
    }
}
