package com.chenyang.nse.bussiness.controller.core.backup;

import cn.hutool.core.util.ObjectUtil;
import com.chenyang.nse.bussiness.commmon.json.ErrCode;
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.entity.vo.dataproject.TCoreDataBackUpVO;
import com.chenyang.nse.bussiness.service.core.backup.DataBackUpService;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StreamUtils;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping({"/core/backup"})
public class DataBackUpController {
   @Autowired
   DataBackUpService dataBackUpService;

   @PostMapping({"/checkTable"})
   @ResponseBody
   public Response checkTable(@RequestBody TCoreDataBackUpVO params) {
      String msg = this.dataBackUpService.checkTable(params);
      if (msg != null) {
         return RespHelper.createResp(ErrCode.DATA_IS_EXIST.getCode(), String.format("%s 已经存在.", msg));
      } else {
         HashMap<String, String> map = new HashMap();
         map.put("msg", "1");
         return RespHelper.successResp(map);
      }
   }

   @RequestMapping({"/dataSync"})
   @ResponseBody
   public Response dataSync(@RequestBody TCoreDataBackUpVO params) {
      this.dataBackUpService.dataSync(params);
      return RespHelper.successResp();
   }

   @RequestMapping({"/exportSql"})
   @ResponseBody
   public void exportSql(HttpServletResponse response) {
      Process process = null;
      new Properties();

      try {
         Properties properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
         Runtime runtime = Runtime.getRuntime();
         String command = getExportCommand(properties);
         process = runtime.exec(command);
         process.waitFor();
         String filePath = properties.getProperty("jdbc.exportPath");
         this.loadFile(filePath, response);
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         if (process != null) {
            process.destroy();
         }

      }

   }

   @RequestMapping({"/importSql"})
   @ResponseBody
   public Response importSql(HttpServletRequest request, HttpServletResponse response, @RequestParam("fileUpload") MultipartFile sqlFile) throws IOException {
      new Properties();
      InputStream in = null;

      try {
         Properties properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
         String msg = null;
         if (ObjectUtil.isEmpty(sqlFile)) {
            msg = "请添加文件";
            Response var92 = RespHelper.successResp(msg);
            return var92;
         }

         in = sqlFile.getInputStream();
         String importPath = properties.getProperty("jdbc.importPath");
         File importFile = new File(importPath);
         if (!importFile.exists()) {
            importFile.getParentFile().mkdirs();

            try {
               importFile.createNewFile();
            } catch (IOException e) {
               e.printStackTrace();
            }
         }

         OutputStream fileOutputStreams = new FileOutputStream(importPath);
         Throwable cmdarray = null;

         try {
            byte[] temp_info = new byte[1024];
            int size = 0;

            do {
               size = in.read(temp_info);
               if (size != -1) {
                  fileOutputStreams.write(temp_info, 0, size);
               }
            } while(size != -1);
         } catch (Throwable var87) {
            cmdarray = var87;
            throw var87;
         } finally {
            if (fileOutputStreams != null) {
               if (cmdarray != null) {
                  try {
                     fileOutputStreams.close();
                  } catch (Throwable var81) {
                     cmdarray.addSuppressed(var81);
                  }
               } else {
                  fileOutputStreams.close();
               }
            }

         }

         Runtime runtime = Runtime.getRuntime();
         String[] cmdarrayNew = getImportCommand(properties);
         Process process = runtime.exec(cmdarrayNew[0]);
         OutputStream os = process.getOutputStream();
         Throwable var13 = null;

         try {
            OutputStreamWriter writer = new OutputStreamWriter(os);
            Throwable var15 = null;

            try {
               writer.write(cmdarrayNew[1] + "\r\n" + cmdarrayNew[2]);
            } catch (Throwable var82) {
               var15 = var82;
               throw var82;
            } finally {
               if (writer != null) {
                  if (var15 != null) {
                     try {
                        writer.close();
                     } catch (Throwable var80) {
                        var15.addSuppressed(var80);
                     }
                  } else {
                     writer.close();
                  }
               }

            }
         } catch (Throwable var85) {
            var13 = var85;
            throw var85;
         } finally {
            if (os != null) {
               if (var13 != null) {
                  try {
                     os.close();
                  } catch (Throwable var79) {
                     var13.addSuppressed(var79);
                  }
               } else {
                  os.close();
               }
            }

         }
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         in.close();
      }

      return RespHelper.successResp();
   }

   private static String[] getImportCommand(Properties properties) {
      String username = properties.getProperty("jdbc.user");
      String password = properties.getProperty("jdbc.password");
      String host = properties.getProperty("jdbc.host");
      String port = properties.getProperty("jdbc.port");
      String importDatabaseName = properties.getProperty("jdbc.importDatabaseName");
      String importPath = properties.getProperty("jdbc.importPath");
      String MysqlPath = properties.getProperty("MysqlPath");
      String loginCommand = MysqlPath + "mysql -h" + host + " -u" + username + " -p" + password + " -P" + port;
      String switchCommand = "use " + importDatabaseName;
      String importCommand = " source " + importPath;
      String[] commands = new String[]{loginCommand, switchCommand, importCommand};
      return commands;
   }

   private static String getExportCommand(Properties properties) {
      StringBuilder command = new StringBuilder();
      String username = properties.getProperty("jdbc.user");
      String password = properties.getProperty("jdbc.password");
      String exportDatabaseName = properties.getProperty("jdbc.exportDatabaseName");
      String host = properties.getProperty("jdbc.host");
      String port = properties.getProperty("jdbc.port");
      String exportPath = properties.getProperty("jdbc.exportPath");
      File sqlFile = new File(exportPath);
      if (!sqlFile.exists()) {
         sqlFile.getParentFile().mkdirs();

         try {
            sqlFile.createNewFile();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }

      String MysqlPath = properties.getProperty("MysqlPath");
      command.append(MysqlPath).append("mysqldump -u").append(username).append(" -p").append(password).append(" -h").append(host).append(" -P").append(port).append(" ").append(exportDatabaseName).append(" -r ").append(exportPath);
      return command.toString();
   }

   public void loadFile(String filePath, HttpServletResponse response) {
      BufferedInputStream in = null;
      BufferedOutputStream out = null;

      try {
         if (null == filePath) {
            throw new Exception("invalid filepath of null");
         }

         File file = new File(filePath);
         if (!file.exists()) {
            throw new Exception("file not exist in path [" + filePath + "]");
         }

         String fileName = file.getName();
         in = new BufferedInputStream(new FileInputStream(filePath));
         out = new BufferedOutputStream(response.getOutputStream());
         response.setContentType("application/x-download;charset=utf-8");
         response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
         byte[] buffer = new byte[8192];
         int count = 0;

         while((count = in.read(buffer, 0, 8192)) != -1) {
            out.write(buffer, 0, count);
         }

         out.flush();
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         this.closeStream(in, out);
      }

   }

   public void closeStream(InputStream in, OutputStream out) {
      if (null != in) {
         try {
            in.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }

      if (null != out) {
         try {
            out.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }

   }

   public void exportData(String name, HttpServletResponse response) throws Exception {
      File sqlFile = new File(name);
      response.setContentType("application/octet-stream");
      response.setHeader("content-disposition", "attachment; filename=backup.sql");
      response.setContentLengthLong(sqlFile.length());
      FileInputStream fileInputStream = new FileInputStream(sqlFile);
      Throwable var5 = null;

      try {
         StreamUtils.copy(fileInputStream, response.getOutputStream());
      } catch (Throwable var14) {
         var5 = var14;
         throw var14;
      } finally {
         if (fileInputStream != null) {
            if (var5 != null) {
               try {
                  fileInputStream.close();
               } catch (Throwable var13) {
                  var5.addSuppressed(var13);
               }
            } else {
               fileInputStream.close();
            }
         }

      }

   }
}
