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

import com.alibaba.fastjson.JSON;
import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import com.chenyang.nse.bussiness.entity.orm.table.core.desensitizationtask.DesensitizationTablecolumn;
import com.chenyang.nse.bussiness.entity.param.filesystem.FileDemoParam;
import com.chenyang.nse.bussiness.entity.vo.ProgressVO;
import com.chenyang.nse.bussiness.service.core.DesensitizationtaskService;
import com.chenyang.nse.bussiness.tools.datatime.DateTimeTool;
import com.chenyang.nse.bussiness.tools.io.FileTool;
import com.chenyang.nse.bussiness.tools.object.JsonTool;
import com.chenyang.nse.bussiness.tools.string.StringTool;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.ui.Model;
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/instantfilemasking"})
public class InstantFileMaskingController {
   @Autowired
   private DesensitizationtaskService desensitizationtaskService;

   @RequestMapping
   public String index(HttpServletRequest request, HttpServletResponse response, Model model) {
      return "core/instantFileMasking/createstep";
   }

   @RequestMapping({"/createtaskstep"})
   public String createtaskstep(String step, HttpServletRequest request, HttpServletResponse response, Model model) {
      return "core/instantFileMasking/" + step;
   }

   @RequestMapping({"/step01_data"})
   @ResponseBody
   public boolean step01(@RequestParam Map map, String chooseType, HttpServletRequest request) {
      request.getSession().setAttribute("instantfilemasking", map);
      return true;
   }

   @ResponseBody
   @RequestMapping({"/formatdata"})
   public List<List<String>> formatdata(@RequestBody FileDemoParam param, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<List<String>> data = new ArrayList();
      Map map = (Map)request.getSession().getAttribute("instantfilemasking");
      String datalist = (String)map.get("data");
      String cb_title = (String)map.get("cb_title");
      List<String> filecontent = (List)JsonTool.toObject(datalist, ArrayList.class);
      if (param.getSeparate() == null) {
         param = (FileDemoParam)map.get("instantfilemasking_param");
      }

      map.put("instantfilemasking_param", param);
      String separate = param.getSeparate();
      String l = param.getLimit();
      String limit = null;
      switch (l) {
         case "1":
            limit = "'";
            break;
         case "2":
            limit = "\"";
            break;
         default:
            limit = "";
      }

      String escepe = "";
      Boolean multi = 1 == 1;
      int i = 0;

      for(String str : filecontent) {
         if (i != 0 || "".equals(cb_title)) {
            data.add(StringTool.splitString(str, separate, multi, escepe, limit));
         }

         ++i;
      }

      return data;
   }

   @ResponseBody
   @RequestMapping({"/formattitle"})
   public List<DesensitizationTablecolumn> formattitle(FileDemoParam param, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<List<String>> data = new ArrayList();
      Map map = (Map)request.getSession().getAttribute("instantfilemasking");
      String datalist = (String)map.get("data");
      List<String> filecontent = (List)JsonTool.toObject(datalist, ArrayList.class);
      String cb_title = (String)map.get("cb_title");
      param = (FileDemoParam)map.get("instantfilemasking_param");
      String separate = param.getSeparate();
      String limits = param.getLimit();
      String limit = null;
      switch (limits) {
         case "1":
            limit = "'";
            break;
         case "2":
            limit = "\"";
            break;
         default:
            limit = "";
      }

      String escepe = "";

      for(String str : filecontent) {
         data.add(StringTool.splitString(str, separate, true, escepe, limit));
      }

      List<DesensitizationTablecolumn> field = new ArrayList();
      List<String> l = (List)data.get(0);

      for(int i = 0; i < l.size(); ++i) {
         DesensitizationTablecolumn temp = new DesensitizationTablecolumn();
         temp.setId(String.valueOf(i + 1));
         temp.setColumnname((String)l.get(i));
         temp.setColumnlength("100");
         temp.setRegextype("");
         temp.setRuleid("");
         if ("".equals(cb_title)) {
            temp.setColumnname("Field" + (i + 1));
         }

         field.add(temp);
      }

      request.getSession().setAttribute("DesensitizationTablecolumn", field);
      return field;
   }

   @ResponseBody
   @RequestMapping({"/formattitle_reset"})
   public List<DesensitizationTablecolumn> formattitle_reset(FileDemoParam param, HttpServletRequest request, HttpServletResponse response, Model model) {
      new ArrayList();
      List<DesensitizationTablecolumn> field = (List)request.getSession().getAttribute("DesensitizationTablecolumn");
      return field;
   }

   @ResponseBody
   @RequestMapping({"/formattitle_finsh"})
   public List<DesensitizationTablecolumn> formattitle_finsh(FileDemoParam param, HttpServletRequest request, HttpServletResponse response, Model model) {
      new ArrayList();
      List<DesensitizationTablecolumn> field = (List)request.getSession().getAttribute("finsh_DesensitizationTablecolumn");
      return field;
   }

   @ResponseBody
   @RequestMapping({"/save_data"})
   public List<DesensitizationTablecolumn> save_data(@RequestParam Map map, HttpServletRequest request, HttpServletResponse response, Model model) {
      String datalist = (String)map.get("data");
      new ArrayList();
      List<DesensitizationTablecolumn> list = JSON.parseArray(datalist, DesensitizationTablecolumn.class);
      request.getSession().setAttribute("finsh_DesensitizationTablecolumn", list);
      return null;
   }

   @ResponseBody
   @RequestMapping({"/get_info"})
   public Map get_info(HttpServletRequest request, HttpServletResponse response, Model model) {
      Map map = (Map)request.getSession().getAttribute("instantfilemasking");
      return map;
   }

   @RequestMapping({"/getFileByUp"})
   @ResponseBody
   public HashMap<String, String> getFileContent(@RequestParam("file") MultipartFile file, String progressid, HttpServletRequest request, HttpServletResponse response, Model model) {
      HashMap<String, String> hashmap = new HashMap();
      Map map = (Map)request.getSession().getAttribute("instantfilemasking");
      String stamp = DateTimeTool.formatDate(new Date(), "yyMMddHHmmss");
      new ArrayList();
      List<DesensitizationTablecolumn> colum = (List)request.getSession().getAttribute("finsh_DesensitizationTablecolumn");
      FileDemoParam param = (FileDemoParam)map.get("instantfilemasking_param");
      String filename = (String)map.get("filename");
      String[] fix = filename.split("\\.");
      String fix_suffix = fix[fix.length - 1];
      String filerealname = filename.substring(0, filename.length() - fix_suffix.length() - 1);
      map.put("fix", fix_suffix);
      map.put("realname", filerealname);
      map.put("stamp", stamp);
      map.put("limit", param.getLimit());
      map.put("separate", param.getSeparate());
      map.put("colum", colum);
      Properties props = new Properties();

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

      String path = "D:\\";
      path = request.getSession().getServletContext().getRealPath("") + props.getProperty("file_up_path");
      String downpath = request.getSession().getServletContext().getRealPath("") + props.getProperty("file_down_path");
      if (!FileTool.isFileExit(downpath)) {
         FileTool.createFolder(downpath);
      }

      if (!FileTool.isFileExit(path)) {
         FileTool.createFolder(path);
      }

      File dbffile = new File(path + "s" + stamp + "." + fix_suffix);

      try {
         dbffile.createNewFile();
         file.transferTo(dbffile);
         Long longcount = FileTool.getFileDataCountBuffered(path + "s" + stamp + "." + fix_suffix);
         map.put("longcount", longcount);
         map.put("progressid", progressid);
         System.out.println(path + "s" + stamp + "." + fix_suffix + "：行数：" + longcount);
         request.getSession().setAttribute("instantfilemasking", map);
         boolean is_generate_xml = this.desensitizationtaskService.generate_xml(map, request);
         if (is_generate_xml) {
            String webPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
            hashmap.put("path", webPath + props.getProperty("file_down_path") + "/s" + stamp + ".zip");
            hashmap.put("name", filerealname);
            return hashmap;
         } else {
            hashmap.put("path", "");
            return hashmap;
         }
      } catch (Exception e) {
         e.printStackTrace();
         hashmap.put("path", "");
         return hashmap;
      }
   }

   @ResponseBody
   @RequestMapping({"/getProgress"})
   public ProgressVO getProgress(HttpServletRequest request, String progressid) {
      ProgressVO progressVO = (ProgressVO)request.getSession().getAttribute("progress");
      if (progressVO != null && !progressVO.getProgressid().equals(progressid)) {
         request.getSession().setAttribute("progress", null);
      }

      if (progressVO == null) {
         progressVO = new ProgressVO();
         progressVO.setProgressid(progressid);
         progressVO.setProgresscontent("正在生成脱敏xml文件.........");
         progressVO.setProgressState(true);
         progressVO.setProgressValue(new Double((double)55.0F));
      }

      return progressVO;
   }

   @ResponseBody
   @RequestMapping({"/down_file"})
   public void down_file(String path, HttpServletRequest request, HttpServletResponse response, Model model) {
      path = "D:\\s181101134722.txt@s181101134722.txt";
      File file = new File(path.split("\\@")[0]);

      try {
         InputStream fis = new BufferedInputStream(new FileInputStream(file));
         byte[] buffer = new byte[fis.available()];
         fis.read(buffer);
         fis.close();
         response.reset();
         response.addHeader("Content-Disposition", "attachment;filename=" + new String(path.split("\\@")[1].getBytes("utf-8"), "ISO-8859-1"));
         response.addHeader("Content-Length", "" + file.length());
         OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
         response.setContentType("application/octet-stream");
         toClient.write(buffer);
         toClient.flush();
         toClient.close();
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }

   }
}
