package com.qqchen.deploy.backend.workflow.service.impl;

import com.qqchen.deploy.backend.framework.service.impl.BaseServiceImpl;
import com.qqchen.deploy.backend.workflow.converter.WorkflowNodeInstanceConverter;
import com.qqchen.deploy.backend.workflow.dto.WorkflowNodeInstanceDTO;
import com.qqchen.deploy.backend.workflow.dto.query.WorkflowNodeInstanceQuery;
import com.qqchen.deploy.backend.workflow.entity.WorkflowInstance;
import com.qqchen.deploy.backend.workflow.entity.WorkflowNodeInstance;
import com.qqchen.deploy.backend.workflow.enums.WorkflowNodeInstanceStatusEnums;
import com.qqchen.deploy.backend.workflow.dto.event.WorkflowNodeInstanceStatusChangeEvent;
import com.qqchen.deploy.backend.workflow.repository.IWorkflowInstanceRepository;
import com.qqchen.deploy.backend.workflow.repository.IWorkflowNodeInstanceRepository;
import com.qqchen.deploy.backend.workflow.service.IWorkflowNodeInstanceService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WorkflowNodeInstanceServiceImpl extends BaseServiceImpl<WorkflowNodeInstance, WorkflowNodeInstanceDTO, WorkflowNodeInstanceQuery, Long> implements IWorkflowNodeInstanceService {

    @Resource
    private IWorkflowNodeInstanceRepository workflowNodeInstanceRepository;

    @Resource
    private WorkflowNodeInstanceConverter workflowNodeInstanceConverter;

    @Resource
    private IWorkflowInstanceRepository workflowInstanceRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WorkflowNodeInstance updateNodeStatus(String processInstanceId, String executionId, WorkflowNodeInstanceStatusEnums status) {
        WorkflowNodeInstance nodeInstance = workflowNodeInstanceRepository.findByProcessInstanceIdAndExecutionId(processInstanceId, executionId)
            .orElseThrow(() -> new RuntimeException("Node instance not found for processInstanceId: " + processInstanceId + ", executionId: " + executionId));

        nodeInstance.setStatus(status);
        nodeInstance.setUpdateTime(LocalDateTime.now());

        if (status == WorkflowNodeInstanceStatusEnums.COMPLETED ||
            status == WorkflowNodeInstanceStatusEnums.TERMINATED ||
            status == WorkflowNodeInstanceStatusEnums.FAILED) {
            nodeInstance.setEndTime(LocalDateTime.now());
        }

        return workflowNodeInstanceRepository.save(nodeInstance);
    }

    @Override
    public List<WorkflowNodeInstanceDTO> getNodesByProcessInstanceId(String processInstanceId) {
        List<WorkflowNodeInstance> nodes = workflowNodeInstanceRepository.findByProcessInstanceId(processInstanceId);
        return nodes.stream()
            .map(workflowNodeInstanceConverter::toDto)
            .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void saveOrUpdateWorkflowNodeInstance(WorkflowNodeInstanceStatusChangeEvent event) {
        WorkflowNodeInstance nodeInstance = workflowNodeInstanceConverter.eventToEntity(event);
        WorkflowInstance workflowInstance = workflowInstanceRepository.findByProcessInstanceId(nodeInstance.getProcessInstanceId())
            .orElseThrow(() -> new RuntimeException("Node instance not found for processInstanceId: " + nodeInstance.getProcessInstanceId()));
        WorkflowNodeInstance workflowNodeInstance = workflowNodeInstanceRepository.findByProcessInstanceIdAndNodeId(workflowInstance.getProcessInstanceId(), event.getNodeId());
        if (workflowNodeInstance == null) {
            // 新建节点实例
            nodeInstance.setWorkflowInstanceId(workflowInstance.getId());
            nodeInstance.setWorkflowDefinitionId(workflowInstance.getWorkflowDefinitionId());
            // ✅ 保存节点执行变量
            nodeInstance.setVariables(event.getVariables());
            // ✅ 保存错误信息（如果有）
            nodeInstance.setErrorMessage(event.getErrorMessage());
            super.repository.save(nodeInstance);
            return;
        }
        // 更新节点实例
        workflowNodeInstance.setEndTime(event.getEndTime());
        workflowNodeInstance.setStatus(event.getStatus());
        // ✅ 更新节点执行变量
        workflowNodeInstance.setVariables(event.getVariables());
        // ✅ 更新错误信息（如果有）
        workflowNodeInstance.setErrorMessage(event.getErrorMessage());
        super.repository.save(workflowNodeInstance);
    }
}
