package com.yeejoin.amos.boot.module.statistcs.biz.config;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.apache.commons.lang3.StringUtils;
import org.typroject.tyboot.core.foundation.utils.DateTimeUtil;

import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @JsonComponent 会覆盖JsonFormat, 这里解析字段提升JsonFormat优先级
 * <p>
 * ProjectName: amos-boot-biz
 * PackageName: com.yeejoin.amos.boot.module.jg.biz.config
 *
 * @author yangyang
 * @version v1.0
 * @date 2023/12/18 17:35
 */
public class BizCustomDateSerializer extends StdSerializer<Date> {

    private List<String> customFields = Arrays.asList("acceptDate", "expiryDate","applicationDate");

    public BizCustomDateSerializer()
    {
        super(Date.class);
    }

    @Override
    public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        try {
            Class<?> clazz = jgen.getCurrentValue().getClass();
            if (Objects.equals(clazz, HashMap.class)) {
                // 分页参数
                if (customFields.contains(jgen.getOutputContext().getCurrentName())) {
                    SimpleDateFormat formatter = new SimpleDateFormat(DateTimeUtil.ISO_DATE);
                    jgen.writeString(formatter.format(value));
                    return;
                }
            } else {
                Field field = clazz.getDeclaredField(jgen.getOutputContext().getCurrentName());
                if (Objects.equals(field.getType(), Date.class)) {
                    if (field.isAnnotationPresent(JsonFormat.class)) {
                        String pattern = field.getAnnotation(JsonFormat.class).pattern();
                        if (StringUtils.isNotBlank(pattern)) {
                            SimpleDateFormat formatter = new SimpleDateFormat(pattern);
                            jgen.writeString(formatter.format(value));
                            return;
                        }
                    }
                }
            }
            jgen.writeString(defaultFormattedDate(value));
        } catch (Exception e) {
            jgen.writeString(defaultFormattedDate(value));
        }
    }

    private String defaultFormattedDate(Date value) {
        SimpleDateFormat formatter = new SimpleDateFormat(DateTimeUtil.ISO_DATE_HOUR24_MIN_SEC);
        return formatter.format(value);
    }

}