package com.test.test.controller;

import java.util.List;

import com.test.test.domain.PerformanceTest;
import com.test.test.domain.TestCase;
import com.test.test.domain.qo.PerformanceTestQO;
import com.test.test.domain.vo.PerformanceTestVO;
import com.test.test.service.IPerformanceTestCaseReportService;
import com.test.test.service.IPerformanceTestService;
import com.test.test.service.ITestCaseService;
import com.test.test.task.DynamicTaskManager;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.test.common.annotation.Log;
import com.test.common.core.controller.BaseController;
import com.test.common.core.domain.AjaxResult;
import com.test.common.enums.BusinessType;
import com.test.common.utils.poi.ExcelUtil;
import com.test.common.core.page.TableDataInfo;

/**
 * 性能测试Controller
 *
 * @author test
 * @date 2025-04-14
 */
@RestController
@RequestMapping("/test/performanceTest")
@Slf4j
public class PerformanceTestController extends BaseController {
    @Value("${test.jmeterHomePath:/opt/apache-jmeter}")
    private String jmeterHomePath;
    @Autowired
    private IPerformanceTestService performanceTestService;
    @Autowired
    private ITestCaseService testCaseService;
    @Autowired
    private IPerformanceTestCaseReportService performanceTestCaseReportService;
    @Autowired
    private DynamicTaskManager dynamicTaskManager;


    /**
     * 查询性能测试列表
     */
//    @PreAuthorize("@ss.hasPermi('system:test:list')")
    @GetMapping("/list")
    public TableDataInfo list(PerformanceTest performanceTest) {
        startPage();
        List<PerformanceTest> list = performanceTestService.selectPerformanceTestList(performanceTest);
        return getDataTable(list);
    }

    @GetMapping("/testCaseList")
    public TableDataInfo testCaseList(TestCase testCase) {
        startPage();
        List<TestCase> testCaseList = testCaseService.selectTestCaseList(testCase);
        return getDataTable(testCaseList);
    }

    /**
     * 导出性能测试列表
     */
    // @PreAuthorize("@ss.hasPermi('system:test:export')")
    @Log(title = "性能测试", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PerformanceTest performanceTest) {
        List<PerformanceTest> list = performanceTestService.selectPerformanceTestList(performanceTest);
        ExcelUtil<PerformanceTest> util = new ExcelUtil<PerformanceTest>(PerformanceTest.class);
        util.exportExcel(response, list, "性能测试数据");
    }

    /**
     * 获取性能测试详细信息
     */
    // @PreAuthorize("@ss.hasPermi('system:test:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(performanceTestService.selectPerformanceTestById(id));
    }

    /**
     * 新增保存性能测试
     */
    // @PreAuthorize("@ss.hasPermi('system:test:add')")
    @Log(title = "性能测试", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody PerformanceTestQO performanceTestQO) {
        try {
            Long l = performanceTestService.insertPerformanceTest(performanceTestQO);
            // 获取新增的任务完整信息
            PerformanceTestVO newTaskVo = performanceTestService.selectPerformanceTestById(l);
            PerformanceTest entity = new PerformanceTest();
            entity.setId(newTaskVo.getId());
            entity.setCrontab(newTaskVo.getCrontab());
            entity.setCrontabStatus(newTaskVo.getCrontabStatus());
            entity.setDelFlag(newTaskVo.getDelFlag());
            // 如果任务是定时任务且状态为启用，则添加到定时任务管理器
            if (entity.getCrontabStatus() == 1) {
                dynamicTaskManager.addNewTask(entity);
            }
            return success(l);
        } catch (Exception e) {
            log.info("新增失败!", e);
            return error("新增失败!");
        }
    }


    /**
     * 新增保存并执行性能测试
     */
    @Log(title = "性能测试", businessType = BusinessType.INSERT)
    @PostMapping("/addAndExecute")
    public AjaxResult addAndExecute(@RequestBody PerformanceTestQO performanceTestQO) {
        try {
            Long l = performanceTestService.insertPerformanceTest(performanceTestQO);
            // 获取新增的任务完整信息
            PerformanceTestVO newTaskVo = performanceTestService.selectPerformanceTestById(l);
            PerformanceTest entity = new PerformanceTest();
            entity.setId(newTaskVo.getId());
            entity.setCrontab(newTaskVo.getCrontab());
            entity.setCrontabStatus(newTaskVo.getCrontabStatus());
            entity.setDelFlag(newTaskVo.getDelFlag());
            // 如果任务是定时任务且状态为启用，则添加到定时任务管理器
            if (entity.getCrontabStatus() == 1) {
                dynamicTaskManager.addNewTask(entity);
            }
            // 执行性能测试
            try {
                Long l1 = performanceTestCaseReportService.executePerformanceTestAndReport(l, jmeterHomePath, 2);
                return success(l1);
            } catch (Exception e) {
                log.error("执行失败!", e);
                return error("执行失败!");
            }
        } catch (Exception e) {
            log.error("新增并执行失败!", e);
            return error("新增并执行失败!");
        }
    }

    /**
     * ·
     */
    // @PreAuthorize("@ss.hasPermi('system:test:edit')")
    @Log(title = "性能测试", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PerformanceTestQO performanceTestQO) {
        try {
            PerformanceTestVO originalTask  = performanceTestService.selectPerformanceTestById(performanceTestQO.getId());
            Long l = performanceTestService.updatePerformanceTest(performanceTestQO);
            PerformanceTestVO updatedTask  = performanceTestService.selectPerformanceTestById(performanceTestQO.getId());
            // 如果crontab或crontab_status被修改了，则更新定时任务
            if (!updatedTask.getCrontab().equals(originalTask.getCrontab())
                    || updatedTask.getCrontabStatus() != originalTask.getCrontabStatus()) {
                PerformanceTest entity = new PerformanceTest();
                entity.setId(updatedTask.getId());
                entity.setCrontab(updatedTask.getCrontab());
                entity.setCrontabStatus(updatedTask.getCrontabStatus());
                entity.setDelFlag(updatedTask.getDelFlag());
                dynamicTaskManager.updateTask(entity);
            }
            return success(l);
        } catch (Exception e) {
            log.error("修改失败!", e);
            return error("修改失败!");
        }
    }



    @Log(title = "性能测试", businessType = BusinessType.UPDATE)
    @PutMapping("/editAndExecute")
    public AjaxResult editAndExecute(@RequestBody PerformanceTestQO performanceTestQO) {
        try {
            PerformanceTestVO originalTask  = performanceTestService.selectPerformanceTestById(performanceTestQO.getId());
            Long l = performanceTestService.updatePerformanceTest(performanceTestQO);
            PerformanceTestVO updatedTask  = performanceTestService.selectPerformanceTestById(performanceTestQO.getId());
            // 如果crontab或crontab_status被修改了，则更新定时任务
            if (!updatedTask.getCrontab().equals(originalTask.getCrontab())
                    || updatedTask.getCrontabStatus() != originalTask.getCrontabStatus()) {
                PerformanceTest entity = new PerformanceTest();
                entity.setId(updatedTask.getId());
                entity.setCrontab(updatedTask.getCrontab());
                entity.setCrontabStatus(updatedTask.getCrontabStatus());
                entity.setDelFlag(updatedTask.getDelFlag());
                dynamicTaskManager.updateTask(entity);
            }
            try {
                Long l1 = performanceTestCaseReportService.executePerformanceTestAndReport(l, jmeterHomePath, 2);
                return success(l1);
            } catch (Exception e) {
                log.error("执行失败!", e);
                return error("执行失败!");
            }
        } catch (Exception e) {
            log.error("修改并执行失败!", e);
            return error("修改并执行失败!");
        }
    }

    /**
     * 删除性能测试
     */
    // @PreAuthorize("@ss.hasPermi('system:test:remove')")
    @Log(title = "性能测试", businessType = BusinessType.UPDATE)
    @PutMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        dynamicTaskManager.removeTasks(ids);
        return toAjax(performanceTestService.deletePerformanceTestByIds(ids));
    }

    /**
     * 立即执行性能测试
     */
    // @PreAuthorize("@ss.hasPermi('system:test:remove')")
    @GetMapping("/executeNow")
    public AjaxResult executeNow(@RequestParam Long id) {
        Long l1 = performanceTestCaseReportService.executePerformanceTestAndReport(id, jmeterHomePath, 2);
        return success(l1);
    }
}
