package com.ruoyi.common.handler;


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;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;


@MappedJdbcTypes(value = { JdbcType.VARCHAR })

public class ListTypeHandler extends BaseTypeHandler<List<Double>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Double> parameter, JdbcType jdbcType)
            throws SQLException {
        String d = parameter.stream().map(v -> String.valueOf(v)).collect(Collectors.joining(","));
        ps.setString(i, d);
    }

    @Override
    public List<Double> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String values = rs.getString(columnName);
        return getResults(values);
    }

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

    @Override
    public List<Double> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String values = cs.getString(columnIndex);
        return getResults(values);
    }

    private List<Double> getResults(String values) {
        if (StringUtils.isNotBlank(values)) {
            String[] data = values.split(",");
            return Arrays.stream(data).mapToDouble(v -> Double.parseDouble(v)).boxed().collect(Collectors.toList());
        }
        return new ArrayList<>();
    }
}
