package com.ruoyi.system.mapper.typehandler;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.utils.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

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

/**
 * @author wjh
 * 2024/4/1
 */
public abstract class AbstractJsonListTypeHandler<O> extends BaseTypeHandler<List<O>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<O> parameter,
                                    JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSON.toJSONString(parameter));
    }

    @Override
    public List<O> getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        String data = rs.getString(columnName);
        return StringUtils.isBlank(data) ? Collections.emptyList() : JSON.parseArray(data, (Class<O>) getRawType());
    }

    @Override
    public List<O> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String data = rs.getString(columnIndex);
        return StringUtils.isBlank(data) ? Collections.emptyList() : JSON.parseArray(data, (Class<O>) getRawType());
    }

    @Override
    public List<O> getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        String data = cs.getString(columnIndex);
        return StringUtils.isBlank(data) ? Collections.emptyList() : JSON.parseArray(data, (Class<O>) getRawType());
    }


}
