package com.erp.task.controller;

import com.erp.task.dto.*;
import com.erp.task.service.ScheduledTaskService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import com.erp.common.core.model.PageResponse;
import java.util.Map;

/**
 * 定时任务管理接口
 */
@Tag(name = "定时任务管理", description = "定时任务CRUD和调度管理")
@RestController
@RequestMapping("/api/task")
@RequiredArgsConstructor
public class ScheduledTaskController {

    private final ScheduledTaskService taskService;

    @Operation(summary = "创建任务")
    @PostMapping
    public ResponseEntity<ScheduledTaskDTO> create(@Valid @RequestBody TaskCreateRequest request) {
        return ResponseEntity.ok(taskService.create(request));
    }

    @Operation(summary = "更新任务")
    @PutMapping("/{id}")
    public ResponseEntity<ScheduledTaskDTO> update(
            @PathVariable Long id,
            @Valid @RequestBody TaskUpdateRequest request) {
        request.setId(id);
        return ResponseEntity.ok(taskService.update(request));
    }

    @Operation(summary = "删除任务")
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        taskService.delete(id);
        return ResponseEntity.ok().build();
    }

    @Operation(summary = "查询任务详情")
    @GetMapping("/{id}")
    public ResponseEntity<ScheduledTaskDTO> getById(@PathVariable Long id) {
        return ResponseEntity.ok(taskService.getById(id));
    }

    @Operation(summary = "分页查询任务")
    @GetMapping("/list")
    public ResponseEntity<PageResponse<ScheduledTaskDTO>> query(
            @Parameter(description = "任务名称") @RequestParam(required = false) String taskName,
            @Parameter(description = "任务分组") @RequestParam(required = false) String taskGroup,
            @Parameter(description = "状态") @RequestParam(required = false) String status,
            @Parameter(description = "任务类型") @RequestParam(required = false) String taskType,
            @Parameter(description = "负责人") @RequestParam(required = false) String owner,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "20") Integer pageSize,
            @Parameter(description = "排序字段") @RequestParam(defaultValue = "createdAt") String sortBy,
            @Parameter(description = "排序方向") @RequestParam(defaultValue = "DESC") String sortOrder) {

        TaskQueryRequest request = new TaskQueryRequest();
        request.setTaskName(taskName);
        request.setTaskGroup(taskGroup);
        request.setStatus(status);
        request.setTaskType(taskType);
        request.setOwner(owner);
        request.setPage(page);
        request.setPageSize(pageSize);
        request.setSortBy(sortBy);
        request.setSortOrder(sortOrder);

        return ResponseEntity.ok(taskService.query(request));
    }

    @Operation(summary = "启动任务")
    @PostMapping("/{id}/start")
    public ResponseEntity<ScheduledTaskDTO> start(@PathVariable Long id) {
        return ResponseEntity.ok(taskService.start(id));
    }

    @Operation(summary = "停止任务")
    @PostMapping("/{id}/stop")
    public ResponseEntity<ScheduledTaskDTO> stop(@PathVariable Long id) {
        return ResponseEntity.ok(taskService.stop(id));
    }

    @Operation(summary = "暂停任务")
    @PostMapping("/{id}/pause")
    public ResponseEntity<ScheduledTaskDTO> pause(@PathVariable Long id) {
        return ResponseEntity.ok(taskService.pause(id));
    }

    @Operation(summary = "恢复任务")
    @PostMapping("/{id}/resume")
    public ResponseEntity<ScheduledTaskDTO> resume(@PathVariable Long id) {
        return ResponseEntity.ok(taskService.resume(id));
    }

    @Operation(summary = "立即执行一次")
    @PostMapping("/{id}/execute")
    public ResponseEntity<Void> executeOnce(@PathVariable Long id) {
        taskService.executeOnce(id);
        return ResponseEntity.ok().build();
    }

    @Operation(summary = "获取运行中的任务")
    @GetMapping("/running")
    public ResponseEntity<List<ScheduledTaskDTO>> getRunningTasks() {
        return ResponseEntity.ok(taskService.getRunningTasks());
    }

    @Operation(summary = "获取任务统计")
    @GetMapping("/stats")
    public ResponseEntity<TaskStatsDTO> getStats() {
        return ResponseEntity.ok(taskService.getStats());
    }

    @Operation(summary = "获取最近执行时间")
    @GetMapping("/{id}/next-fire-times")
    public ResponseEntity<List<LocalDateTime>> getNextFireTimes(
            @PathVariable Long id,
            @RequestParam(defaultValue = "5") int n) {
        return ResponseEntity.ok(taskService.getNextFireTimes(id, n));
    }

    @Operation(summary = "验证Cron表达式")
    @GetMapping("/validate-cron")
    public ResponseEntity<Map<String, Object>> validateCron(
            @RequestParam String cronExpression,
            @RequestParam(required = false, defaultValue = "quartz") String type) {
        boolean valid = taskService.validateCron(cronExpression);
        return ResponseEntity.ok(Map.of(
                "valid", valid,
                "cronExpression", cronExpression,
                "type", type
        ));
    }

    @Operation(summary = "健康检查")
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        return ResponseEntity.ok(Map.of(
                "status", "UP",
                "timestamp", LocalDateTime.now()
        ));
    }
}
