package cn.axzo.workflow.core.service.converter;

import cn.axzo.workflow.common.model.response.bpmn.model.BpmnModelDetailVO;
import com.alibaba.fastjson.JSON;
import org.flowable.engine.impl.persistence.entity.ModelEntityImpl;
import org.flowable.engine.repository.Model;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

import java.util.Arrays;
import java.util.Map;

import static cn.axzo.workflow.common.constant.MetaInfoConstants.MODEL_DESCRIPTION;
import static org.mapstruct.NullValueCheckStrategy.ALWAYS;

/**
 * 流程模型的 MapStruts 转换器
 */
@Mapper(
        componentModel = "spring",
        nullValueCheckStrategy = ALWAYS,
        imports = Arrays.class
)
public interface BpmnModelConverter extends EntityConverter<BpmnModelDetailVO, Model> {

    @Override
    @Mapping(target = "id", source = "id")
    @Mapping(target = "key", source = "key")
    @Mapping(target = "name", source = "name")
    @Mapping(target = "category", source = "category")
    @Mapping(target = "createAt", source = "createTime")
    @Mapping(target = "updateAt", source = "lastUpdateTime")
    @Mapping(target = "version", source = "version")
    @Mapping(target = "deploymentId", source = "deploymentId")
    @Mapping(target = "editorSourceId", expression = "java(getEditorSourceValueId(entity))")
    @Mapping(target = "metaInfo", source = "metaInfo")
    @Mapping(target = "tenantId", source = "tenantId")
    BpmnModelDetailVO toVo(Model entity);

    default BpmnModelDetailVO toVoParseDesc(Model entity) {
        BpmnModelDetailVO vo = toVo(entity);
        Map<String, String> metaInfoMap = JSON.parseObject(vo.getMetaInfo(), Map.class);
        vo.setDescription(metaInfoMap.get(MODEL_DESCRIPTION));
        return vo;
    }

    default String getEditorSourceValueId(Model entity) {
        if (entity == null) {
            return null;
        }
        return ((ModelEntityImpl) entity).getEditorSourceValueId();
    }
}
