package com.chenyang.nse.bussiness.encryptor.service.impl;

import com.chenyang.nse.bussiness.dao.table.core.scheduler.TCoreSchedulerKmLogDao;
import com.chenyang.nse.bussiness.dao.table.core.scheduler.TCoreSchedulerKmRulesDao;
import com.chenyang.nse.bussiness.entity.orm.table.core.scheduler.TCoreSchedulerKmLog;
import com.chenyang.nse.bussiness.entity.orm.table.core.scheduler.TCoreSchedulerKmRules;
import com.chenyang.nse.bussiness.local.service.TestService;
import com.chenyang.nse.bussiness.service.key.KeyManagerService;
import com.chenyang.nse.bussiness.tools.encryption.EncProvider;
import java.io.File;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import kl.hsm.client.sdk.HsmSdk;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service("SdkTestServiceImpl")
public class SdkTestServiceImpl implements TestService {
   @Autowired
   private TCoreSchedulerKmRulesDao tCoreSchedulerKmRulesDao;
   @Autowired
   private TCoreSchedulerKmLogDao tCoreSchedulerKmLogDao;
   @Autowired
   private KeyManagerService keyManagerService;
   private static final Logger LOGGER = LoggerFactory.getLogger(SdkTestServiceImpl.class);
   @Autowired
   protected JdbcTemplate jdbcTemplate;
   private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

   public void test() {
      try {
         TestResult result = this.testSdk();
         this.saveTestResult(result);
      } catch (Exception e) {
         LOGGER.error(e.getMessage(), e);
      }

   }

   public void initSecretKey() {
   }

   private void saveTestResult(TestResult result) {
      TCoreSchedulerKmLog tCoreSchedulerKmLog = new TCoreSchedulerKmLog();
      tCoreSchedulerKmLog.setId(UUID.randomUUID().toString().replace("-", ""));
      tCoreSchedulerKmLog.setCreatetime(new Date());
      tCoreSchedulerKmLog.setTestTime(new Date());
      List<TCoreSchedulerKmRules> tCoreSchedulerKmRulesList = this.tCoreSchedulerKmRulesDao.queryAll();
      if (null != tCoreSchedulerKmRulesList && tCoreSchedulerKmRulesList.size() > 0) {
         tCoreSchedulerKmLog.setRulestype(((TCoreSchedulerKmRules)tCoreSchedulerKmRulesList.get(0)).getRulestype());
         if (((TCoreSchedulerKmRules)tCoreSchedulerKmRulesList.get(0)).getHowtime().equals("")) {
            tCoreSchedulerKmLog.setPollingRule("每天");
         } else {
            String[] arr1 = ((TCoreSchedulerKmRules)tCoreSchedulerKmRulesList.get(0)).getHowtime().split(",");
            StringBuilder logBuilder = new StringBuilder();

            for(int i = 0; i < arr1.length; ++i) {
               if ("1".equals(arr1[i])) {
                  logBuilder.append("周一");
               }

               if ("2".equals(arr1[i])) {
                  logBuilder.append("周二");
               }

               if ("3".equals(arr1[i])) {
                  logBuilder.append("周三");
               }

               if ("4".equals(arr1[i])) {
                  logBuilder.append("周四");
               }

               if ("5".equals(arr1[i])) {
                  logBuilder.append("周五");
               }

               if ("6".equals(arr1[i])) {
                  logBuilder.append("周六");
               }

               if ("7".equals(arr1[i])) {
                  logBuilder.append("周日");
               }
            }

            String pollingRule = "";
            if (null != logBuilder && !"".equals(logBuilder)) {
               pollingRule = logBuilder.toString();
               tCoreSchedulerKmLog.setPollingRule(pollingRule);
            }
         }
      } else {
         tCoreSchedulerKmLog.setPollingRule("每天");
         tCoreSchedulerKmLog.setRulestype("0");
      }

      if (result.success) {
         tCoreSchedulerKmLog.setTestResult("1");
      } else {
         tCoreSchedulerKmLog.setTestResult("0");
      }

      if (null != result.message && !"".equals(result.message.toString())) {
         tCoreSchedulerKmLog.setTestDetail(result.message.toString());
      }

      this.tCoreSchedulerKmLogDao.save(tCoreSchedulerKmLog);
   }

   private TestResult testSdk() throws TException {
      TestResult result = new TestResult();
      Boolean testBoolean = this.testDataKey(result.message);
      if (!testBoolean) {
         return result;
      } else {
         Boolean testBool = this.testDecryptKey(result.message);
         if (testBool && testBoolean) {
            result.success = true;
         }

         return result;
      }
   }

   private Boolean testDataKey(StringBuffer sb) throws TException {
      sb.append(sdf.format(new Date()) + " INFO - 开始执行加密机建立会话获得会话ID校验: \r\n");
      HsmSdk sdk = new HsmSdk();
      Long sessionId = 0L;

      Boolean path;
      try {
         Map<String, String> map = this.keyManagerService.showKeyParams("2");
         String pathNew = (String)map.get("hsmfiledir");
         pathNew = (pathNew.endsWith(File.separator) ? pathNew : pathNew + File.separator) + "HsmConfig.properties";
         sdk.init(pathNew);
         sessionId = sdk.openSession();
         if (null != sessionId && sessionId.toString().length() > 0) {
            sb.append(sdf.format(new Date()) + " INFO - 建立会话获得会话ID成功。\r\n");
         } else {
            sb.append(sdf.format(new Date()) + " ERR - 建立会话获得会话ID失败，会话ID为空\r\n");
         }

         Boolean var6 = true;
         return var6;
      } catch (Exception e) {
         sb.append(sdf.format(new Date()) + " ERR - 建立会话获得会话ID失败，异常为：");
         this.printException(sb, e);
         sb.append("。\r\n");
         path = false;
      } finally {
         if (sessionId > 0L) {
            sdk.closeSession(sessionId);
         }

      }

      return path;
   }

   private Boolean testDecryptKey(StringBuffer sb) throws TException {
      Map<String, String> map = this.keyManagerService.showKeyParams("2");
      String path = (String)map.get("hsmfiledir");
      path = (path.endsWith(File.separator) ? path : path + File.separator) + "HsmConfig.properties";
      String SDKKeyId = (String)map.get("sdkkeyid");
      sb.append(sdf.format(new Date()) + " INFO - 开始执行加密机加密校验：\r\n");
      HsmSdk sdk = new HsmSdk();
      Long sessionId = 0L;

      Boolean random;
      try {
         try {
            sdk.init(path);
            sessionId = sdk.openSession();
            String n16 = EncProvider.generateKey("SM4");
            ByteBuffer randomNew = ByteBuffer.wrap(n16.getBytes());
            ByteBuffer dataKeyBuf = sdk.asymEncIn(Integer.parseInt(SDKKeyId), randomNew);
            String dataKey = Base64.getEncoder().encodeToString(dataKeyBuf.array());
            if (null != dataKey && dataKey.length() > 0) {
               sb.append(sdf.format(new Date()) + " INFO - 加密机加密成功。\r\n");
            }

            sb.append(sdf.format(new Date()) + " INFO - 开始执行加密机解密校验：\r\n");
            String password = (String)map.get("sdkpassword");
            sdk.getPrivateKeyAccessRight(sessionId, Integer.parseInt(SDKKeyId), ByteBuffer.wrap(password.getBytes()));
            ByteBuffer asymDecDataByt = sdk.asymDecIn(sessionId, Integer.parseInt(SDKKeyId), dataKeyBuf);
            String dataKeyTest = new String(asymDecDataByt.array());
            if (null != dataKeyTest && dataKeyTest.length() > 0) {
               sb.append(sdf.format(new Date()) + " INFO - 加密机解密成功。\r\n");
            }

            return true;
         } catch (Exception e) {
            if (sb.toString().contains("加密机加密成功")) {
               sb.append(sdf.format(new Date()) + " ERR - 校验加密机解密失败，异常为：");
            } else {
               sb.append(sdf.format(new Date()) + " ERR - 校验加密机加密失败，异常为：");
            }
            this.printException(sb, e);
         }


         sb.append("。\r\n");
         random = false;
      } finally {
         if (sessionId > 0L) {
            sdk.closeSession(sessionId);
         }

      }

      return random;
   }

   private void printException(StringBuffer sb, Exception exception) {
      sb.append(exception.toString());
   }

   static class TestResult {
      boolean success = false;
      StringBuffer message = new StringBuffer();
   }
}
