package cn.axzo.workflow.core.engine.cmd;

import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.form.api.FormEngineConfigurationApi;
import org.flowable.form.api.FormInstance;
import org.flowable.form.api.FormService;
import org.springframework.util.StringUtils;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;

/**
 * 算 cn.axzo.workflow.core.engine.cmd.CustomGetFormInstanceLatestValuesCmd 的另一种实现吧
 *
 * @author wangli
 * @since 2025-07-29 15:19
 */
public class CustomGetFormDataValuesCmd implements Command<byte[]> {
    private final String processInstanceId;
    private final String taskId;

    public CustomGetFormDataValuesCmd(String processInstanceId, String taskId) {
        this.processInstanceId = processInstanceId;
        this.taskId = taskId;
    }

    @Override
    public byte[] execute(CommandContext commandContext) {
        FormEngineConfigurationApi formEngineConfiguration = CommandContextUtil.getFormEngineConfiguration(commandContext);

        FormService formService = formEngineConfiguration.getFormService();
        List<FormInstance> list = formService.createFormInstanceQuery().processInstanceId(processInstanceId).list();
        FormInstance formInstance = list.stream().max(Comparator.comparing(FormInstance::getSubmittedDate)).orElse(null);
        if (StringUtils.hasText(taskId)) {
            formInstance = list.stream().filter(i -> Objects.equals(i.getTaskId(), taskId)).findFirst()
                    .orElse(formInstance);
        }
        return formInstance.getFormValueBytes();
    }
}
