package rd.dao.type;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Slf4j
//@MappedTypes(List<Double>.class)
@MappedJdbcTypes(JdbcType.ARRAY)
public class DoubleListTypeHandler extends BaseTypeHandler<List<Double>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Double> parameter, JdbcType jdbcType) throws SQLException {
        String typeName = "Double";

        Connection conn = ps.getConnection();
        Array array = conn.createArrayOf(typeName, parameter.toArray());
        ps.setArray(i, array);
    }
    
    @Override
    public List<Double> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return getArray(rs.getArray(columnName));
    }

    @Override
    public List<Double> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getArray(rs.getArray(columnIndex));
    }

    @Override
    public List<Double> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getArray(cs.getArray(columnIndex));
    }

    private List<Double> getArray(Array array) {
        if (array == null) {
            return null;
        }
        try {
            var arr = array.getArray();
            var result = new ArrayList<Double>();

            if (arr instanceof Double[] doubleArr) {
                Collections.addAll(result, doubleArr);
            } else if (arr instanceof Float[] floatArr) {
                for (Float floatVal : floatArr) {
                    result.add(floatVal.doubleValue());
                }
            }  else if (arr instanceof Integer[] intArr) {
                for (Integer intVal : intArr) {
                    result.add(intVal.doubleValue());
                }
            } else if (arr instanceof Short[] shortArr) {
                for (Short shortVal : shortArr) {
                    result.add(shortVal.doubleValue());
                }
            } else if (arr instanceof Long[] longArr) {
                for (Long longVal : longArr) {
                    result.add(longVal.doubleValue());
                }
            }

            return result;
        } catch (Exception e) {
            log.error("类型转换出错：", e);
        }

        return null;
    }
}
