package com.hotent.base.typehandle;

import com.hotent.base.util.StringUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.*;
import java.time.LocalDateTime;

/*
* 将String类型转换成int，解决pgsql拼接错误问题
* 用法：在实体类TableField注解中加入 typeHandler = StringConvert2IntHandler.class
* */
public class StringConvert2IntHandler extends BaseTypeHandler<Object> {
    public StringConvert2IntHandler() {
    }
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        if (parameter instanceof LocalDateTime) {
            parameter = Timestamp.valueOf((LocalDateTime)parameter);
        }
        ps.setObject(i, parameter);
    }

    @Override
    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Object result = rs.getObject(columnName);
        return rs.wasNull() ? null : dealResult(result);
    }
    @Override
    public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Object result = rs.getObject(columnIndex);
        return rs.wasNull() ? null : dealResult(result);
    }
    @Override
    public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Object result = cs.getObject(columnIndex);
        return cs.wasNull() ? null : dealResult(result);
    }

    public Object dealResult(Object result) throws SQLException{
        return result;
    }

    /*
    * 将字符串转换成int
    * */
    @Override
    public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        if (parameter instanceof String) {
            try{
                ps.setInt(i,Integer.parseInt((String)parameter));
            }catch (Exception e){
                super.setParameter(ps,i,parameter,jdbcType);
            }
        }else{
            super.setParameter(ps,i,parameter,jdbcType);
        }
    }
}
