package com.yhy.module.core.dal.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;

/**
 * PostgreSQL BIGINT[] 数组类型处理器
 * 
 * 用于处理 PostgreSQL 的 BIGINT[] 类型与 Java Long[] 类型的转换
 */
@MappedTypes(Long[].class)
@MappedJdbcTypes(JdbcType.ARRAY)
public class PostgreSQLBigintArrayTypeHandler extends BaseTypeHandler<Long[]> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Long[] parameter, JdbcType jdbcType) throws SQLException {
        Connection conn = ps.getConnection();
        Array array = conn.createArrayOf("bigint", parameter);
        ps.setArray(i, array);
    }

    @Override
    public Long[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return getArray(rs.getArray(columnName));
    }

    @Override
    public Long[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getArray(rs.getArray(columnIndex));
    }

    @Override
    public Long[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getArray(cs.getArray(columnIndex));
    }

    private Long[] getArray(Array array) throws SQLException {
        if (array == null) {
            return null;
        }
        Object[] objArray = (Object[]) array.getArray();
        if (objArray == null) {
            return null;
        }
        Long[] result = new Long[objArray.length];
        for (int i = 0; i < objArray.length; i++) {
            if (objArray[i] != null) {
                result[i] = ((Number) objArray[i]).longValue();
            }
        }
        return result;
    }
}
