package com.erp.task.controller;

import com.erp.task.entity.ScheduledTask;
import com.erp.task.enums.TaskStatus;
import com.erp.task.repository.ScheduledTaskRepository;
import com.erp.task.service.TaskExecutor;
import com.erp.task.scheduler.TaskScheduler;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * XXL-Job兼容接口
 * 提供与XXL-Job Admin相同的API接口，方便对接
 */
@Tag(name = "XXL-Job兼容", description = "兼容XXL-Job调度器的API接口")
@Slf4j
@RestController
@RequestMapping("/api/xxl-job")
@RequiredArgsConstructor
public class XxlJobCompatibleController {

    private final ScheduledTaskRepository taskRepository;
    private final TaskExecutor taskExecutor;
    private final TaskScheduler taskScheduler;

    @Operation(summary = "获取所有任务")
    @GetMapping("/jobinfo/pageList")
    public ResponseEntity<Map<String, Object>> pageList(
            @RequestParam(defaultValue = "1") int start,
            @RequestParam(defaultValue = "20") int length,
            @RequestParam(required = false) String jobGroup,
            @RequestParam(required = false) String jobName,
            @RequestParam(required = false) Integer jobStatus) {

        List<ScheduledTask> allTasks = taskRepository.findAll();
        List<ScheduledTask> filtered = allTasks.stream()
                .filter(t -> t.getStatus() != TaskStatus.DELETED)
                .filter(t -> jobGroup == null || jobGroup.equals(t.getTaskGroup()))
                .filter(t -> jobName == null || t.getTaskName().contains(jobName))
                .filter(t -> jobStatus == null || jobStatus.equals(mapStatus(t.getStatus())))
                .collect(Collectors.toList());

        int fromIndex = start;
        int toIndex = Math.min(start + length, filtered.size());
        List<ScheduledTask> page = fromIndex < filtered.size()
                ? filtered.subList(fromIndex, toIndex)
                : List.of();

        List<Map<String, Object>> records = page.stream().map(this::toXxlJobInfo).collect(Collectors.toList());

        Map<String, Object> result = new HashMap<>();
        result.put("recordsTotal", allTasks.size());
        result.put("recordsFiltered", filtered.size());
        result.put("data", records);

        return ResponseEntity.ok(result);
    }

    @Operation(summary = "添加任务")
    @PostMapping("/jobinfo/add")
    public ResponseEntity<Map<String, Object>> add(@RequestBody Map<String, Object> params) {
        // 简化实现，参考实际XXL-Job接口
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "success");
        result.put("content", 1);
        return ResponseEntity.ok(result);
    }

    @Operation(summary = "更新任务")
    @PostMapping("/jobinfo/update")
    public ResponseEntity<Map<String, Object>> update(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "success");
        return ResponseEntity.ok(result);
    }

    @Operation(summary = "删除任务")
    @PostMapping("/jobinfo/remove")
    public ResponseEntity<Map<String, Object>> remove(@RequestParam Long id) {
        taskRepository.findById(id).ifPresent(task -> {
            task.setStatus(TaskStatus.DELETED);
            taskRepository.save(task);
        });

        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "success");
        return ResponseEntity.ok(result);
    }

    @Operation(summary = "停止任务")
    @PostMapping("/jobinfo/stop")
    public ResponseEntity<Map<String, Object>> stop(@RequestParam Long id) {
        taskRepository.findById(id).ifPresent(task -> {
            taskScheduler.pauseJob(task);
            task.setStatus(TaskStatus.STOPPED);
            taskRepository.save(task);
        });

        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "success");
        return ResponseEntity.ok(result);
    }

    @Operation(summary = "启动任务")
    @PostMapping("/jobinfo/start")
    public ResponseEntity<Map<String, Object>> start(@RequestParam Long id) {
        taskRepository.findById(id).ifPresent(task -> {
            taskScheduler.scheduleJob(task);
            task.setStatus(TaskStatus.RUNNING);
            taskRepository.save(task);
        });

        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "success");
        return ResponseEntity.ok(result);
    }

    @Operation(summary = "触发任务执行")
    @PostMapping("/jobinfo/trigger")
    public ResponseEntity<Map<String, Object>> trigger(
            @RequestParam Long id,
            @RequestParam(required = false) String executorParams,
            @RequestParam(required = false) Integer triggerType) {

        taskRepository.findById(id).ifPresent(task -> {
            taskExecutor.execute(task);
        });

        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "success");
        return ResponseEntity.ok(result);
    }

    @Operation(summary = "获取任务分组")
    @GetMapping("/jobgroup/pageList")
    public ResponseEntity<Map<String, Object>> jobGroupPageList() {
        List<Object[]> groupCounts = taskRepository.countByGroup();

        List<Map<String, Object>> groups = groupCounts.stream().map(row -> {
            Map<String, Object> group = new HashMap<>();
            group.put("id", row[0]);
            group.put("title", row[0]);
            group.put("appname", row[0]);
            group.put("addressType", 0);
            return group;
        }).collect(Collectors.toList());

        Map<String, Object> result = new HashMap<>();
        result.put("recordsTotal", groups.size());
        result.put("recordsFiltered", groups.size());
        result.put("data", groups);

        return ResponseEntity.ok(result);
    }

    /**
     * 转换为XXL-Job格式
     */
    private Map<String, Object> toXxlJobInfo(ScheduledTask task) {
        Map<String, Object> info = new HashMap<>();
        info.put("id", task.getId());
        info.put("jobGroup", task.getTaskGroup());
        info.put("jobName", task.getTaskName());
        info.put("jobDesc", task.getDescription());
        info.put("addTime", task.getCreatedAt());
        info.put("updateTime", task.getUpdatedAt());
        info.put("glueType", "BEAN");
        info.put("jobType", 0);
        info.put("jobStatus", mapStatus(task.getStatus()));
        info.put("cronGenContent", task.getCronExpression());
        info.put("routeStrategy", "FIRST");
        info.put("misfireStrategy", "DO_NOTHING");
        info.put("executorBlockStrategy", task.getConcurrent() ? "SERIAL_EXECUTION" : "DISCARD_LATER");
        info.put("executorTimeout", task.getTimeout() != null ? task.getTimeout() : 0);
        info.put("executorFailRetryCount", task.getMaxRetries());
        info.put("glueRemark", task.getRemark());
        return info;
    }

    /**
     * 状态映射
     */
    private Integer mapStatus(TaskStatus status) {
        return switch (status) {
            case RUNNING -> 1;
            case STOPPED, PAUSED -> 0;
            case DRAFT -> 5;
            default -> 0;
        };
    }
}
