package digital.laboratory.platform.entrustment.config;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

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

@Slf4j
@MappedTypes({List.class})      // 指定与其关联的 Java 类型列表。 如果在 javaType 属性中也同时指定，则注解上的配置将被忽略。
@MappedJdbcTypes(JdbcType.VARCHAR)
// public class StringListJsonHandler extends BaseMybatisList2JsonHandler<String> {
// }
public class StringListJsonHandler extends BaseTypeHandler<List<String>> {

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

	@Override
	public List<String> getNullableResult(ResultSet rs, String columnName)
			throws SQLException {
		String data = rs.getString(columnName);
		//List<String> r = StringUtils.isBlank(data) ? null : JSON.parseArray(data, (Class<String>) getRawType());
		List<String> r = StringUtils.isBlank(data) ? null : JSON.parseArray(data, String.class);
		System.out.println(String.format("StringListJsonHandler.getNullableResult, columnName=%s data=%s r=%s", columnName, data, r));
		return r;
	}

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

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

	@Override
	public List<String> getResult(ResultSet rs, String columnName) throws SQLException {
		List<String> r = super.getResult(rs, columnName);
		System.out.println(String.format("StringListJsonHandler.getResult, columnName=%s r=%s", columnName, r));
		return r;
	}

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

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


