package com.zzsn.common.util;

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

import java.io.*;
import java.sql.*;


/**
 * BLOB类型转换器
 * 创建人：李东亮
 * 创建时间：2015-5-30 下午2:28:19
 * 公司 ：郑州数能软件科技有限公司
 * @version  1.0
 *
 */
//@MappedJdbcTypes(JdbcType.BLOB) // 声明数据库中对应数据类型
//@MappedTypes(value = String.class)
public class BlobTypeHandler extends BaseTypeHandler<String> {
    @Override
    public String getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        // TODO Auto-generated method stub
        Blob blob = rs.getBlob(columnName);
        if(blob==null){
            return null;
        }
        return this.readBlob(blob, "UTF-8" );
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        // TODO Auto-generated method stub
        Blob blob = rs.getBlob(columnIndex);
        String charset = rs.getString("charset");
        if(charset==null){
            charset = "UTF-8";
        }
        return this.readBlob(blob,charset);
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        // TODO Auto-generated method stub
        Blob blob  = cs.getBlob(columnIndex);
        if(blob==null){
            return null;
        }
        return this.readBlob(blob, cs.getString("charset"));
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int columnIndex,
                                    String content, JdbcType jdbcType) throws SQLException {
        // TODO Auto-generated method stub
        try {
            ps.setBlob(columnIndex, new ByteArrayInputStream(content.getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * 获取blob字段值
     * 创建人:  李东亮
     * 创建时间:  2015-5-28 上午9:40:21
     * @version 1.0
     * @param blob
     * @return
     */
    private  String readBlob(Blob blob,String charset){

        StringBuffer result = new StringBuffer();
        if (blob != null) {
            try {
                InputStream input = blob.getBinaryStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        input,"UTF-8"));
                char[] buffer = new char[256];
                int length = -1;
                while ((length = br.read(buffer)) != -1) {
                    result.append(new String(buffer,0,length));
                }
			/*	byte[] buffer = new byte[512];
				int length = -1;
				while((length=input.read(buffer))!=-1){
				    result.append();
				}*/
            } catch (SQLException | IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return result.toString();

    }

    public static void main(String[] args) {
    }

}
