package com.ruoyi.common.handler;

import com.ruoyi.common.utils.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

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


@MappedJdbcTypes(value = {JdbcType.VARCHAR})
@MappedTypes(value = {List.class})
public class ListToVarcharTypeHandler implements TypeHandler<List<String>> {
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, List<String> longs, JdbcType jdbcType) throws SQLException {
        StringBuffer buffer = new StringBuffer();
        for (int j = 0; j < longs.size(); j++) {
            if (j == longs.size() - 1) {
                buffer.append(longs.get(j));
            } else {
                buffer.append(longs.get(j)).append(",");
            }
        }
        preparedStatement.setString(i, buffer.toString());
    }

    @Override
    public List<String> getResult(ResultSet resultSet, String s) throws SQLException {
        String longs = resultSet.getString(s);
        if (StringUtils.isNotEmpty(longs)) {
            return Arrays.asList(longs.split(","));
        }
        return null;
    }

    @Override
    public List<String> getResult(ResultSet resultSet, int i) throws SQLException {
        String longs = resultSet.getString(i);
        if (StringUtils.isNotEmpty(longs)) {
            return Arrays.asList(longs.split(","));
        }
        return null;
    }

    @Override
    public List<String> getResult(CallableStatement callableStatement, int i) throws SQLException {
        String longs = callableStatement.getString(i);
        if (StringUtils.isNotEmpty(longs)) {
            return Arrays.asList(longs.split(","));
        }
        return null;
    }
}
