package com.chenyang.nse.bussiness.controller.key;

import com.chenyang.nse.bussiness.annot.PassToken;
import com.chenyang.nse.bussiness.commmon.json.RespHelper;
import com.chenyang.nse.bussiness.commmon.json.Response;
import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import com.chenyang.nse.bussiness.dao.table.core.encryption.TCoreEncryptionDao;
import com.chenyang.nse.bussiness.entity.orm.table.core.encryption.TCoreEncryption;
import com.chenyang.nse.bussiness.service.key.KeyManagerService;
import com.chenyang.nse.bussiness.tools.msg.MesUtil;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.thrift.TException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping({"/key/manager"})
public class KeyManagerController {
   private static String ZERO = "0";
   private static String ERR_CODE = "-1";
   private static String ONE = "1";
   private static String ENCRYPTION_RULE_NOT_NULL = "请先清空加密规则!";
   private static String NO_ENCRYPTION_TYPE = "没有获取到秘钥类型信息";
   private static String FOLDER_CLOUD = "cloud";
   private static String CALL_KEY_FAIL = "连接设备失败";
   @Autowired
   KeyManagerService keyManagerService;
   @Autowired
   TCoreEncryptionDao tCoreEncryptionDao;

   @GetMapping({"/queryKeys"})
   public Response queryKeys() throws InvocationTargetException, IllegalAccessException {
      return RespHelper.successResp(this.keyManagerService.queryTCoreKeyTypeManagementList());
   }

   @PostMapping({"/editIsUse"})
   public Response editIsUse(@RequestBody Map<String, String> param) {
      String typeId = (String)param.get("typeid");
      String isUse = (String)param.get("isuse");
      List<TCoreEncryption> encryptionList = this.tCoreEncryptionDao.queryAll();
      if (!CollectionUtils.isEmpty(encryptionList)) {
         return RespHelper.createResp(false, ERR_CODE, ENCRYPTION_RULE_NOT_NULL);
      } else {
         if (!StringUtils.isEmpty(isUse) && !StringUtils.equals(isUse, ZERO)) {
            if (!StringUtils.isEmpty(isUse) && StringUtils.equals(isUse, ONE)) {
               this.keyManagerService.setIsUseStart(typeId);
            }
         } else {
            this.keyManagerService.batchUpdateIsUseStop();
         }

         return RespHelper.successResp();
      }
   }

   @GetMapping({"/showKeyParams"})
   public Response showKeyParams(String typeid) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
      return StringUtils.isEmpty(typeid) ? RespHelper.createResp(false, ERR_CODE, NO_ENCRYPTION_TYPE) : RespHelper.successResp(this.keyManagerService.showKeyParams(typeid));
   }

   @PostMapping({"/saveKeyParams"})
   public Response saveKeyParams(@RequestBody Map<String, Object> param) {
      String typeId = (String)param.get("typeid");
      if (StringUtils.isEmpty(typeId)) {
         return RespHelper.createResp(false, ERR_CODE, NO_ENCRYPTION_TYPE);
      } else {
         return this.keyManagerService.saveParameter(param) ? RespHelper.successResp() : RespHelper.createResp(false, "POP_00022", MesUtil.getMsg("POP_00022", new String[0]));
      }
   }

   @PassToken
   @GetMapping({"/downloadHsmConfig"})
   public void downloadHsmConfig(HttpServletRequest request, HttpServletResponse response) throws IOException {
      String fileName = "HsmConfig.properties";
      response.setCharacterEncoding("utf-8");
      response.setContentType("application/octet-stream");
      response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
      OutputStream out = response.getOutputStream();
      String filePath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + File.separator + fileName;
      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
      byte[] buff = new byte[bis.available()];
      bis.read(buff);
      bis.close();
      out.write(buff);
      out.flush();
      out.close();
   }

   @PassToken
   @GetMapping({"/downloadCloudHsmConfig"})
   public void downloadCloudHsmConfig(HttpServletRequest request, HttpServletResponse response) throws IOException {
      String fileName = "HsmConfig.properties";
      response.setCharacterEncoding("utf-8");
      response.setContentType("application/octet-stream");
      response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
      OutputStream out = response.getOutputStream();
      BufferedInputStream bis = new BufferedInputStream(ClassUtils.getDefaultClassLoader().getResourceAsStream(FOLDER_CLOUD + File.separator + fileName));
      byte[] buff = new byte[bis.available()];
      bis.read(buff);
      bis.close();
      out.write(buff);
      out.flush();
      out.close();
   }

   @PostMapping({"/uploadHsmConfig"})
   public Response uploadHsmConfig(@RequestParam("file") MultipartFile file, String filePath) {
      if (file.isEmpty()) {
         return RespHelper.createResp(false, "FIS_001", MesUtil.getMsg("FIS_001", new String[0]));
      } else {
         String fileName = file.getOriginalFilename();
         if (!StringUtils.isEmpty(fileName)) {
            if (!filePath.endsWith(File.separator)) {
               filePath = filePath + File.separator;
            }

            File fileTmp = new File(filePath + fileName);
            if (!fileTmp.exists() && !fileTmp.isDirectory()) {
               fileTmp.mkdirs();
            }

            try {
               file.transferTo(fileTmp);
            } catch (Exception e) {
               e.printStackTrace();
               return RespHelper.createResp(false, "FIS_003", MesUtil.getMsg("FIS_003", new String[0]));
            }
         }

         return RespHelper.successResp(filePath + File.separator);
      }
   }

   @GetMapping({"/createParam"})
   public Response createParam(String cphpwd) {
      Map<String, String> params = this.keyManagerService.createParam(cphpwd);
      return RespHelper.successResp(params);
   }

   @GetMapping({"/testCallKey"})
   public Response testCallKey(String typeid) throws TException, InvocationTargetException, IllegalAccessException, NoSuchMethodException {
      return this.keyManagerService.testCallKey(typeid) ? RespHelper.successResp() : RespHelper.errRespStr(CALL_KEY_FAIL);
   }

   @PassToken
   @GetMapping({"/downloadSanWeiConfig"})
   public void downloadSanWeiConfig(HttpServletRequest request, HttpServletResponse response) throws IOException {
      String fileName = "swsds.ini";
      response.setCharacterEncoding("utf-8");
      response.setContentType("application/octet-stream");
      response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
      OutputStream out = response.getOutputStream();
      BufferedInputStream bis = new BufferedInputStream(ClassUtils.getDefaultClassLoader().getResourceAsStream(fileName));
      byte[] buff = new byte[bis.available()];
      bis.read(buff);
      bis.close();
      out.write(buff);
      out.flush();
      out.close();
   }

   @PostMapping({"/uploadSanWeiConfig"})
   public Response uploadSanWeiConfig(@RequestParam("file") MultipartFile file) {
      Properties props = null;
      String swsdsPath = null;
      if (file.isEmpty()) {
         return RespHelper.createResp(false, "FIS_001", MesUtil.getMsg("FIS_001", new String[0]));
      } else {
         String fileName = file.getOriginalFilename();
         if (!StringUtils.isEmpty(fileName)) {
            try {
               props = PropertiesLoaderUtils.loadAllProperties("config.properties");
            } catch (IOException e) {
               e.printStackTrace();
            }

            swsdsPath = props.getProperty("swsdsPath") + File.separator;
            File fileTmp = new File(swsdsPath + fileName);
            if (!fileTmp.exists() && !fileTmp.isDirectory()) {
               fileTmp.mkdirs();
            }

            try {
               file.transferTo(fileTmp);
            } catch (Exception e) {
               e.printStackTrace();
               return RespHelper.createResp(false, "FIS_003", MesUtil.getMsg("FIS_003", new String[0]));
            }
         }

         return RespHelper.successResp(swsdsPath);
      }
   }

   @PassToken
   @GetMapping({"/downloadZdxlzjceConfig"})
   public void downloadZdxlzjceConfig(HttpServletRequest request, HttpServletResponse response) throws IOException {
      String fileName = "zdxlz.ini";
      response.setCharacterEncoding("utf-8");
      response.setContentType("application/octet-stream");
      response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
      OutputStream out = response.getOutputStream();
      BufferedInputStream bis = new BufferedInputStream(ClassUtils.getDefaultClassLoader().getResourceAsStream(fileName));
      byte[] buff = new byte[bis.available()];
      bis.read(buff);
      bis.close();
      out.write(buff);
      out.flush();
      out.close();
   }
}
