package digital.laboratory.platform.entrustment.config;

import com.alibaba.fastjson.JSON;
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.List;

public abstract class BaseMybatisList2JsonHandler<T> extends BaseTypeHandler<List<T>> {

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

	@Override
	public List<T> getNullableResult(ResultSet rs, String columnName)
			throws SQLException {
		String data = rs.getString(columnName);
		List<T> r = StringUtils.isBlank(data) ? null : JSON.parseArray(data, (Class<T>) getRawType());
		return r;
	}

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

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

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

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

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