package com.bonus.canteen.core.common.encrypt;

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

import javax.annotation.Resource;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

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

   public void setNonNullParameter(PreparedStatement preparedStatement, int i, Object parameter, JdbcType jdbcType) throws SQLException {
      String columnValue = (String)parameter;
      if (ObjectUtil.isNotNull(columnValue)) {
         preparedStatement.setString(i, DigestAlgorithmUtil.digest(columnValue));
      } else {
         preparedStatement.setString(i, columnValue);
      }

   }

   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;
   }

   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;
   }

   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;
   }
}
