package org.xyzh.common.utils.config;

import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;

/**
 * @description FastJson配置类 - 统一处理日期时间格式序列化
 * @filename FastJsonConfig.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-11-28
 */
@Configuration
@ConditionalOnClass(WebMvcConfigurer.class)
public class FastJsonConfiguration implements WebMvcConfigurer {

    /**
     * 配置FastJson消息转换器
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        
        // FastJson配置
        FastJsonConfig config = new FastJsonConfig();
        
        // 设置日期格式
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        
        // 设置字符集
        converter.setDefaultCharset(StandardCharsets.UTF_8);
        
        // 设置支持的MediaType
        converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
        
        // 应用配置
        converter.setFastJsonConfig(config);
        
        // 添加到转换器列表（添加到最前面，优先使用）
        converters.add(0, converter);
    }
}
