package org.springblade.thirdparty.mk.support;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.thirdparty.mk.pojo.dto.approval.MKConditionDTO;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @author bfhuange
 * @since 2025/5/21
 */
public class MultiKeySerializer extends JsonSerializer<List<MKConditionDTO>> {
    @Override
    public void serialize(List<MKConditionDTO> values, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        values = values.stream()
                .filter(Objects::nonNull)
                .toList();
        if (CollectionUtil.isNotEmpty(values)) {
            // 获取当前字段名
            String fieldName = gen.getOutputContext().getCurrentName();
            boolean writeValue = false;
            for (MKConditionDTO value : values) {
                if (writeValue) {
                    // 写过值了，要再添加一个字段名
                    gen.writeFieldName(fieldName);
                }
                gen.writeObject(value);
                writeValue = true;
            }
        }
    }
}
