package com.brilliance.mda.support.mybatis.typehandler;

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

import java.sql.*;

@MappedJdbcTypes({JdbcType.VARCHAR})
public class TDStringTypeHandler extends BaseTypeHandler<String> {

    @Override
    public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        if(parameter == null || parameter.length() == 0)
            parameter = " ";
        super.setParameter(ps, i, parameter, jdbcType);
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, String parameter, JdbcType jdbcType) throws SQLException {
        if(parameter == null || parameter.length() == 0)
            parameter = " ";
        preparedStatement.setString(i,parameter);
    }

    @Override
    public String getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String value = resultSet.getString(s);
        if(value == null) {
            return "";
        }
        if(value.length() == 0) {
            value = "";
        }
        // 针对码表处理
        if (value.length() > 0  && "".equalsIgnoreCase(value.trim())) {
            return value;
        }
        value = value.trim();
        return value;
    }

    @Override
    public String getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String value = resultSet.getString(i);
        if(value == null) {
            return "";
        }
        if(value.length() == 0) {
            value = "";
        }
        // 针对码表处理
        if (value.length() > 0  && "".equalsIgnoreCase(value.trim())) {
            return value;
        }
        value = value.trim();
        return value;
    }

    @Override
    public String getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String value = callableStatement.getString(i);
        if(value == null) {
            return "";
        }
        if(value.length() == 0) {
            value = "";
        }
        // 针对码表处理
        if (value.length() > 0  && "".equalsIgnoreCase(value.trim())) {
            return value;
        }
        value = value.trim();
        return value;
    }
}
