package com.yinlihupo.enlish.service.config;

import com.yinlihupo.framework.common.util.JsonUtils;
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.List;

public class ListWordIdTypeHandler extends BaseTypeHandler<List<Integer>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Integer> parameter, JdbcType jdbcType) throws SQLException {
        try {
            String json = JsonUtils.toJsonString(parameter);
            ps.setString(i, json);
        } catch (SQLException e) {
            throw new SQLException("转换List<Word>为JSON字符串失败", e);
        }
    }

    /**
     * 获取结果（从ResultSet中按列名获取）：将JSON字符串转换为List<Word>
     */
    @Override
    public List<Integer> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseJson(rs.getString(columnName));
    }

    /**
     * 获取结果（从ResultSet中按列索引获取）
     */
    @Override
    public List<Integer> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseJson(rs.getString(columnIndex));
    }

    /**
     * 获取结果（从CallableStatement中获取）
     */
    @Override
    public List<Integer> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseJson(cs.getString(columnIndex));
    }

    private List<Integer> parseJson(String json) {
        if (json == null || json.isEmpty()) {
            return null;
        }
        try {
            return JsonUtils.parseList(json, Integer.class);
        } catch (Exception e) {
            throw new RuntimeException("转换JSON字符串为List<Word>失败", e);
        }
    }
}
