package com.storlead.system.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

/**
 * LocalDateTime LocalDate LocalTime 日期自动转换器 pojo jackson 序列化/反序列化
 *
 * @author blank
 * @since 2020-03-17 下午 12:20
 **/
@Configuration
public class JacksonConfig {

    /**
     * 默认日期时间格式
     */
//    public static final String DEFAULT_DATE_TIME_FORMAT = DatePattern.NORM_DATETIME_PATTERN;
    /**
     * 默认日期格式
     */
//    public static final String DEFAULT_DATE_FORMAT = DatePattern.NORM_DATE_PATTERN;
    /**
     * 默认时间格式
     */
//    public static final String DEFAULT_TIME_FORMAT = DatePattern.NORM_TIME_PATTERN;

    /**
     * LocalDate转换器，用于转换RequestParam和PathVariable参数
     * spring Lambda Converter not support @link {https://github.com/spring-projects/spring-framework/issues/22509}
     */
//    @Bean
//    public Converter<String, LocalDate> localDateConverter() {
//        return new Converter<String, LocalDate>() {
//            @Override
//            public LocalDate convert(@NotNull String source) {
//                return LocalDate.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT));
//            }
//        };
//    }

    /**
     * LocalDateTime转换器，用于转换RequestParam和PathVariable参数
     */
//    @Bean
//    public Converter<String, LocalDateTime> localDateTimeConverter() {
//        return new Converter<String, LocalDateTime>() {
//            @Override
//            public LocalDateTime convert(@NotNull String source) {
//                return LocalDateTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT));
//            }
//        };
//    }

    /**
     * LocalTime转换器，用于转换RequestParam和PathVariable参数
     */
//    @Bean
//    public Converter<String, LocalTime> localTimeConverter() {
//        return new Converter<String, LocalTime>() {
//            @Override
//            public LocalTime convert(@NotNull String source) {
//                return LocalTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT));
//            }
//        };
//    }

    /**
     * Date转换器，用于转换RequestParam和PathVariable参数
     */
//    @Bean
//    public Converter<String, Date> dateConverter() {
//        return new Converter<String, Date>() {
//            @Override
//            public Date convert(@NotNull String source) {
//                SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
//                try {
//                    return format.parse(source);
//                } catch (ParseException e) {
//                    throw new RuntimeException(e);
//                }
//            }
//        };
//    }

    /**
     * Json序列化和反序列化转换器，用于转换Post请求体中的json以及将我们的对象序列化为返回响应的json
     */
    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 指定要序列化的域，field,get和set,以及修饰符范围，ANY是都有包括private和public
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型，类必须是非final修饰的，final修饰的类，比如String,Integer等会跑出异常
        //必须配置否则将无法反序列化 see https://github.com/FasterXML/jackson-databind/issues/2838
        //目前不兼容Swagger3
        //objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);

//        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//        objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
//        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
//        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        //将枚举类型转换为字符串
        objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);

        // 解决enum不匹配问题 默认值为null
        objectMapper.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL);

        //时区东8区
        objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        //默认日期格式
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

        //LocalDateTime系列序列化和反序列化模块，继承自jsr310，我们在这里修改了日期格式
//        JavaTimeModule javaTimeModule = new JavaTimeModule();
//        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
//        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
//        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
//        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
//        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
//        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));

        /**
         * 序列换成json时,将所有的long变成string
         * 因为js中得数字类型范围不能包含所有的java long值
         */
        SimpleModule longTypeModule = new SimpleModule();
        longTypeModule.addSerializer(Long.class, ToStringSerializer.instance);
        longTypeModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(longTypeModule);

        //日期处理
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.registerModule(new JavaTimeModule());

        //忽略未知字段
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        //Date序列化和反序列化
//        javaTimeModule.addSerializer(Date.class, new JsonSerializer<>() {
//            @Override
//            public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
//                SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
//                String formattedDate = formatter.format(date);
//                jsonGenerator.writeString(formattedDate);
//            }
//        });
//        javaTimeModule.addDeserializer(Date.class, new JsonDeserializer<>() {
//            @Override
//            public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
//                SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
//                String date = jsonParser.getText();
//                try {
//                    return format.parse(date);
//                } catch (ParseException e) {
//                    throw new RuntimeException(e);
//                }
//            }
//        });

//        objectMapper.registerModule(javaTimeModule);
        return objectMapper;
    }

}
