package com.starry.admin.utils;

/**
 * @Author: huchuansai
 * @Date: 2024/3/5 11:52 AM
 * @Description:
 */

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

/**
 * List<Integer> ==> string
 *
 * @Date 2022-10-08
 */
public class ListToStringHandle extends BaseTypeHandler<List> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List list, JdbcType jdbcType)
            throws SQLException {
        if (CollectionUtils.isNotEmpty(list)) {
            preparedStatement.setString(i, JSON.toJSONString(list));
        } else {
            preparedStatement.setString(i, null);
        }

    }

    @Override
    public List getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String result = resultSet.getString(s);
        return result == null ? new ArrayList<>() : JSONArray.parseArray(result);
    }

    @Override
    public List getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String result = resultSet.getString(i);
        return result == null ? new ArrayList<>() : JSONArray.parseArray(result);
    }

    @Override
    public List getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String result = callableStatement.getString(i);
        return result == null ? new ArrayList<>() : JSONArray.parseArray(result);
    }
}
