package com.ruoyi.mingxue.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.core.domain.entity.MenuExtInfo;
import com.ruoyi.common.utils.StringUtils;
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(MenuExtInfo.ConfigExtends.class)
public class MxjbTagExtInfoHandler implements TypeHandler<MenuExtInfo.ConfigExtends> {
    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, MenuExtInfo.ConfigExtends extInfo, JdbcType jdbcType) throws SQLException {
        try {
            preparedStatement.setString(i, null == extInfo ? null : om.writeValueAsString(extInfo));
        } catch (JsonProcessingException e) {
            preparedStatement.setString(i, null);
        }
    }

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

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

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

    private MenuExtInfo.ConfigExtends toObject(String s) {
        try {
            return StringUtils.isNotBlank(s) ? om.readValue(s, MenuExtInfo.ConfigExtends.class) : null;
        } catch (JsonProcessingException e) {
            return null;
        }
    }
}
