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

import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import com.chenyang.nse.bussiness.dao.PageInfo;
import com.chenyang.nse.bussiness.entity.cache.LoginUser;
import com.chenyang.nse.bussiness.entity.orm.table.core.dataproject.TCoreProjectFileDetail;
import com.chenyang.nse.bussiness.entity.orm.table.core.desensitizationimgtask.DesensitizationImgInfo;
import com.chenyang.nse.bussiness.entity.orm.table.core.desensitizationimgtask.DesensitizationImgtask;
import com.chenyang.nse.bussiness.entity.vo.DataGridVO;
import com.chenyang.nse.bussiness.entity.vo.dataproject.ImgTaskVO;
import com.chenyang.nse.bussiness.service.core.DesensitizationImgtaskService;
import com.chenyang.nse.bussiness.tools.command.CommandTool;
import com.chenyang.nse.bussiness.tools.datatime.DateTimeTool;
import com.chenyang.nse.bussiness.tools.filesystem.FileSystemTool;
import com.chenyang.nse.bussiness.tools.string.StringTool;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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 java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.hadoop.fs.FileStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@EnableAsync
@Controller
@RequestMapping({"/core/desensitizationimgtask"})
public class DesensitizationImgTaskController {
   @Autowired
   DesensitizationImgtaskService desensitizationImgtaskService;

   @RequestMapping
   public String index(HttpServletRequest request, HttpServletResponse response, Model model, Integer pageCurr) {
      String crud = request.getParameter("crud");
      if (pageCurr != null) {
         model.addAttribute("toPageCurr", pageCurr);
      } else {
         model.addAttribute("toPageCurr", 1);
      }

      String projectid = (String)request.getSession().getAttribute("projectid");
      model.addAttribute("projectid", projectid);
      model.addAttribute("crud", crud);
      return "core/dataproject/picturemaskingtask/desensitizationimgtask_list";
   }

   @RequestMapping({"/desensitizationImg"})
   public String desensitizationImg(HttpServletRequest request, HttpServletResponse response, Model model) {
      String ip = request.getHeader("x-forwarded-for");
      if (null == ip || 0 == ip.length() || "unknown".equalsIgnoreCase(ip)) {
         ip = request.getHeader("Proxy-Client-IP");
      }

      if (null == ip || 0 == ip.length() || "unknown".equalsIgnoreCase(ip)) {
         ip = request.getHeader("WL-Proxy-Client-IP");
      }

      if (null == ip || 0 == ip.length() || "unknown".equalsIgnoreCase(ip)) {
         ip = request.getHeader("X-Real-IP");
      }

      if (null == ip || 0 == ip.length() || "unknown".equalsIgnoreCase(ip)) {
         ip = request.getRemoteAddr();
      }

      model.addAttribute("ip", ip);
      return "core/dataproject/desensitizationtask/desensitizationtask_img";
   }

   @RequestMapping({"/desensitizationImgSave"})
   public String desensitizationImgSave(@RequestParam Map<String, String> map, HttpServletRequest request, HttpServletResponse response, Model model) {
      String stamp = DateTimeTool.formatDate(new Date(), "yyMMddHHmmss");
      String projectId = (String)request.getSession().getAttribute("projectid");
      new LoginUser();
      LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
      String taskname = (String)map.get("taskname");
      String sourcedirpath = (String)map.get("sourcedirpath");
      String maskingtype = (String)map.get("maskingtype");
      String maskingcontent = (String)map.get("checkboxvals");
      String targetdirpath = (String)map.get("targetdirpath");
      String remark = (String)map.get("remark");
      String taskid = (String)map.get("taskid");
      DesensitizationImgtask desensitizationImgtask = null;
      DesensitizationImgInfo desensitizationImgInfo = null;
      if (taskid != null && !"".endsWith(taskid)) {
         List<DesensitizationImgtask> list1 = this.desensitizationImgtaskService.queryImgtaskByid(taskid);
         List<DesensitizationImgInfo> list2 = this.desensitizationImgtaskService.queryImgInfo(taskid);
         desensitizationImgtask = (DesensitizationImgtask)list1.get(0);
         desensitizationImgInfo = (DesensitizationImgInfo)list2.get(0);
         desensitizationImgtask.setUpdatatime(new Date());
      } else {
         desensitizationImgtask = new DesensitizationImgtask();
         desensitizationImgInfo = new DesensitizationImgInfo();
         desensitizationImgtask.setTasknamereal(stamp + "_" + StringTool.hanziToPinyinFirst(taskname));
         desensitizationImgtask.setUserid(loginUser.getTsysUser().getId());
         desensitizationImgtask.setUsername(loginUser.getTsysUser().getUsername());
         desensitizationImgtask.setCreatetime(new Date());
      }

      desensitizationImgtask.setTaskname(taskname);
      desensitizationImgtask.setProjectid(projectId);
      desensitizationImgtask.setRemark(remark);
      desensitizationImgtask.setFlag("0");
      this.desensitizationImgtaskService.saveDesensitizationImgtask(desensitizationImgtask);
      desensitizationImgInfo.setSourceDirPath(sourcedirpath);
      desensitizationImgInfo.setMaskingImgType(maskingtype);
      desensitizationImgInfo.setMaskingContent(maskingcontent);
      desensitizationImgInfo.setTargetDirPath(targetdirpath);
      desensitizationImgInfo.setTaskid(desensitizationImgtask.getId());
      this.desensitizationImgtaskService.saveDesensitizationImgInfo(desensitizationImgInfo);
      model.addAttribute("projectid", projectId);
      model.addAttribute("toPageCurr", 1);
      return "core/dataproject/picturemaskingtask/desensitizationimgtask_list";
   }

   @RequestMapping({"/queryImgtask"})
   @ResponseBody
   public DataGridVO<DesensitizationImgtask> queryImgtask(String isstart, String engineid, String taskname, String projectid, Integer page, Integer rows, PageInfo pageInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
      pageInfo.setPageno(page);
      pageInfo.setPagesize(rows);
      List<DesensitizationImgtask> list = this.desensitizationImgtaskService.queryImgtask(projectid, pageInfo);
      DataGridVO<DesensitizationImgtask> vo = new DataGridVO<DesensitizationImgtask>(pageInfo.getCount(), list);
      return vo;
   }

   @RequestMapping({"/queryImgInfo"})
   @ResponseBody
   public List<ImgTaskVO> queryImgInfo(String taskid, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<ImgTaskVO> list = this.desensitizationImgtaskService.queryImgByid(taskid);
      return list;
   }

   @RequestMapping({"/removetask"})
   @ResponseBody
   public void removetask(String taskid, HttpServletRequest request, HttpServletResponse response, Model model) {
      this.desensitizationImgtaskService.removeTask(taskid);
      this.desensitizationImgtaskService.removeInfoByTaskid(taskid);
   }

   @RequestMapping({"/executeTask"})
   @ResponseBody
   public String executeTask(String taskid, String tasknamereal, HttpServletRequest request, HttpServletResponse response, Model model) {
      this.desensitizationImgtaskService.queryImgtaskByid(taskid);
      List<DesensitizationImgInfo> queryImgInfoList = this.desensitizationImgtaskService.queryImgInfo(taskid);
      String sourceDirPath = ((DesensitizationImgInfo)queryImgInfoList.get(0)).getSourceDirPath();
      String targetDirPath = ((DesensitizationImgInfo)queryImgInfoList.get(0)).getTargetDirPath();
      String maskingImgType = "0".equals(((DesensitizationImgInfo)queryImgInfoList.get(0)).getMaskingImgType()) ? "mask" : "black";
      String maskingContent = ((DesensitizationImgInfo)queryImgInfoList.get(0)).getMaskingContent();

      try {
         new Properties();
         Properties e = PropertiesLoaderUtils.loadAllProperties("config.properties");
         String imglogPath = e.get("imglog_path").toString() + "/" + tasknamereal + "_log.txt";
         File imglogFile = new File(imglogPath);
         if (imglogFile.exists()) {
            imglogFile.delete();
            imglogFile.createNewFile();
         } else {
            imglogFile.createNewFile();
         }

         File sourceFile = new File(sourceDirPath);
         if (!sourceFile.getParentFile().exists()) {
            return "2";
         }

         File targetFile = new File(targetDirPath);
         if (targetFile.exists()) {
            if (targetFile.isDirectory()) {
               targetFile.createNewFile();
            }
         } else {
            File file2 = new File(targetFile.getParent());
            file2.mkdirs();
            if (!targetFile.isDirectory()) {
               file2.createNewFile();
            }
         }

         if ("0".equals(maskingContent)) {
            String commandlf = "/data/infa_imgmaksing/imgfigurebatchmasking.sh " + sourceDirPath + "/ " + targetDirPath + "/ " + maskingImgType;
            CommandTool.commandRtnToFile(commandlf, imglogPath);
         } else if (!"3".equals(maskingContent) && !"2,3".equals(maskingContent)) {
            if ("0,3".equals(maskingContent) || "0,2,3".equals(maskingContent) || "0,2".equals(maskingContent)) {
               String midpath = "/data/infa_file/midimg/";
               String commandlf1 = "/data/infa_imgmaksing/imgfigurebatchmasking.sh " + sourceDirPath + "/ " + midpath + "/ " + maskingImgType;
               CommandTool.commandRtnToFile(commandlf1, imglogPath);
               String commandlf2 = "/data/infa_imgmaksing/imgcardbatchmasking.sh " + midpath + "/ " + targetDirPath + "/ " + maskingImgType;
               CommandTool.commandRtnToFile(commandlf2, imglogPath);
               File file = new File(midpath);
               deleteFile(file);
            }
         } else {
            String commandlf = "/data/infa_imgmaksing/imgcardbatchmasking.sh " + sourceDirPath + "/ " + targetDirPath + "/ " + maskingImgType;
            CommandTool.commandRtnToFile(commandlf, imglogPath);
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

      return "sucess";
   }

   public static void deleteFile(File file) {
      if (file != null && file.exists()) {
         File[] files = file.listFiles();

         for(File f : files) {
            if (f.isDirectory()) {
               deleteFile(f);
            } else {
               f.delete();
            }
         }

      } else {
         System.out.println("文件删除失败,请检查文件路径是否正确");
      }
   }

   @RequestMapping({"/readImgLog"})
   @ResponseBody
   public Map<String, String> readImgLog(String taskid, String tasknamereal, HttpServletRequest request, HttpServletResponse response) {
      List<DesensitizationImgInfo> queryImgInfoList = this.desensitizationImgtaskService.queryImgInfo(taskid);
      String sourceDirPath = ((DesensitizationImgInfo)queryImgInfoList.get(0)).getSourceDirPath();
      String targetDirPath = ((DesensitizationImgInfo)queryImgInfoList.get(0)).getTargetDirPath();
      String maskingContent = ((DesensitizationImgInfo)queryImgInfoList.get(0)).getMaskingContent();
      Map<String, String> map = new HashMap();
      InputStream inputStream = null;
      BufferedReader br = null;
      int sucessnum = 0;
      String count = "";

      try {
         new Properties();
         Properties e = PropertiesLoaderUtils.loadAllProperties("config.properties");
         String imglogPath = e.get("imglog_path").toString() + "/" + tasknamereal + "_log.txt";
         inputStream = new FileInputStream(imglogPath);
         br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
         String patterncount = "Find .* images";
         String state = "0";
         int finishedcount = 0;

         String line;
         while((line = br.readLine()) != null) {
            if (Pattern.matches(patterncount, line)) {
               count = line.split(" ")[1];
            }

            if (line.contains(sourceDirPath) || line.contains("/data/infa_file/midimg/")) {
               ++sucessnum;
            }

            if (line.contains("finished")) {
               ++finishedcount;
            }
         }

         map.put("count", count);
         if (!"0,3".equals(maskingContent) && !"0,2,3".equals(maskingContent) && !"0,2".equals(maskingContent)) {
            map.put("sucessnum", String.valueOf(sucessnum));
            if (finishedcount > 0) {
               state = "1";
            } else {
               state = "0";
            }
         } else {
            map.put("sucessnum", String.valueOf(sucessnum / 2));
            if (finishedcount == 2) {
               state = "1";
            } else {
               state = "0";
            }
         }

         map.put("state", state);
      } catch (Exception var32) {
         System.out.println(">>>>>>>>>>>>>>>>>>>warnning：日志文件暂未生成!");
      } finally {
         if (inputStream != null) {
            try {
               inputStream.close();
            } catch (IOException var31) {
               System.out.println(">>>>>>>>>>>>>>>>>>>warnning：日志文件读取流-FileInputStream关闭报错!");
            }
         }

         if (br != null) {
            try {
               br.close();
            } catch (IOException var30) {
               System.out.println(">>>>>>>>>>>>>>>>>>>warnning：日志文件读取流-BufferedReader关闭报错!");
            }
         }

      }

      return map;
   }

   @RequestMapping({"/setState"})
   @ResponseBody
   public void setState(String taskid, HttpServletRequest request, HttpServletResponse response, Model model) {
      DesensitizationImgtask desensitizationImgtask = (DesensitizationImgtask)this.desensitizationImgtaskService.queryImgtaskByid(taskid).get(0);
      desensitizationImgtask.setFlag("1");
      this.desensitizationImgtaskService.saveDesensitizationImgtask(desensitizationImgtask);
   }

   @RequestMapping({"/isrepeatname"})
   @ResponseBody
   public boolean isrepeatname(String taskname, HttpServletRequest request, HttpServletResponse response) {
      if (taskname != null && !"".equals(taskname)) {
         String projectid = (String)request.getSession().getAttribute("projectid");
         DesensitizationImgtask desensitizationtask = this.desensitizationImgtaskService.queryTaskByName(taskname, projectid);
         return desensitizationtask == null;
      } else {
         return true;
      }
   }

   @RequestMapping({"/querydir"})
   @ResponseBody
   public Map<String, Object> querydir(String path) {
      Map<String, Object> map = new HashMap();
      List<TCoreProjectFileDetail> list = new ArrayList();
      FileSystemTool fst = new FileSystemTool();

      try {
         FileStatus[] files = FileSystemTool.getFileByPath(path);

         for(int i = 0; i < files.length; ++i) {
            FileStatus fileStatus = files[i];
            TCoreProjectFileDetail tCoreProjectFileDetail = new TCoreProjectFileDetail();
            tCoreProjectFileDetail.setFilename(fileStatus.getPath().toString().substring(fileStatus.getPath().toString().lastIndexOf("/") + 1));
            tCoreProjectFileDetail.setIsdir(fileStatus.isDir());
            if (fileStatus.isDir()) {
               tCoreProjectFileDetail.setFilesize(0L);
            } else {
               tCoreProjectFileDetail.setFilesize(fileStatus.getLen());
            }

            String os = System.getProperty("os.name");
            if (os.toLowerCase().startsWith("win")) {
               tCoreProjectFileDetail.setOwner("");
               tCoreProjectFileDetail.setPermission("");
            } else {
               tCoreProjectFileDetail.setOwner(files[i].getOwner());
               tCoreProjectFileDetail.setPermission(fileStatus.getPermission().toString());
            }

            list.add(tCoreProjectFileDetail);
         }

         map.put("result", "success");
         map.put("list", list);
      } catch (Exception e) {
         e.printStackTrace();
         map.put("result", "文件路径输入错误");
      }

      return map;
   }
}
