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

import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import com.chenyang.nse.bussiness.entity.cache.LoginUser;
import com.chenyang.nse.bussiness.entity.vo.mappletxml.MappletxmlVO;
import com.chenyang.nse.bussiness.service.core.mappletxml.MappletxmlDetailsService;
import com.chenyang.nse.bussiness.service.core.mappletxml.TCoreRuleMappletInfoService;
import com.chenyang.nse.bussiness.tools.command.CommandTool;
import com.chenyang.nse.bussiness.tools.io.FileTool;
import com.chenyang.nse.bussiness.tools.xml.PowerXml;
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.io.OutputStream;
import java.util.Date;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
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/mapplet"})
public class MappletxmlController {
   @Autowired
   private TCoreRuleMappletInfoService tCoreRuleMappletInfoService;
   @Autowired
   private MappletxmlDetailsService mappletxmlDetailsService;

   @RequestMapping({"/mapplet"})
   @ResponseBody
   public String page(@RequestBody MappletxmlVO mappletxmlVO, @RequestParam(value = "file",required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response, Model model) {
      Object object = request.getSession().getAttribute("loginUser");
      LoginUser loginUser = (LoginUser)object;
      String username = loginUser.getTsysUser().getUsername();
      String id = mappletxmlVO.gettCoreRuleMappletInfo().getId();
      HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
      format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
      format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
      format.setVCharType(HanyuPinyinVCharType.WITH_V);
      char[] charArray = mappletxmlVO.gettCoreRuleMappletInfo().getMappletname().trim().toCharArray();
      String output = "";

      try {
         for(int i = 0; i < charArray.length; ++i) {
            if (Character.toString(charArray[i]).matches("[\\u4E00-\\u9FA5]+")) {
               String[] temp = PinyinHelper.toHanyuPinyinStringArray(charArray[i], format);
               output = output + temp[0];
            } else {
               output = output + Character.toString(charArray[i]);
            }
         }
      } catch (BadHanyuPinyinOutputFormatCombination e) {
         e.printStackTrace();
      }

      mappletxmlVO.gettCoreRuleMappletInfo().setMappletenglishname(output);
      if (id != null && !"".equals(id)) {
         mappletxmlVO.gettCoreRuleMappletInfo().setUpdatetime(new Date());
         mappletxmlVO.gettCoreRuleMappletInfo().setModifier(username);
      } else {
         mappletxmlVO.gettCoreRuleMappletInfo().setFounder(username);
         mappletxmlVO.gettCoreRuleMappletInfo().setUpdatetime(new Date());
         mappletxmlVO.gettCoreRuleMappletInfo().setCreationtime(new Date());
         mappletxmlVO.gettCoreRuleMappletInfo().setModifier(username);
      }

      String string = this.tCoreRuleMappletInfoService.savemapplet(mappletxmlVO);
      PowerXml.generatePowerXml(mappletxmlVO);
      String execCmd = "java -jar /data/infa_file/engine/rulesXmlToJavaTxt.jar " + output + "";
      CommandTool.command(execCmd);
      return string;
   }

   @ResponseBody
   @RequestMapping({"/updataMappletxmlDetails"})
   public MappletxmlVO updataMappletxmlDetails(String mappletxmldetailsid, HttpServletRequest request, HttpServletResponse response, Model model) {
      MappletxmlVO mappletxmlVO = this.mappletxmlDetailsService.updataMappletxmlDetails(mappletxmldetailsid);
      return mappletxmlVO;
   }

   @RequestMapping({"/uploadFile"})
   public void uploadFile(@RequestParam(value = "file",required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response, Model model) {
      if (file != null) {
         String path = "/data/infa_work_report/LkpFiles/";
         String fileName = file.getOriginalFilename();
         File targetFile = new File(new File(path), fileName);

         try {
            file.transferTo(targetFile);
         } catch (Exception e) {
            e.printStackTrace();
         }
      }

   }

   @RequestMapping({"/Fileparsing"})
   @ResponseBody
   public String fileParsing(@RequestParam(value = "file",required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response, Model model) {
      InputStream in = null;
      StringBuilder result = new StringBuilder();

      try {
         in = file.getInputStream();
         BufferedReader bfr = new BufferedReader(new InputStreamReader(in, "GBK"));
         String lineTxt = null;
         if ((lineTxt = bfr.readLine()) != null) {
            result.append(lineTxt);
         }

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

      return result.toString();
   }

   @RequestMapping({"/getxmldir"})
   @ResponseBody
   public String getxmldir(@RequestBody MappletxmlVO mappletxmlVO, HttpServletRequest request, HttpServletResponse response, Model model) {
      Properties props = new Properties();

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

      HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
      format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
      format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
      format.setVCharType(HanyuPinyinVCharType.WITH_V);
      char[] charArray = mappletxmlVO.gettCoreRuleMappletInfo().getMappletname().trim().toCharArray();
      String output = "";

      try {
         for(int i = 0; i < charArray.length; ++i) {
            if (Character.toString(charArray[i]).matches("[\\u4E00-\\u9FA5]+")) {
               String[] temp = PinyinHelper.toHanyuPinyinStringArray(charArray[i], format);
               output = output + temp[0];
            } else {
               output = output + Character.toString(charArray[i]);
            }
         }
      } catch (BadHanyuPinyinOutputFormatCombination e) {
         e.printStackTrace();
      }

      mappletxmlVO.gettCoreRuleMappletInfo().setMappletenglishname(output);
      String path = props.getProperty("xml_mapplet_file_path");
      path = path + mappletxmlVO.gettCoreRuleMappletInfo().getMappletenglishname() + ".xml";
      PowerXml.generatePowerXml(mappletxmlVO);
      String execCmd = "java -jar /data/infa_file/engine/rulesXmlToJavaTxt.jar " + output + "";
      CommandTool.command(execCmd);
      return path;
   }

   @RequestMapping({"/downxmlfile"})
   @ResponseBody
   public String downxmlfile(String path, HttpServletRequest request, HttpServletResponse response, Model model) {
      int i = path.lastIndexOf("/");
      String xmlname = path.substring(i + 1);

      try {
         response.setCharacterEncoding("utf-8");
         response.setContentType("multipart/form-data");
         response.setHeader("Content-Disposition", "attachment;fileName=" + xmlname);
         InputStream inputStream = new FileInputStream(new File(path));
         OutputStream os = response.getOutputStream();
         byte[] b = new byte[2048];

         int length;
         while((length = inputStream.read(b)) > 0) {
            os.write(b, 0, length);
         }

         os.close();
         inputStream.close();
         FileTool.removeFile(path);
      } catch (Exception e) {
         e.printStackTrace();
      }

      return null;
   }

   @RequestMapping({"/backsssssss"})
   public String backssssss(String back, HttpServletRequest request, HttpServletResponse response, Model model) {
      model.addAttribute("back", back);
      return "core/customdesensitizationrules/customdesensitizationrulesdetails";
   }
}
