package digital.laboratory.platform.entrustment.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

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

public abstract class BaseMybatisMap2JsonHandler<T> extends BaseTypeHandler<HashMap<String, T>> {

	protected abstract TypeReference getType();
//	typeReference =  new InstructionBoHashMap();

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, HashMap<String, T> parameter, JdbcType jdbcType) throws SQLException {
		ps.setString(i, JSON.toJSONString(parameter));
	}

	@Override
	public HashMap<String, T> getNullableResult(ResultSet rs, String columnName)
			throws SQLException {
		String data = rs.getString(columnName);

		return StringUtils.isBlank(data) ? null : (HashMap<String, T>)JSON.parseObject(data, getType());
	}

	@Override
	public HashMap<String, T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		String data = rs.getString(columnIndex);
		return StringUtils.isBlank(data) ? null : (HashMap<String, T>)JSON.parseObject(data, getType());
	}

	@Override
	public HashMap<String, T> getNullableResult(CallableStatement cs, int columnIndex)
			throws SQLException {
		String data = cs.getString(columnIndex);
		return StringUtils.isBlank(data) ? null : (HashMap<String, T>)JSON.parseObject(data, getType());
	}

	@Override
	public HashMap<String, T> getResult(ResultSet rs, String columnName) throws SQLException {
		return super.getResult(rs, columnName);
	}

	@Override
	public HashMap<String, T> getResult(ResultSet rs, int columnIndex) throws SQLException {
		return super.getResult(rs, columnIndex);
	}

	@Override
	public HashMap<String, T> getResult(CallableStatement cs, int columnIndex) throws SQLException {
		return super.getResult(cs, columnIndex);
	}
}
