package cn.axzo.workflow.server.controller.listener.activity;

import cn.axzo.workflow.common.enums.FileTypeEnum;
import cn.axzo.workflow.common.exception.WorkflowEngineException;
import cn.axzo.workflow.common.model.dto.VariableObjectDTO;
import cn.axzo.workflow.common.model.request.bpmn.BpmnSignConf;
import cn.axzo.workflow.core.common.context.ActivityOperationContext;
import cn.axzo.workflow.core.common.utils.BpmnMetaParserHelper;
import cn.axzo.workflow.core.listener.AbstractBpmnEventListener;
import cn.axzo.workflow.core.listener.BpmnActivityEventListener;
import cn.axzo.workflow.core.repository.entity.ExtAxProcessSign;
import cn.axzo.workflow.core.service.ExtAxProcessSignService;
import cn.axzo.workflow.server.common.util.WpsUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.Process;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.impl.util.ProcessDefinitionUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static cn.axzo.workflow.common.code.BpmnInstanceRespCode.PROCESS_SIGN_DATA_NOT_EXISTS;

/**
 * 每个审批节点运行结束后，临时替换一次变量，并更新至 ext_ax_process_sign 中 file_archive 字段
 *
 * @author wangli
 * @since 2025-04-03 11:05
 */
@Slf4j
@Component
@Scope("prototype")
public class OperationFileArchiveActivityEvent_101_Listener extends AbstractBpmnEventListener<ActivityOperationContext> implements BpmnActivityEventListener, Ordered {
    @Resource
    private ExtAxProcessSignService extAxProcessSignService;
    @Resource
    private WpsUtil wpsUtil;

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE + 101;
    }

    @Override
    public void onEnd(DelegateExecution execution) {
        Process process = ProcessDefinitionUtil.getProcess(execution.getProcessDefinitionId());
        Optional<BpmnSignConf> signConfig = BpmnMetaParserHelper.getSignConfig(process);
        if (!signConfig.isPresent() || Objects.isNull(signConfig.get().getSignType())) {
            return;
        }
        ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration();
        ExtAxProcessSign processSign = extAxProcessSignService.findByProcessInstanceId(execution.getProcessInstanceId());
        if (Objects.isNull(processSign)) {
            throw new WorkflowEngineException(PROCESS_SIGN_DATA_NOT_EXISTS);
        }
        List<VariableObjectDTO> wpsReplaceVariables = wpsUtil.getWpsReplaceVariables(processEngineConfiguration, execution.getProcessInstanceId());
        processSign.getFileArchive().stream().filter(i -> Objects.equals(i.getFileType(), FileTypeEnum.WORD)
                        || Objects.equals(i.getFileType(), FileTypeEnum.EXCEL))
                .forEach(docBaseVO -> {
                    String newFileKey = wpsUtil.wpsFileVariableReplace(wpsReplaceVariables, null, docBaseVO.getFileKey(), docBaseVO.getTemplateName() + docBaseVO.getFileType().getSuffix());
                    docBaseVO.setFileKey(newFileKey);
                });
        extAxProcessSignService.updateById(processSign);
    }
}
