package jnpf.model.personnels.dto.analysis;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.ReUtil;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;

import java.lang.reflect.Type;
import java.text.ParseException;

@SuppressWarnings("unchecked")
public class PersonnlesAnalysisDeserializer implements ObjectDeserializer {
    // yyyy-MM-dd
    private static final String FIRST = "^\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$";
    // yyyy-MM
    private static final String SECOND = "^\\d{4}-(0[1-9]|1[0-2])$";

    @Override
    public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        String dateStr = parser.parseObject(String.class);
        if (dateStr == null || dateStr.isEmpty()) {
            return null;
        }
        try {
            if (ReUtil.isMatch(SECOND, dateStr)) {
                return (T) DatePattern.NORM_MONTH_FORMAT.parse(dateStr);
            } else if (ReUtil.isMatch(FIRST, dateStr)) {
                return (T) DatePattern.NORM_DATE_FORMAT.parse(dateStr);
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @Override
    public int getFastMatchToken() {
        return 0;
    }
}
