package com.bonus.core.common.encrypt;

import cn.hutool.core.util.StrUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import com.bonus.utils.SM4EncryptUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component
public class SM4EncDecHandler extends BaseTypeHandler {
   @Resource
   private DataEncDecProperties dataEncDecProperties;


   @Override
   public void setNonNullParameter(PreparedStatement preparedStatement, int i, Object parameter, JdbcType jdbcType) throws SQLException {
      String columnValue = (String)parameter;
      if (StrUtil.isNotEmpty(columnValue) && this.dataEncDecProperties.isEncrypted()) {
         preparedStatement.setString(i, SM4EncryptUtils.sm4Encrypt(columnValue));
      } else {
         preparedStatement.setString(i, columnValue);
      }

   }

   @Override
   public Object getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
      String columnValue = resultSet.getString(columnName);
      return StrUtil.isNotBlank(columnValue) && this.dataEncDecProperties.isEncrypted() ? SM4EncryptUtils.sm4Decrypt(columnValue) : columnValue;
   }

   @Override
   public Object getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
      String columnValue = resultSet.getString(columnIndex);
      return StrUtil.isNotBlank(columnValue) && this.dataEncDecProperties.isEncrypted() ? SM4EncryptUtils.sm4Decrypt(columnValue) : columnValue;
   }

   @Override
   public Object getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
      String columnValue = callableStatement.getString(columnIndex);
      return StrUtil.isNotBlank(columnValue) && this.dataEncDecProperties.isEncrypted() ? SM4EncryptUtils.sm4Decrypt(columnValue) : columnValue;
   }
}
