package com.ruoyi.common.type;

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

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;


@MappedTypes(List.class)
public class ListTypeHandler extends BaseTypeHandler<List<String>>{


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

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

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

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

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





}
