package com.qqchen.deploy.backend.workflow.api;

import com.qqchen.deploy.backend.framework.api.Response;
import com.qqchen.deploy.backend.framework.controller.BaseController;
import com.qqchen.deploy.backend.framework.enums.ResponseCode;
import com.qqchen.deploy.backend.workflow.dto.WorkflowCategoryDTO;
import com.qqchen.deploy.backend.workflow.dto.WorkflowDefinitionDTO;
import com.qqchen.deploy.backend.workflow.dto.WorkflowExecutionDTO;
import com.qqchen.deploy.backend.workflow.dto.WorkflowInstanceDTO;
import com.qqchen.deploy.backend.workflow.entity.WorkflowDefinition;
import com.qqchen.deploy.backend.workflow.dto.query.WorkflowDefinitionQuery;
import com.qqchen.deploy.backend.workflow.service.IWorkflowDefinitionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

/**
 * 工作流定义控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/workflow/definition")
@Tag(name = "工作流定义管理", description = "工作流定义管理相关接口")
public class WorkflowDefinitionApiController extends BaseController<WorkflowDefinition, WorkflowDefinitionDTO, Long, WorkflowDefinitionQuery> {

    @Resource
    private IWorkflowDefinitionService workflowDefinitionService;

    @Resource
    private HistoryService historyService;

    @Operation(summary = "保存工作流设计")
    @PostMapping("/design")
    public Response<WorkflowDefinitionDTO> saveWorkflowDesign(@RequestBody WorkflowDefinitionDTO dto) throws Exception {
        return Response.success(workflowDefinitionService.saveWorkflowDesign(dto));
    }

    @GetMapping("/published")
    public Response<List<WorkflowDefinitionDTO>> findPublishedWorkflow() {
        return Response.success(workflowDefinitionService.findPublishedWorkflow());
    }

    @PostMapping("/{workflowDefinitionId}/published")
    public Response<Void> publishedWorkflowDesign(@PathVariable Long workflowDefinitionId) {
        workflowDefinitionService.publishedWorkflowDesign(workflowDefinitionId);
        return Response.success();
    }

//    @Operation(summary = "部署工作流")
//    @PostMapping("/deploy")
//    public Response<WorkflowDefinitionDTO> deployWorkflow(@RequestBody WorkflowDefinitionDTO dto) {
//        return Response.success(workflowDefinitionService.deployWorkflow(dto));
//    }

    @Operation(summary = "挂起工作流实例")
    @PostMapping("/{processInstanceId}/suspend")
    public Response<Void> suspendWorkflow(
        @Parameter(description = "流程实例ID", required = true) @PathVariable String processInstanceId
    ) {
        workflowDefinitionService.suspendWorkflow(processInstanceId);
        return Response.success();
    }

    @Operation(summary = "恢复工作流实例")
    @PostMapping("/{processInstanceId}/resume")
    public Response<Void> resumeWorkflow(
        @Parameter(description = "流程实例ID", required = true) @PathVariable String processInstanceId
    ) {
        workflowDefinitionService.resumeWorkflow(processInstanceId);
        return Response.success();
    }

    @Operation(summary = "查询工作流实例")
    @GetMapping("/instance/{processInstanceId}")
    public Response<WorkflowInstanceDTO> getWorkflowInstance(
        @Parameter(description = "流程实例ID", required = true) @PathVariable String processInstanceId
    ) {
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
            .processInstanceId(processInstanceId)
            .includeProcessVariables()
            .singleResult();

        if (historicProcessInstance == null) {
            return Response.error(ResponseCode.WORKFLOW_NOT_FOUND);
        }

        WorkflowInstanceDTO instanceDTO = new WorkflowInstanceDTO();
//        instanceDTO.setId(historicProcessInstance.getId());
//        instanceDTO.setProcessDefinitionId(historicProcessInstance.getProcessDefinitionId());
//        instanceDTO.setBusinessKey(historicProcessInstance.getBusinessKey());
//        instanceDTO.setStartTime(historicProcessInstance.getStartTime());
//        instanceDTO.setEndTime(historicProcessInstance.getEndTime());
//        instanceDTO.setDurationInMillis(historicProcessInstance.getDurationInMillis());
//        instanceDTO.setStartUserId(historicProcessInstance.getStartUserId());
//        instanceDTO.setStatus(historicProcessInstance.getEndTime() != null ? WorkflowInstanceStatusEnums.COMPLETED : WorkflowInstanceStatusEnums.RUNNING);
//        instanceDTO.setVariables(historicProcessInstance.getProcessVariables());
//
//        // 查询活动节点历史
//        List<HistoricActivityInstance> activities = historyService.createHistoricActivityInstanceQuery()
//            .processInstanceId(processInstanceId)
//            .orderByHistoricActivityInstanceStartTime()
//            .asc()
//            .list();
//
//        List<WorkflowInstanceDTO.ActivityInstance> activityInstances = activities.stream()
//            .map(activity -> {
//                WorkflowInstanceDTO.ActivityInstance activityInstance = new WorkflowInstanceDTO.ActivityInstance();
//                activityInstance.setId(activity.getId());
//                activityInstance.setActivityId(activity.getActivityId());
//                activityInstance.setActivityName(activity.getActivityName());
//                activityInstance.setActivityType(activity.getActivityType());
//                activityInstance.setStartTime(activity.getStartTime());
//                activityInstance.setEndTime(activity.getEndTime());
//                activityInstance.setDurationInMillis(activity.getDurationInMillis());
//
//                // 如果是Shell任务，获取Shell相关变量
//                if ("serviceTask".equals(activity.getActivityType())) {
//                    Map<String, Object> variables = historicProcessInstance.getProcessVariables();
//                    activityInstance.setShellOutput((String) variables.get("shellOutput"));
//                    activityInstance.setShellError((String) variables.get("shellError"));
//                    activityInstance.setShellExitCode((Integer) variables.get("shellExitCode"));
//                }
//
//                return activityInstance;
//            })
//            .collect(Collectors.toList());
//
//        instanceDTO.setActivities(activityInstances);
//
//        return Response.success(instanceDTO);'
        return Response.success();
    }

    @Operation(summary = "获取工作流执行状态")
    @GetMapping("/instance/{processInstanceId}/execution")
    public ResponseEntity<WorkflowExecutionDTO> getWorkflowExecution(@PathVariable String processInstanceId) {
        return ResponseEntity.ok(workflowDefinitionService.getWorkflowExecution(processInstanceId));
    }

    @Operation(summary = "查询工作流实例列表")
    @GetMapping("/instances")
    public Response<List<WorkflowInstanceDTO>> listWorkflowInstances(
        @Parameter(description = "流程标识") @RequestParam(required = false) String processKey,
        @Parameter(description = "业务标识") @RequestParam(required = false) String businessKey
    ) {
        List<HistoricProcessInstance> historicProcessInstances = historyService.createHistoricProcessInstanceQuery()
            .processDefinitionKey(processKey)
            .processInstanceBusinessKey(businessKey)
            .includeProcessVariables()
            .orderByProcessInstanceStartTime()
            .desc()
            .list();

//        List<WorkflowInstanceDTO> instanceDTOs = historicProcessInstances.stream()
//            .map(historicProcessInstance -> {
//                WorkflowInstanceDTO instanceDTO = new WorkflowInstanceDTO();
////                instanceDTO.setId(historicProcessInstance.getId());
//                instanceDTO.setProcessDefinitionId(historicProcessInstance.getProcessDefinitionId());
//                instanceDTO.setBusinessKey(historicProcessInstance.getBusinessKey());
//                instanceDTO.setStartTime(historicProcessInstance.getStartTime());
//                instanceDTO.setEndTime(historicProcessInstance.getEndTime());
//                instanceDTO.setDurationInMillis(historicProcessInstance.getDurationInMillis());
//                instanceDTO.setStartUserId(historicProcessInstance.getStartUserId());
//                instanceDTO.setStatus(historicProcessInstance.getEndTime() != null ? WorkflowInstanceStatusEnums.COMPLETED : WorkflowInstanceStatusEnums.RUNNING);
//                instanceDTO.setVariables(historicProcessInstance.getProcessVariables());
//                return instanceDTO;
//            })
//            .collect(Collectors.toList());

//        return Response.success(instanceDTOs);
        return Response.success();
    }

    @Operation(summary = "获取节点实时日志")
    @GetMapping("/instance/{processInstanceId}/node/{nodeId}/logs")
    public Response<Map<String, Object>> getNodeLogs(
        @Parameter(description = "流程实例ID", required = true) @PathVariable String processInstanceId,
        @Parameter(description = "节点ID", required = true) @PathVariable String nodeId
    ) {
        Map<String, Object> result = new HashMap<>();

        // 获取历史活动实例
        HistoricActivityInstance activity = historyService.createHistoricActivityInstanceQuery()
            .processInstanceId(processInstanceId)
            .activityId(nodeId)
            .singleResult();

        if (activity == null) {
            return Response.error(ResponseCode.WORKFLOW_NODE_NOT_FOUND);
        }

        // 获取执行ID
        String executionId = activity.getExecutionId();

        // 获取节点相关的变量
        List<HistoricVariableInstance> variables = historyService.createHistoricVariableInstanceQuery()
            .processInstanceId(processInstanceId)
            .list();

        // 收集日志信息
        variables.forEach(variable -> {
            String variableName = variable.getVariableName();
            if (variableName.startsWith(executionId)) {
                // 移除executionId前缀
                String key = variableName.substring(executionId.length() + 1); // +1 for the underscore
                result.put(key, variable.getValue());
            }
        });

        // 添加节点基本信息
        result.put("nodeId", nodeId);
        result.put("nodeName", activity.getActivityName());
        result.put("nodeType", activity.getActivityType());
        result.put("startTime", activity.getStartTime());
        result.put("endTime", activity.getEndTime());
        result.put("status", activity.getEndTime() == null ? "RUNNING" : "COMPLETED");

        return Response.success(result);
    }


    @Operation(summary = "禁用工作流")
    @PostMapping("/{id}/disable")
    public Response<Void> disable(
        @Parameter(description = "工作流定义ID", required = true) @PathVariable Long id
    ) {
        workflowDefinitionService.disable(id);
        return Response.success();
    }

    @Operation(summary = "启用工作流")
    @PostMapping("/{id}/enable")
    public Response<Void> enable(
        @Parameter(description = "工作流定义ID", required = true) @PathVariable Long id
    ) {
        workflowDefinitionService.enable(id);
        return Response.success();
    }


    @Operation(summary = "启用工作流")
    @GetMapping("/categories")
    public Response<List<WorkflowCategoryDTO>> getWorkflowCategories() {
        return Response.success(workflowDefinitionService.getWorkflowCategories());
    }


    @Override
    protected void exportData(HttpServletResponse response, List<WorkflowDefinitionDTO> data) {

    }
}
