package com.ruoyi.common.type;

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

import com.ruoyi.common.utils.JsonUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import com.fasterxml.jackson.databind.JsonNode;



@MappedTypes(JsonNode.class)
public class JSONTypeHandler extends BaseTypeHandler<JsonNode>{


	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, JsonNode parameter, JdbcType jdbcType)
			throws SQLException {
		try {
			ps.setString(i, parameter.toPrettyString());
		} catch (Exception e) {
			throw new SQLException("类型转换错误:String[]",e);
		}
	}

	@Override
	public JsonNode getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return get(rs.getString(columnName));
	}

	@Override
	public JsonNode getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return get(rs.getString(columnIndex));
	}

	@Override
	public JsonNode getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return get(cs.getString(columnIndex));
	}

	private JsonNode get(String str) throws SQLException{
		try {
			if(str==null){
				return null;
			}
			return JsonUtils.getObjectMapper().readTree(str);
		} catch (Exception e) {
			throw new SQLException("类型转换错误:String[] for "+str, e);
		}
	}





}
