/*
 * Copyright (c) 2023 codvision.com All Rights Reserved.
 */

package com.codvision.webcore.config;

import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * web核心配置
 *
 * @author lingee
 * @date 2023/7/21
 */
@Configuration
@ComponentScan("com.codvision.webcore")
@PropertySource(value = {"classpath:web-core.properties", "file:web-core.properties"}, ignoreResourceNotFound = true)
public class WebCoreConfig {

    /**
     * 序列化配置
     *
     * @return jackson配置
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer customizer() {
        //final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return builder -> {
            //builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            //        .locale(Locale.CHINA)
            //        .timeZone(TimeZone.getTimeZone("GMT+8"));
            //// 序列化
            //builder.serializerByType(Date.class, new DateSerializer(false, simpleDateFormat));
            //// 反序列化
            //builder.deserializerByType(Date.class,
            //                new DateDeserializers.DateDeserializer(DateDeserializers.DateDeserializer.instance,
            //                        simpleDateFormat, "yyyy-MM-dd HH:mm:ss"));
            builder.featuresToEnable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
            // 属性为空的不序列化
            // builder.serializationInclusion(JsonInclude.Include.NON_NULL);
            //把java.util.date 序列化为long
            //builder.featuresToEnable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            builder.simpleDateFormat("yyyy-MM-dd HH:mm:ss");
        };
    }

    @Bean
    public CorsFilter corsFilter () {
        CorsConfiguration configuration = new CorsConfiguration();
        // 放行所有原始域
        configuration.addAllowedOriginPattern("*");
        // 设置跨域访问可以携带cookie
        configuration.setAllowCredentials(Boolean.TRUE);
        // 放行哪些请求方式，*代表所有
        configuration.addAllowedMethod("*");
        // 允许携带任何头信息
        configuration.addAllowedHeader("*");
        // 预检请求的有效期，单位为秒。
        configuration.setMaxAge(3600L);

        // 初始化cors配置源对象
        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        configurationSource.registerCorsConfiguration("/**", configuration);
        return new CorsFilter(configurationSource);
    }
}
