package cn.com.ty.lift.business.framework.conf;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdScalarSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;

import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.Objects;

/**
 * BigDecimal序列化: 默认四舍五入保留两位小数
 *
 * @author wcz
 * @since 2020/4/26
 */
public class BigDecimalSerializer extends StdScalarSerializer<BigDecimal> implements ContextualSerializer {

    public static final BigDecimalSerializer instance = new BigDecimalSerializer();

    public BigDecimalSerializer() {
        super(BigDecimal.class);
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider provider,
                                              BeanProperty property) throws JsonMappingException {
        JsonFormat.Value format = findFormatOverrides(provider, property, handledType());
        if (format != null) {
            switch (format.getShape()) {
                case STRING:
                    return ToStringSerializer.instance;
                default:
            }
        }
        return this;
    }

    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if(Objects.nonNull(value)){
            gen.writeNumber(value.setScale(2, BigDecimal.ROUND_HALF_UP));
        } else {
            gen.writeNumber(value);
        }
    }

    @Override
    public JsonNode getSchema(SerializerProvider provider, Type typeHint) {
        return createSchemaNode("number", true);
    }

    @Override
    public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException {
        visitFloatFormat(visitor, typeHint, JsonParser.NumberType.BIG_DECIMAL);
    }
}
