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

import cn.axzo.workflow.common.model.request.form.definition.FormFieldDTO;
import org.flowable.form.model.FormContainer;
import org.flowable.form.model.FormField;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

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

import static org.mapstruct.NullValueCheckStrategy.ALWAYS;

/**
 * Converter
 *
 * @author wangli
 * @since 2024-11-11 11:27
 */
@Mapper(
        componentModel = "spring",
        nullValueCheckStrategy = ALWAYS,
        imports = {Arrays.class, ConversionUtils.class}
)
public interface FormFieldConverter extends EntityConverter<FormFieldDTO, FormField> {


    @Mapping(target = "id", source = "entity.id")
    @Mapping(target = "name", source = "entity.name")
    @Mapping(target = "type", source = "entity.type")
    @Mapping(target = "value", expression = "java(ConversionUtils.convertObject(entity.getValue()))")
    @Mapping(target = "placeholder", source = "entity.placeholder")
    @Mapping(target = "params", source = "entity.params")
    FormFieldDTO toVo(FormField entity);

    @Mapping(target = "fieldType", expression = "java(entity.getClass().getSimpleName())")
    @Mapping(target = "id", source = "entity.id")
    @Mapping(target = "name", source = "entity.name")
    @Mapping(target = "type", source = "entity.type")
    @Mapping(target = "value", expression = "java(ConversionUtils.convertObject(entity.getValue()))")
    @Mapping(target = "placeholder", source = "entity.placeholder")
    @Mapping(target = "params", source = "entity.params")
    @Mapping(target = "fields", source = "entity.fields")
    FormFieldDTO toVo(FormContainer entity);

    @Override
    default List<FormFieldDTO> toVos(List<FormField> entities) {
        List<FormFieldDTO> dtos = new ArrayList<>();
        for (FormField entity : entities) {
            if(entity instanceof FormContainer) {
                dtos.add(toVo((FormContainer) entity));
            } else{
                dtos.add(toVo((FormField) entity));
            }
        }
        return dtos;
    }
}
