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

import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskDelegateAssigner;
import cn.axzo.workflow.common.model.response.bpmn.process.BpmnProcessDefinitionVO;
import cn.axzo.workflow.core.repository.entity.ExtAxReProcDef;
import com.alibaba.fastjson.JSON;
import org.flowable.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.flowable.engine.repository.ProcessDefinition;
import org.mapstruct.Mapper;

import java.util.Arrays;
import java.util.List;

import static org.mapstruct.NullValueCheckStrategy.ALWAYS;

/**
 * 流程定义的 MapStruts 转换器
 *
 * @author wangli
 * @since 2023/7/25 22:44
 */
@Mapper(
        componentModel = "spring",
        nullValueCheckStrategy = ALWAYS,
        imports = Arrays.class
)
public interface BpmnProcessDefinitionConverter extends EntityConverter<BpmnProcessDefinitionVO, ProcessDefinition> {

    @Override
    default BpmnProcessDefinitionVO toVo(ProcessDefinition entity) {
        if (entity == null) {
            return null;
        }

        BpmnProcessDefinitionVO bpmnProcessDefinitionVO = new BpmnProcessDefinitionVO();

        if (entity.getId() != null) {
            bpmnProcessDefinitionVO.setId(entity.getId());
        }
        if (entity.getName() != null) {
            bpmnProcessDefinitionVO.setName(entity.getName());
        }
        if (entity.getKey() != null) {
            bpmnProcessDefinitionVO.setKey(entity.getKey());
        }
        if (entity.getDescription() != null) {
            bpmnProcessDefinitionVO.setDescription(entity.getDescription());
        }
        if (entity.getCategory() != null) {
            bpmnProcessDefinitionVO.setCategory(entity.getCategory());
        }
        if (entity.getTenantId() != null) {
            bpmnProcessDefinitionVO.setTenantId(entity.getTenantId());
        }
        bpmnProcessDefinitionVO.setVersion(entity.getVersion());
        ProcessDefinitionEntity entitySource = (ProcessDefinitionEntity) entity;
        bpmnProcessDefinitionVO.setSuspensionState(entitySource.getSuspensionState());

        return bpmnProcessDefinitionVO;
    }

    default List<BpmnProcessDefinitionVO> toVos(List<ProcessDefinition> entities,
                                                List<ExtAxReProcDef> extAxReProcDefs) {
        List<BpmnProcessDefinitionVO> vos = EntityConverter.super.toVos(entities);
        vos.forEach(vo -> extAxReProcDefs.forEach(i -> {
            if (vo.getId().equals(i.getProcDefId())) {
                vo.setOperator(JSON.parseObject(i.getOperatorMetaData(), BpmnTaskDelegateAssigner.class));
                vo.setCreateTime(i.getCreateAt());
            }
        }));
        return vos;
    }
}
