package com.ruoyi.interfaces.workflow.executor;

import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.interfaces.domain.MdModelStep;
import com.ruoyi.interfaces.domain.MdModelStepExecution;
import com.ruoyi.interfaces.service.MdModelStepExecutionService;
import com.ruoyi.interfaces.workflow.ExecutionContext;
import kotlin.collections.builders.MapBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.expression.MapAccessor;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

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

/**
 * @author LinQiLong
 * @date 2025/7/16 9:26
 */
@Slf4j
@Component
public class ConditionStepExecutor implements StepExecutor {

    @Autowired
    private MdModelStepExecutionService stepExecutionService;

    @Override
    public MdModelStep.StepType getSupportedStepType() {
        return MdModelStep.StepType.CONDITION;
    }

    @Override
    public MdModelStepExecution execute(MdModelStep step, ExecutionContext context) {
        MdModelStepExecution stepExecution = new MdModelStepExecution();
        stepExecution.setExecutionId(context.getWorkflowId());
        stepExecution.setStepId(step.getId());
        stepExecution.setStepName(step.getName());
        stepExecution.setStepType(MdModelStep.StepType.API);
        stepExecution.markStart();
        stepExecutionService.saveOrUpdate(stepExecution);

        Map<String, Object> config = (Map<String, Object>) JsonUtils.jsonToPojo(step.getConfig(), Map.class);
        String expression = config.get("expression").toString();
        boolean judge = isPremiumPackage(expression, context);
        context.setContextValue("CONDITION_RESULT", judge);

        Map<String, Object> output = new HashMap<>();
        output.put("CONDITION_RESULT", judge);

        stepExecution.markSuccess(output);
        stepExecutionService.saveOrUpdate(stepExecution);
        return stepExecution;
    }

    public boolean isPremiumPackage(String template, ExecutionContext contextData) {
        ExpressionParser parser = new SpelExpressionParser();
        StandardEvaluationContext evalContext = new StandardEvaluationContext();

        Map<String, Object> rootContext = contextData.getAllContextData();
        evalContext.setRootObject(rootContext);
        evalContext.addPropertyAccessor(new MapAccessor());

        Boolean result = parser.parseExpression(template)
                .getValue(evalContext, Boolean.class);
        return Boolean.TRUE.equals(result);
    }

}
