package com.fs.app.config;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.context.annotation.Configuration;

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

@Configuration
public class ArrayStringTypeHandler extends BaseTypeHandler<List<String>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        // 将 List<String> 转换为字符串，ClickHouse 支持的格式为 "['item1', 'item2']"
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int j = 0; j < parameter.size(); j++) {
            sb.append("'").append(parameter.get(j)).append("'");
            if (j < parameter.size() - 1) {
                sb.append(",");
            }
        }
        sb.append("]");
        ps.setString(i, sb.toString());
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // 处理查询结果，将其转换为 List<String>
        String result = rs.getString(columnName);
        return parseArray(result);
    }

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

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

    private List<String> parseArray(String arrayStr) {
        // 将 ClickHouse 的 Array 字符串转换为 List<String>
        if (arrayStr == null || arrayStr.isEmpty()) {
            return null;
        }
        arrayStr = arrayStr.substring(1, arrayStr.length() - 1);  // 去掉 "[" 和 "]"
        String[] elements = arrayStr.split(",");
        return java.util.Arrays.asList(elements);
    }
}
