package com.vctgo.system.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.vctgo.system.api.domain.dto.VoteExpertWorkingPlatformDto;
import com.vctgo.system.api.domain.dto.VoteSubmissionItemVo;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class DataEncoder {

    private final ObjectMapper objectMapper = new ObjectMapper();

    public DataEncoder() {
        configureEncoder();
    }

    public void configureEncoder() {
        SimpleModule module = new SimpleModule();
        module.addSerializer(VoteExpertWorkingPlatformDto.class, new VoteExpertWorkingPlatformDtoSerializer());
        objectMapper.registerModule(module);
    }

    public String encode(VoteExpertWorkingPlatformDto dto) throws JsonProcessingException {
        return objectMapper.writeValueAsString(dto);
    }

    static class VoteExpertWorkingPlatformDtoSerializer extends StdSerializer<VoteExpertWorkingPlatformDto> {
        protected VoteExpertWorkingPlatformDtoSerializer() {
            super(VoteExpertWorkingPlatformDto.class);
        }

        @Override
        public void serialize(VoteExpertWorkingPlatformDto value, com.fasterxml.jackson.core.JsonGenerator gen, com.fasterxml.jackson.databind.SerializerProvider provider) throws IOException {
            gen.writeStartObject();
            gen.writeStringField("judgesId", value.getJudgesId());
            gen.writeStringField("eventId", String.valueOf(value.getEventId()));
            gen.writeStringField("workSettingsId", String.valueOf(value.getWorkSettingsId()));
            gen.writeStringField("roundId", String.valueOf(value.getRoundId()));
            gen.writeStringField("submissionId", String.valueOf(value.getSubmissionId()));
            gen.writeStringField("status", value.getStatus());
            // 序列化 itemList 为 JSON 数组
            gen.writeFieldName("itemList");
            gen.writeStartArray();
            for (VoteSubmissionItemVo item : value.getItemList()) {
                gen.writeStartObject();
                gen.writeStringField("submissionId", String.valueOf(item.getSubmissionId()));
                gen.writeNumberField("itemId", item.getItemId());
                gen.writeNumberField("score", item.getScore());
                gen.writeEndObject();
            }
            gen.writeEndArray();
            gen.writeEndObject();
        }
    }
}
