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

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.console.TConsoleLogDao;
import com.chenyang.nse.bussiness.entity.orm.table.console.TConsoleLog;
import com.chenyang.nse.bussiness.tools.command.CommandTool;
import com.chenyang.nse.bussiness.tools.encryption.SM3Utils;
import com.chenyang.nse.bussiness.tools.io.FileTool;
import com.chenyang.nse.bussiness.tools.token.TokenUtil;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
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.ResponseBody;

@Controller
@RequestMapping({"/system/console"})
public class SystemConsoleController {
   public static final String PING = "ping";
   @Autowired
   TConsoleLogDao tConsoleLogDao;

   @PostMapping({"/command"})
   @ResponseBody
   public Response queryAll(@RequestBody(required = false) Map<String, String> map, HttpServletRequest request) {
      String command = (String)map.get("command");
      if (command.contains("ping")) {
         command = command + " -c 4";
      }

      String finalCommand = command;
      Thread thread = new Thread(() -> CommandTool.newcommand(finalCommand));
      thread.start();
      String username = "";
      if (!ObjectUtils.isEmpty(request) && !ObjectUtils.isEmpty(request.getHeader("token"))) {
         username = TokenUtil.getUserId(request.getHeader("token"));
      }

      TConsoleLog record = new TConsoleLog();
      record.setId(UUID.randomUUID().toString().replace("-", ""));
      record.setOperationObject("DDM_000000");
      record.setOperationUser(username);
      record.setModule("系统设置-系统控制台");
      record.setOperationtime(new Date());
      String column_enc = "";
      Date date = record.getOperationtime();
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      String dateString = sdf.format(date);

      try {
         column_enc = SM3Utils.encrypt(record.getOperationUser() + dateString + record.getLogmessage());
      } catch (Exception exception) {
         exception.printStackTrace();
      }

      record.setColumn_enc(column_enc);
      record.setLogmessage("用户[" + username + "]在系统控制台对[" + command + "命令]执行了操作;");
      this.tConsoleLogDao.save(record);
      return RespHelper.successResp();
   }

   @ResponseBody
   @PostMapping({"/commandlog"})
   public Response getProcessLog() {
      Properties props = new Properties();

      try {
         props = PropertiesLoaderUtils.loadAllProperties("config.properties");
      } catch (IOException e) {
         e.printStackTrace();
      }

      String path = props.getProperty("commandpath") + "/commandlog.log";
      String processlog = this.getProcesslog(path);
      return RespHelper.successResp(processlog);
   }

   public String getProcesslog(String path) {
      File logFile = new File(path);
      BufferedReader reader = null;
      StringBuffer stringBuffer = new StringBuffer();

      try {
         if (!logFile.exists()) {
            FileTool.fileDirsCreate(path);
            logFile.createNewFile();
         }

         reader = new BufferedReader(new FileReader(logFile));
         String lineStr = null;

         while((lineStr = reader.readLine()) != null) {
            stringBuffer.append(lineStr);
            stringBuffer.append("\n");
         }

         reader.close();
      } catch (Exception e) {
         throw new RuntimeException(e);
      } finally {
         if (reader != null) {
            try {
               reader.close();
            } catch (IOException e) {
               throw new RuntimeException(e);
            }
         }

      }

      return stringBuffer.toString();
   }
}
