package com.zzsn.modules.kgj.utils;

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

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.*;

/**
 * BLOB类型转换器
 */
public class BlobTypeHandler extends BaseTypeHandler<String> {

    @Override
    public String getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        Blob blob = rs.getBlob(columnName);
        return this.readBlob(blob);
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        Blob blob = rs.getBlob(columnIndex);
        return this.readBlob(blob);
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        Blob blob = cs.getBlob(columnIndex);
        return this.readBlob(blob);
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int columnIndex,
                                    String content, JdbcType jdbcType) throws SQLException {
        ps.setBlob(columnIndex, new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)));
    }

    //获取blob字段值
    private String readBlob(Blob blob) {
        StringBuilder result = new StringBuilder();
        if (blob != null) {
            try {
                InputStream input = blob.getBinaryStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        input, StandardCharsets.UTF_8));
                char[] buffer = new char[256];
                int length;
                while ((length = br.read(buffer)) != -1) {
                    result.append(new String(buffer, 0, length));
                }
            } catch (SQLException | IOException e) {
                e.printStackTrace();
            }
        }
        return result.toString();

    }

}
