package com.ruoyi.core.utils;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 com.fasterxml.jackson.databind.ObjectMapper;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(Long[].class)
@MappedJdbcTypes(JdbcType.VARCHAR) // 注意：如果你的数据库字段类型是JSON，但JDBC驱动会把它当成VARCHAR处理，所以这里用VARCHAR
public class LongArrayTypeHandler extends BaseTypeHandler<Long[]> {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Long[] parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, toJson(parameter));
    }

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

    @Override
    public Long[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        return fromJson(json);
    }

    @Override
    public Long[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        return fromJson(json);
    }

    private String toJson(Long[] array) {
        try {
            return objectMapper.writeValueAsString(array);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private Long[] fromJson(String json) {
        try {
            if (json == null || json.isEmpty()) {
                return null;
            }
            return objectMapper.readValue(json, Long[].class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
