package com.ruoyi.ibs.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.stereotype.Component;

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

/**
 * @Author 吴凯程
 * @Date 2025/6/20
 **/

@Component
public class StringListTypeHandler extends BaseTypeHandler<List<String>> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int parameterIndex, List<String> parameter, JdbcType jdbcType)
            throws SQLException {
        preparedStatement.setString(parameterIndex, String.join(",", parameter));
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        String result = resultSet.getString(columnName);
        return parseToList(result);
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String result = resultSet.getString(columnIndex);
        return parseToList(result);
    }

    @Override
    public List<String> getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String result = callableStatement.getString(columnIndex);
        return parseToList(result);
    }

    private List<String> parseToList(String result) {
        if (result == null || result.isEmpty()) {
            return new ArrayList<>();
        }
        return Arrays.asList(result.split(","));
    }

}
