package rd.dao.type.json;

import com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.postgresql.util.PGobject;

import java.sql.PreparedStatement;
import java.sql.SQLException;

@Slf4j
public abstract class BaseJsonTypeHandler<T> extends AbstractJsonTypeHandler<T> {
    protected static final ObjectMapper objectMapper = new ObjectMapper();

    protected final JavaType javaType;
    protected final Class<T> clazz;

    protected BaseJsonTypeHandler(JavaType javaType) {
        this.javaType = javaType;
        this.clazz = null;
    }

    protected BaseJsonTypeHandler(Class<T> clazz) {
        this.javaType = null;
        this.clazz = clazz;
    }

    @Override
    protected T parse(String json) {
        try {
            if (clazz == null) {
                return objectMapper.readValue(json, javaType);
            } else {
                return objectMapper.readValue(json, clazz);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        PGobject obj = new PGobject();
        obj.setType("jsonb");
        obj.setValue(toJson(parameter));

        ps.setObject(i, obj);
    }

    @Override
    protected String toJson(T obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.warn("对象序列化异常：", e);
        }

        return null;
    }
}
