package com.goldenwater.framework.handler;

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

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

/**
 * MyBatis 自定义 TypeHandler：将数据库 CLOB / NCLOB 类型转为 String
 * <p>
 * 解决 DM 数据库返回 NClobProxyImpl 对象导致 Jackson 序列化深度超限的问题。
 * 在 MyBatis 映射阶段就将 CLOB 读取为字符串，避免 JDBC 内部对象泄漏到业务层。
 *
 * @author goldenwater
 */
@MappedTypes({String.class})
public class ClobTypeHandler extends BaseTypeHandler<String>
{
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException
    {
        ps.setString(i, parameter);
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException
    {
        return clobToString(rs.getObject(columnName));
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException
    {
        return clobToString(rs.getObject(columnIndex));
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException
    {
        return clobToString(cs.getObject(columnIndex));
    }

    /**
     * 将 Clob / NClob / ClobProxyImpl 等对象转为字符串
     */
    private String clobToString(Object obj) throws SQLException
    {
        if (obj == null)
        {
            return null;
        }
        if (obj instanceof String)
        {
            return (String) obj;
        }
        if (obj instanceof Clob)
        {
            Clob clob = (Clob) obj;
            long length = clob.length();
            if (length == 0)
            {
                return "";
            }
            return clob.getSubString(1, (int) length);
        }
        if (obj instanceof NClob)
        {
            NClob nclob = (NClob) obj;
            long length = nclob.length();
            if (length == 0)
            {
                return "";
            }
            return nclob.getSubString(1, (int) length);
        }
        return obj.toString();
    }
}
