package com.chenyang.nse.bussiness.dean.impl;

import com.datech.DaToSHCA.DaToSHCA;
import com.datech.DaToSHCA.da_handle;
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 java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
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("DeAnTestServiceImpl")
public class DeAnTestServiceImpl implements TestService {
   @Autowired
   private TCoreSchedulerKmRulesDao tCoreSchedulerKmRulesDao;
   @Autowired
   private TCoreSchedulerKmLogDao tCoreSchedulerKmLogDao;
   @Autowired
   protected KeyManagerService keyManagerService;
   public static da_handle tmpHandle = new da_handle();
   public static DaToSHCA tmpTest = new DaToSHCA();
   private static final Logger LOGGER = LoggerFactory.getLogger(DeAnTestServiceImpl.class);
   @Autowired
   protected JdbcTemplate jdbcTemplate;
   private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

   public void test() {
      try {
         TestResult result = this.testDeAn();
         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 testDeAn() {
      TestResult result = new TestResult();
      Boolean testBool = this.testDecryptKey(result.message);
      if (testBool) {
         result.success = true;
      }

      return result;
   }

   private Boolean testDecryptKey(StringBuffer sb) {
      sb.append(sdf.format(new Date()) + " INFO - 开始执行加密机加密校验：\r\n");

      try {
         Map<String, String> map = this.keyManagerService.showKeyParams("7");
         boolean OpenFlag = tmpTest.DA_OpenHsmServer(tmpHandle, (String)map.get("ip"), Integer.parseInt((String)map.get("port")));
         if (!OpenFlag) {
            sb.append(sdf.format(new Date()) + " ERROR - [ERROR] DA_OpenHsmServer error ...");
            return false;
         }

         sb.append(sdf.format(new Date()) + " INFO - [SUCCESS] DA_OpenHsmServer success ...");
         byte[] inputData = tmpTest.DA_GenRandom(tmpHandle, 16);
         String encrypt = tmpTest.DA_EncKeyNum(tmpHandle, (String)map.get("salg"), Integer.parseInt((String)map.get("keynum")), inputData);
         if (null != encrypt && encrypt.length() > 0) {
            sb.append(sdf.format(new Date()) + " INFO - 加密机加密成功。\r\n");
         }

         sb.append(sdf.format(new Date()) + " INFO - 开始执行加密机解密校验：\r\n");
         byte[] decrypt = tmpTest.DA_DncKeyNum(tmpHandle, (String)map.get("salg"), Integer.parseInt((String)map.get("keynum")), encrypt);
         if (null != decrypt && decrypt.length > 0) {
            sb.append(sdf.format(new Date()) + " INFO - 加密机解密成功。\r\n");
         }

         tmpTest.DA_CloseHsmServer(tmpHandle);
      } 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");
         return false;
      }

      return true;
   }

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

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