package com.ruoyi.system.mapper.typehandler;

import com.ruoyi.common.utils.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.util.CollectionUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * List 转 逗号分隔符
 * 2024/4/22
 */
public abstract class AbstractSplitListTypeHandler<O> extends BaseTypeHandler<List<O>> {

    public static final String DELIMITER = ",";

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<O> parameter,
                                    JdbcType jdbcType) throws SQLException {
        String data = parseToString(parameter, DELIMITER);
        ps.setString(i, data);
    }

    @Override
    public List<O> getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        String data = rs.getString(columnName);
        return StringUtils.isBlank(data) ? Collections.emptyList() : parseToList(data, DELIMITER);
    }

    @Override
    public List<O> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String data = rs.getString(columnIndex);
        return StringUtils.isBlank(data) ? Collections.emptyList() : parseToList(data, DELIMITER);
    }

    @Override
    public List<O> getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        String data = cs.getString(columnIndex);
        return StringUtils.isBlank(data) ? Collections.emptyList() : parseToList(data, DELIMITER);
    }

    /**
     * 转换为列表
     */
    public abstract List<O> parseToList(String data, String delimiter);

    /**
     * 转换为字符串
     */
    private String parseToString(List<O> parameter, String delimiter) {
        if (!CollectionUtils.isEmpty(parameter)) {
            return parameter.stream().map(Object::toString).collect(Collectors.joining(delimiter));
        }
        return "";
    }
}
