package com.ruoyi.mxjb.handlers;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mxjb.domain.MultipleWayData;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedJdbcTypes(value = {JdbcType.VARCHAR, JdbcType.NULL})
@MappedTypes(MultipleWayData.class)
public class MultipleWayDataHandler implements TypeHandler<MultipleWayData> {
    private static ObjectMapper om = new ObjectMapper();
    static {
        om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, MultipleWayData data, JdbcType jdbcType) throws SQLException {
        try {
            preparedStatement.setString(i, null == data ? null : om.writeValueAsString(data));
        } catch (JsonProcessingException e) {
            preparedStatement.setString(i, null);
        }
    }

    @Override
    public MultipleWayData getResult(ResultSet resultSet, String s) throws SQLException {
        return toObject(resultSet.getString(s));
    }

    @Override
    public MultipleWayData getResult(ResultSet resultSet, int i) throws SQLException {
        return toObject(resultSet.getString(i));
    }

    @Override
    public MultipleWayData getResult(CallableStatement callableStatement, int i) throws SQLException {
        return toObject(callableStatement.getString(i));
    }

    private MultipleWayData toObject(String s) {
        if(StringUtils.isNotBlank(s) ) {
            try {
                MultipleWayData data = om.readValue(s, MultipleWayData.class);
                return data;
            } catch (JsonProcessingException e) {

            }
        }
        return new MultipleWayData();
    }
}
