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

import cn.axzo.workflow.common.model.dto.BizDocDTO;
import cn.axzo.workflow.core.repository.entity.ExtAxModelDoc;
import org.springframework.context.ApplicationEvent;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 模型关联的文档变更事件对象
 *
 * @author wangli
 * @since 2025-04-07 16:51
 */
public class DocChangeEventImpl extends ApplicationEvent implements DocChangeEvent {

    private final String key;

    private final Long workspaceId;

    private final List<BizDocDTO> newSettings;

    private final List<BizDocDTO> oldSettings;

    public DocChangeEventImpl(String key, String workspaceId, List<ExtAxModelDoc> newSettings, List<ExtAxModelDoc> oldSettings) {
        super(key);
        this.key = key;
        this.workspaceId = StringUtils.hasText(workspaceId) ? Long.valueOf(workspaceId) : null;
        this.newSettings = convert(newSettings);
        this.oldSettings = convert(oldSettings);
    }

    private List<BizDocDTO> convert(List<ExtAxModelDoc> docs) {
        if (CollectionUtils.isEmpty(docs)) {
            return Collections.emptyList();
        }
        return docs.stream().map(i -> BizDocDTO.builder()
                .archiveName(i.getTemplateName())
                .archiveCode(i.getTag())
                .enabled(i.getStatus())
                .build()).collect(Collectors.toList());
    }

    @Override
    public String getKey() {
        return key;
    }

    @Override
    public Long getWorkspaceId() {
        return workspaceId;
    }

    @Override
    public List<BizDocDTO> getNewSettings() {
        return newSettings;
    }

    @Override
    public List<BizDocDTO> getOldSettings() {
        return oldSettings;
    }

}