package com.cmvr.test.flow.runtime.operator;

import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.flow.context.TaskContext;
import com.cmvr.test.flow.context.TaskInstHolder;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * todo 执行前后都可以做一次控制状态的验证
 */
@Slf4j
public abstract class AbstractNodeOperateHandler implements NodeOperateHandler {

    @Autowired
    protected TaskInstHolder taskInstHolder;

    @Override
    public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message) {
        ActionEnum actionEnum = message.getAction();

        // 正常执行
        TaskNodeExecuteResult result = doExecute(message);
        // 检查上下文状态，处理终止/暂停
        if (!checkContext(message, actionEnum)) {
            // todo
            return null; // 若已暂停或终止，中断后续流程
        }
        // 记录节点执行成功
        after(result, actionEnum);

        return result;
    }

    /**
     * 检查上下文状态，处理暂停/终止逻辑
     */
    protected boolean checkContext(TaskNodeExecuteMessage message, ActionEnum action) {
        TaskContext ctx = taskInstHolder.getContext(message.getInstId());
        if (ctx == null) return false; // 为null说明已经注销

        if (ctx.isStopped()) {
            // TODO 调用 Edge 中止

            // 标记终止
//            taskInstHolder.markStopped(message.getInstId(), message.getTaskId(), message.getItemId());
            return false;
        }

        if (ctx.isPaused()) {
            // TODO 调用 Edge 暂停

            // 标记暂停
//            taskInstHolder.markPaused(message.getInstId(), message.getTaskId(), message.getItemId());
            return false;
        }

        return true;
    }

    protected void after(TaskNodeExecuteResult message, ActionEnum action) {

    }

    protected abstract TaskNodeExecuteResult doExecute(TaskNodeExecuteMessage message);
}
