package com.ruoyi.common.type;

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

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.core.type.TypeReference;


@SuppressWarnings("rawtypes")
@MappedTypes(Map.class)
public class MapTypeHandler extends BaseTypeHandler<Map>{


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

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

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

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

	private Map get(String str) throws SQLException{
		try {
			if(str==null){
				return null;
			}
			return JsonUtils.getObjectMapper().readValue(str, new TypeReference<Map<String,Object>>() {});
		} catch (Exception e) {
			throw new SQLException("类型转换错误:map for "+str, e);
		}
	}





}
