package com.yeejoin.amos.boot.module.jg.api.common;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
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.*;

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

    private List<String> customFields = Arrays.asList("createDate", "acceptDate", "expiryDate", "applicationDate", "noticeDate", "installStartDate", "handleDate", "auditPassDate", "applyDate");

    public BizCustomDateSerializer() {
    }

    @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);
        String formattedDate = formatter.format(value);
        return formattedDate;
    }

}