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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chenyang.nse.bussiness.annot.PassToken;
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.engine.infa.powercenter961.pubtool.StringUtil;
import com.chenyang.nse.bussiness.entity.orm.table.console.TConsoleSearchregex;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDataFileGroup;
import com.chenyang.nse.bussiness.entity.orm.table.core.dataproject.TCoreDataArea;
import com.chenyang.nse.bussiness.entity.orm.table.core.discovery.TcoreTaskFindrule;
import com.chenyang.nse.bussiness.entity.vo.ComboboxVO;
import com.chenyang.nse.bussiness.entity.vo.ResultVO;
import com.chenyang.nse.bussiness.entity.vo.dataproject.TCoreDataAreaVO;
import com.chenyang.nse.bussiness.entity.vo.dataproject.TCoreSearchregexVO;
import com.chenyang.nse.bussiness.service.console.SearchRegexService;
import com.chenyang.nse.bussiness.service.core.dataproject.ExecuteDiscoverytaskService;
import com.chenyang.nse.bussiness.tools.http.BufferUtil;
import com.chenyang.nse.bussiness.tools.login.CommonUtils;
import com.chenyang.nse.bussiness.tools.msg.MesUtil;
import com.chenyang.nse.bussiness.tools.object.ObjectTool;
import com.chenyang.nse.bussiness.tools.token.TokenUtil;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.apache.poi.xssf.usermodel.XSSFDataValidationConstraint;
import org.apache.poi.xssf.usermodel.XSSFDataValidationHelper;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
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.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping({"/core/searchregex"})
public class TdataSearchRegexController {
   @Autowired
   ExecuteDiscoverytaskService executeDiscoverytaskService;
   @Autowired
   private SearchRegexService searchRegexService;
   private static final Logger ddmauditLogger = LoggerFactory.getLogger("ddmauditLogger");
   private static final Logger operationLogger = LoggerFactory.getLogger("operationLogger");

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

   @GetMapping({"/queryAll"})
   @ResponseBody
   public Response queryAllDataArea() {
      List<TCoreDataArea> list = this.searchRegexService.queryAllDataArea();
      return RespHelper.successResp(list);
   }

   @PostMapping({"/query"})
   @ResponseBody
   public Response query(@RequestBody(required = false) Map<String, Object> params) {
      ddmauditLogger.info(MesUtil.getMsg("DDM_00701", new String[]{CommonUtils.loginUsername()}));
      String dataarea = "";
      String rulename = "";
      if (null != params) {
         dataarea = (String)params.get("dataarea");
         rulename = (String)params.get("rulename");
      } else {
         dataarea = "";
         rulename = "";
      }

      List<TCoreSearchregexVO> listAll = this.searchRegexService.queryDataAreaSearchregex(dataarea, rulename);
      List<TCoreDataArea> allDataareaList = this.searchRegexService.queryAllDataarea(params);
      Map<String, List<TCoreSearchregexVO>> reMap = new HashMap();

      for(int i = 0; i < listAll.size(); ++i) {
         TCoreSearchregexVO tCoreSearchregexVO = (TCoreSearchregexVO)listAll.get(i);
         String dataareaKey = tCoreSearchregexVO.getDataarea();
         if (!reMap.containsKey(dataareaKey)) {
            List<TCoreSearchregexVO> list = new ArrayList();
            list.add(tCoreSearchregexVO);
            reMap.put(dataareaKey, list);
         } else {
            List<TCoreSearchregexVO> list = (List)reMap.get(dataareaKey);
            list.add(tCoreSearchregexVO);
         }
      }

      List<Map<String, Object>> relist = new ArrayList();

      for(int i = 0; i < allDataareaList.size(); ++i) {
         Map<String, Object> dataMap = new HashMap();
         TCoreDataArea tCoreDataArea = (TCoreDataArea)allDataareaList.get(i);
         String dataareaname = tCoreDataArea.getDataarea();
         List<TCoreSearchregexVO> list = (List)reMap.get(dataareaname);
         if (null == list) {
            list = new ArrayList();
         }

         dataMap.put("dataarea", tCoreDataArea);
         dataMap.put("data", list);
         relist.add(dataMap);
      }

      return RespHelper.successResp(relist);
   }

   @PostMapping({"/addDataArea"})
   @ResponseBody
   public Response addDataArea(@RequestBody(required = false) Map<String, Object> params) {
      TCoreDataArea tCoreDataArea = null;
      if (null != params) {
         tCoreDataArea = (TCoreDataArea)ObjectTool.getObjectByMap(TCoreDataArea.class, (Map)params.get("tCoreDataArea"));
         if (StringUtil.isBlank(tCoreDataArea.getId())) {
            ddmauditLogger.info(MesUtil.getMsg("DDM_00721", new String[]{CommonUtils.loginUsername(), tCoreDataArea.getDataarea()}));
         } else {
            ddmauditLogger.info(MesUtil.getMsg("DDM_00722", new String[]{CommonUtils.loginUsername(), tCoreDataArea.getDataarea()}));
         }

         this.searchRegexService.saveTCoreDataArea(tCoreDataArea);
         return RespHelper.successResp();
      } else {
         return RespHelper.createResp(false, "POP_00022", MesUtil.getMsg("POP_00022", new String[0]));
      }
   }

   @PostMapping({"/delDataArea"})
   @ResponseBody
   public Response delDataArea(@RequestBody(required = false) Map<String, Object> params) {
      List<String> idlist = new ArrayList();
      String areaid = "";
      String areaname = "";
      if (null != params) {
         areaid = (String)params.get("areaid");
         areaname = (String)params.get("areaname");
      } else if (StringUtil.isBlank(areaid)) {
         areaid = "ff80808170f55b9f0170f57d5ef9000f";
         areaname = "402882eb70f190c80170f19b23e40002";
         return RespHelper.createResp(false, "POP_00022", MesUtil.getMsg("POP_00022", new String[0]));
      }

      if (StringUtil.isBlank(areaid)) {
         return RespHelper.successResp(false);
      } else {
         ddmauditLogger.info(MesUtil.getMsg("DDM_00816", new String[]{CommonUtils.loginUsername(), areaname}));
         List<TConsoleSearchregex> tsList = this.searchRegexService.querySearchregexByDaid(areaid);
         if (null != tsList && tsList.size() > 0) {
            return RespHelper.createResp(false, "POP_00023", MesUtil.getMsg("POP_00023", new String[0]));
         } else {
            idlist.add(areaid);
            this.searchRegexService.removeTCoreDataArea(idlist);
            return RespHelper.successResp();
         }
      }
   }

   @PostMapping({"/initEditDataArea"})
   @ResponseBody
   public Response initEditDataArea(@RequestBody(required = false) Map<String, Object> params) {
      String areaid = "909c577409d511eaa04ce0d55e0181c8";
      if (null != params) {
         areaid = (String)params.get("areaid");
         TCoreDataArea tCoreDataArea = this.searchRegexService.queryDataareaById(areaid);
         ddmauditLogger.info(MesUtil.getMsg("DDM_00720", new String[]{CommonUtils.loginUsername(), tCoreDataArea.getDataarea()}));
         Map<String, Object> reMap = new HashMap();
         reMap.put("tCoreDataArea", tCoreDataArea);
         return RespHelper.successResp(tCoreDataArea);
      } else {
         return RespHelper.createResp(false, "POP_00022", MesUtil.getMsg("POP_00022", new String[0]));
      }
   }

   @GetMapping({"/checkNameExitDataArea"})
   @ResponseBody
   public Response checkNameExitDataArea(@RequestParam(required = false) String areaname, @RequestParam(required = false) String id) {
      if (!StringUtil.isBlank(areaname)) {
         boolean result = this.searchRegexService.checkNameExitDataArea(areaname, id);
         return result ? RespHelper.createResp(false, "POP_00019", MesUtil.getMsg("POP_00019", new String[0])) : RespHelper.successResp(result);
      } else {
         return RespHelper.createResp(false, "POP_00022", MesUtil.getMsg("POP_00022", new String[0]));
      }
   }

   @PostMapping({"/setdefault"})
   @ResponseBody
   public Response setdefault(@RequestBody(required = false) Map<String, Object> params) {
      String ruleid = "";
      String rulename = "";
      if (null != params) {
         ruleid = (String)params.get("ruleid");
         rulename = (String)params.get("rulename");
      } else if (StringUtil.isBlank(ruleid)) {
         return RespHelper.createResp(false, "POP_00022", MesUtil.getMsg("POP_00022", new String[0]));
      }

      ddmauditLogger.info(MesUtil.getMsg("DDM_00707", new String[]{CommonUtils.loginUsername(), rulename}));
      this.searchRegexService.setDefault(ruleid);
      return RespHelper.successResp();
   }

   @PostMapping({"/del"})
   @ResponseBody
   public Response del(@RequestBody(required = false) Map<String, Object> params) {
      List<String> idlist = new ArrayList();
      String ruleid = "";
      String areaid = "";
      String rulename = "";
      String defaulttype = "";
      if (null != params) {
         ruleid = (String)params.get("ruleid");
         areaid = (String)params.get("areaid");
         rulename = (String)params.get("rulename");
         defaulttype = (String)params.get("defaulttype");
      } else if (StringUtil.isBlank(ruleid)) {
         return RespHelper.createResp(false, "POP_00022", MesUtil.getMsg("POP_00022", new String[0]));
      }

      if (StringUtil.isBlank(ruleid)) {
         return RespHelper.successResp(false);
      } else {
         ddmauditLogger.info(MesUtil.getMsg("DDM_00705", new String[]{CommonUtils.loginUsername(), rulename}));
         List<TcoreTaskFindrule> tsList = this.searchRegexService.queryTcoreTaskFindruleByRuleid(ruleid);
         if (null != tsList && tsList.size() > 0) {
            return RespHelper.createResp(false, "POP_00024", MesUtil.getMsg("POP_00024", new String[0]));
         } else {
            idlist.add(ruleid);
            this.searchRegexService.remove(idlist);
            if ("1".equals(defaulttype)) {
               this.searchRegexService.setOtherDefault(areaid);
            }

            return RespHelper.successResp();
         }
      }
   }

   @GetMapping({"/queryDataarea"})
   @ResponseBody
   public Response queryDataarea() {
      List<String> list = this.searchRegexService.queryDataarea();
      List<ComboboxVO> resultList = new ArrayList();

      for(int i = 0; i < list.size(); ++i) {
         resultList.add(new ComboboxVO((String)list.get(i)));
      }

      return RespHelper.successResp(resultList);
   }

   @PostMapping({"/queryDatafileList"})
   @ResponseBody
   public Response queryDatafileList(@RequestBody(required = false) Map<String, Object> params) {
      String ruleid = "";
      String dataarea = "";
      if (null != params) {
         ruleid = (String)params.get("ruleid");
         dataarea = (String)params.get("dataarea");
         List list = this.searchRegexService.queryDatafileList(ruleid);

         for(int i = 0; i < list.size(); ++i) {
            if (((ComboboxVO)list.get(i)).getText().equals(dataarea)) {
               list.remove(i);
            }
         }

         return RespHelper.successResp(list);
      } else {
         return RespHelper.createResp(false, "POP_00022", MesUtil.getMsg("POP_00022", new String[0]));
      }
   }

   @GetMapping({"/checkNameExit"})
   @ResponseBody
   public Response checkNameExit(@RequestParam(required = false) String rulename) {
      if (!StringUtil.isBlank(rulename)) {
         boolean result = this.searchRegexService.checkNameExit(rulename);
         return result ? RespHelper.createResp(false, "POP_00016", MesUtil.getMsg("POP_00016", new String[0])) : RespHelper.successResp(result);
      } else {
         rulename = "aaaas";
         return RespHelper.createResp(false, "POP_00022", MesUtil.getMsg("POP_00022", new String[0]));
      }
   }

   @PostMapping({"/add"})
   @ResponseBody
   public Response add(@RequestBody(required = false) Map<String, Object> params) {
      TConsoleSearchregex searchRegex = null;
      List<Object> subRuleidList = null;
      if (null == params) {
         return RespHelper.createResp(false, "POP_00022", MesUtil.getMsg("POP_00022", new String[0]));
      } else {
         searchRegex = (TConsoleSearchregex)ObjectTool.getObjectByMap(TConsoleSearchregex.class, (Map)params.get("searchRegex"));
         List<Object> var5 = (ArrayList)params.get("subRuleidList");
         ddmauditLogger.info(MesUtil.getMsg("DDM_00904", new String[]{CommonUtils.loginUsername(), searchRegex.getName()}));
         if (!"01".equals(searchRegex.getDiscoverway()) && !"04".equals(searchRegex.getDiscoverway())) {
            if ("02".equals(searchRegex.getDiscoverway())) {
               this.searchRegexService.saveConsoleSearchregex2(searchRegex, (String)null, var5);
            } else if ("03".equals(searchRegex.getDiscoverway())) {
               this.searchRegexService.saveConsoleSearchregex3(searchRegex, (String)null);
            }
         } else {
            this.searchRegexService.saveConsoleSearchregex(searchRegex, (String)null);
         }

         return RespHelper.successResp();
      }
   }

   @PostMapping({"/initEdit"})
   @ResponseBody
   public Response initEdit(@RequestBody(required = false) Map<String, Object> params) {
      String ruleid = "402881e558f25eb60158f25edcef0006";
      if (null != params) {
         ruleid = (String)params.get("ruleid");
         new TCoreSearchregexVO();
         List<TCoreSearchregexVO> tConsoleSearchregexlist = this.searchRegexService.querySearchregexById(ruleid);
         TCoreSearchregexVO tCoreSearchregexVO = (TCoreSearchregexVO)tConsoleSearchregexlist.get(0);
         List<TCoreDataFileGroup> tCoreDataFileGroupList = this.searchRegexService.querydatafileById(ruleid);
         if (tCoreDataFileGroupList != null && tCoreDataFileGroupList.size() > 0) {
            tCoreSearchregexVO.setDatafile(tCoreDataFileGroupList);
         }

         ddmauditLogger.info(MesUtil.getMsg("DDM_00702", new String[]{CommonUtils.loginUsername(), tCoreSearchregexVO.getName()}));
         Map<String, Object> reMap = new HashMap();
         reMap.put("tCoreSearchregexVO", tCoreSearchregexVO);
         return RespHelper.successResp(reMap);
      } else {
         return RespHelper.createResp(false, "POP_00022", MesUtil.getMsg("POP_00022", new String[0]));
      }
   }

   @PostMapping({"/testRegex"})
   @ResponseBody
   public Response testRegex(@RequestBody(required = false) Map<String, Object> params) {
      String regex = "";
      String testString = "";
      String discoverway = "";
      String dictionaryClass = "";
      String matchingway = "";
      List<Object> subRuleidList = null;
      if (null != params) {
         regex = (String)params.get("regex");
         testString = (String)params.get("testString");
         discoverway = (String)params.get("discoverway");
         matchingway = (String)params.get("matchingway");
         dictionaryClass = (String)params.get("dictionaryClass");
         if (null != params.get("subRuleidList")) {
            subRuleidList = (ArrayList)params.get("subRuleidList");
         }

         if (testString == null) {
            return RespHelper.createResp(false, "POP_00027", MesUtil.getMsg("POP_00027", new String[0]));
         }
      } else if (StringUtil.isBlank(regex)) {
         return RespHelper.createResp(false, "POP_00022", MesUtil.getMsg("POP_00022", new String[0]));
      }

      ResultVO vo = null;
      ResultVO vo2 = null;
      if ("01".equals(discoverway)) {
         Pattern pattern = Pattern.compile(regex);
         Matcher matcher = pattern.matcher(testString);
         vo = new ResultVO((String)null, matcher.matches());
      } else if ("02".equals(discoverway)) {
         for(int i = 0; i < subRuleidList.size(); ++i) {
            Map<String, String> map = (Map)subRuleidList.get(i);
            List<TConsoleSearchregex> list = this.searchRegexService.getBydatafileid((String)map.get("datefileid"));
            if (list != null) {
               for(int x = 0; x < list.size(); ++x) {
                  regex = ((TConsoleSearchregex)list.get(x)).getRegex();

                  try {
                     if (regex.startsWith("MethodName:")) {
                        String methodName = regex.substring(11);
                        int maxLength = -1;
                        int level = 0;
                        if (methodName.contains("MaxLength:")) {
                           String[] strings = methodName.split("\\|MaxLength:");
                           if (strings.length == 2) {
                              methodName = strings[0];
                              String[] Weight = strings[1].split("\\|Weight:");
                              maxLength = Integer.parseInt(Weight[0]);

                              try {
                                 level = Integer.parseInt(Weight[1]);
                              } catch (Exception var22) {
                                 level = 0;
                              }
                           }
                        }

                        this.executeDiscoverytaskService.init();
                        vo2 = new ResultVO((String)null, this.executeDiscoverytaskService.matches(methodName, maxLength, testString, level));
                     } else if ("".equals(testString)) {
                        vo2 = new ResultVO((String)null, false);
                     } else {
                        Pattern pattern = Pattern.compile(regex);
                        Matcher matcher = pattern.matcher(testString);
                        vo2 = new ResultVO((String)null, matcher.matches());
                     }
                  } catch (Exception ex) {
                     new ResultVO("SynaxError", true);
                     ex.printStackTrace();
                  }

                  if (vo2.getResult()) {
                     vo = new ResultVO((String)null, true);
                     break;
                  }

                  vo = new ResultVO((String)null, false);
               }
            }

            if (vo.getResult()) {
               vo = new ResultVO((String)null, true);
               break;
            }

            vo = new ResultVO((String)null, false);
         }
      } else if ("03".equals(discoverway)) {
         vo = new ResultVO((String)null, this.searchRegexService.dicmatch(dictionaryClass, matchingway, testString));
      } else {
         try {
            if (regex.startsWith("MethodName:")) {
               String methodName = regex.substring(11);
               int maxLength = -1;
               int level = 0;
               if (methodName.contains("MaxLength:")) {
                  String[] strings = methodName.split("\\|MaxLength:");
                  if (strings.length == 2) {
                     methodName = strings[0];
                     String[] Weight = strings[1].split("\\|Weight:");
                     maxLength = Integer.parseInt(Weight[0]);

                     try {
                        level = Integer.parseInt(Weight[1]);
                     } catch (Exception var20) {
                        level = 0;
                     }
                  }
               }

               this.executeDiscoverytaskService.init();
               vo = new ResultVO((String)null, this.executeDiscoverytaskService.matches(methodName, maxLength, testString, level));
            } else if ("".equals(testString)) {
               vo = new ResultVO((String)null, false);
            }
         } catch (Exception ex) {
            vo = new ResultVO("SynaxError", true);
            ex.printStackTrace();
         }
      }

      return vo != null && vo.getResult() ? RespHelper.createResp(true, "POP_00017", MesUtil.getMsg("POP_00017", new String[0])) : RespHelper.createResp(false, "POP_00018", MesUtil.getMsg("POP_00018", new String[0]));
   }

   @PostMapping({"/querybyprojectid"})
   @ResponseBody
   public Response queryByProjectid(@RequestBody(required = false) Map<String, Object> params) {
      ddmauditLogger.info(MesUtil.getMsg("DDM_00701", new String[]{CommonUtils.loginUsername()}));
      String dataarea = "";
      String rulename = "";
      String projectid = "";
      if (null != params) {
         dataarea = (String)params.get("dataarea");
         rulename = (String)params.get("rulename");
         projectid = (String)params.get("projectid");
      } else {
         dataarea = "";
         rulename = "";
         projectid = "";
      }

      List<TCoreSearchregexVO> listAll = this.searchRegexService.queryDataAreaSearchregexByProjectid(projectid);
      List<TCoreDataArea> allDataareaList = this.searchRegexService.queryDataareaByProjectid(projectid);
      Map<String, List<TCoreSearchregexVO>> reMap = new HashMap();

      for(int i = 0; i < listAll.size(); ++i) {
         TCoreSearchregexVO tCoreSearchregexVO = (TCoreSearchregexVO)listAll.get(i);
         String dataareaKey = tCoreSearchregexVO.getDataarea();
         if (!reMap.containsKey(dataareaKey)) {
            List<TCoreSearchregexVO> list = new ArrayList();
            list.add(tCoreSearchregexVO);
            reMap.put(dataareaKey, list);
         } else {
            List<TCoreSearchregexVO> list = (List)reMap.get(dataareaKey);
            list.add(tCoreSearchregexVO);
         }
      }

      List<Map<String, Object>> relist = new ArrayList();

      for(int i = 0; i < allDataareaList.size(); ++i) {
         Map<String, Object> dataMap = new HashMap();
         TCoreDataArea tCoreDataArea = (TCoreDataArea)allDataareaList.get(i);
         String dataareaname = tCoreDataArea.getDataarea();
         List<TCoreSearchregexVO> list = (List)reMap.get(dataareaname);
         if (null == list) {
            list = new ArrayList();
         }

         dataMap.put("dataarea", tCoreDataArea);
         dataMap.put("data", list);
         relist.add(dataMap);
      }

      return RespHelper.successResp(relist);
   }

   @RequestMapping({"/importExcel"})
   @ResponseBody
   public Response importExcel(@RequestPart("file") MultipartFile file, HttpServletRequest request) throws IOException {
      String username = TokenUtil.getUserId(request.getHeader("token"));
      String msg = "";
      MultipartFile excelFile = file;
      if (null == file) {
         return RespHelper.createResp(false, "POP_00022", MesUtil.getMsg("POP_00022", new String[0]));
      } else {
         InputStream in = null;
         String fileName = file.getOriginalFilename();

         try {
            in = excelFile.getInputStream();
            Workbook wb = null;
            String fileType = fileName.substring(fileName.lastIndexOf("."));
            if (".xls".equals(fileType)) {
               wb = new HSSFWorkbook(in);
            } else if (".xlsx".equals(fileType)) {
               wb = new XSSFWorkbook(in);
            }

            msg = this.searchRegexService.importExcel(wb, username);
         } catch (IOException e) {
            e.printStackTrace();
         }

         return msg.equals("导入成功") ? RespHelper.successResp(msg) : RespHelper.createResp(false, "200", msg);
      }
   }

   @PassToken
   @RequestMapping({"/exportExcelModel"})
   @ResponseBody
   public Response exportExcelModel(HttpServletResponse response) throws Exception {
      String[] headers = new String[]{"数据域名称", "数据域备注", "发现规则名称", "发现方式", "发现规则类型", "正则表达式/Java方法", "字典分类", "匹配方式", "样例", "发现规则备注", "是否为默认规则"};
      String fileName = "数据域-发现规则导出模板";
      XSSFWorkbook workbook = new XSSFWorkbook();
      XSSFSheet sheet = workbook.createSheet(fileName);
      sheet.setDefaultColumnWidth(20);
      XSSFRow row = sheet.createRow(0);
      XSSFCellStyle titleStyle = workbook.createCellStyle();
      titleStyle.setAlignment((short)2);
      titleStyle.setVerticalAlignment((short)1);
      String[] arr1 = new String[]{"字段", "数据"};
      String[] arr2 = new String[]{"正则表达式", "自定义方法", "字典发现"};
      String[] arr3 = new String[]{"等于", "包含", "左匹配", "右匹配"};
      String[] arr4 = new String[]{"是", "否"};
      XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
      XSSFDataValidationConstraint dvConstraint1 = (XSSFDataValidationConstraint)dvHelper.createExplicitListConstraint(arr1);
      XSSFDataValidationConstraint dvConstraint2 = (XSSFDataValidationConstraint)dvHelper.createExplicitListConstraint(arr2);
      XSSFDataValidationConstraint dvConstraint3 = (XSSFDataValidationConstraint)dvHelper.createExplicitListConstraint(arr3);
      XSSFDataValidationConstraint dvConstraint4 = (XSSFDataValidationConstraint)dvHelper.createExplicitListConstraint(arr4);
      CellRangeAddressList addressList1 = new CellRangeAddressList(1, 500, 3, 3);
      XSSFDataValidation validation1 = (XSSFDataValidation)dvHelper.createValidation(dvConstraint1, addressList1);
      CellRangeAddressList addressList2 = new CellRangeAddressList(1, 500, 4, 4);
      XSSFDataValidation validation2 = (XSSFDataValidation)dvHelper.createValidation(dvConstraint2, addressList2);
      CellRangeAddressList addressList3 = new CellRangeAddressList(1, 500, 7, 7);
      XSSFDataValidation validation3 = (XSSFDataValidation)dvHelper.createValidation(dvConstraint3, addressList3);
      CellRangeAddressList addressList4 = new CellRangeAddressList(1, 500, 10, 10);
      XSSFDataValidation validation4 = (XSSFDataValidation)dvHelper.createValidation(dvConstraint4, addressList4);
      sheet.addValidationData(validation1);
      sheet.addValidationData(validation2);
      sheet.addValidationData(validation3);
      sheet.addValidationData(validation4);

      for(short i = 0; i < headers.length; ++i) {
         XSSFCell cell = row.createCell(i);
         XSSFRichTextString text = new XSSFRichTextString(headers[i]);
         cell.setCellValue(text);
         cell.setCellStyle(titleStyle);
      }

      this.getExportedFied(workbook, fileName, response);
      return RespHelper.successResp();
   }

   public void getExportedFied(XSSFWorkbook workbook, String name, HttpServletResponse response) throws Exception {
      BufferedOutputStream fos = null;

      try {
         String fileName = name + ".xlsx";
         response.setContentType("application/x-msdownload");
         response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
         fos = new BufferedOutputStream(response.getOutputStream());
         workbook.write(fos);
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         if (fos != null) {
            fos.close();
         }

      }

   }

   @PassToken
   @RequestMapping({"/downloadTemplate"})
   @ResponseBody
   public Response downloadTemplate(HttpServletResponse response) {
      try {
         new Properties();
         Properties ex = PropertiesLoaderUtils.loadAllProperties("config.properties");
         String path = ex.getProperty("dataAreaExportTemplate");
         File file = new File(path + "数据域发现规则导入模板.xlsx");
         String filename = file.getName();
         String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
         InputStream fis = new BufferedInputStream(new FileInputStream(path + "数据域发现规则导入模板.xlsx"));
         byte[] buffer = new byte[fis.available()];
         fis.read(buffer);
         fis.close();
         response.reset();
         response.setCharacterEncoding("utf-8");
         response.setContentType("multipart/form-data");
         response.addHeader("content-disposition", "attachment;filename=" + new String(filename.getBytes(), "ISO8859-1"));
         response.addHeader("Content-Length", "" + file.length());
         OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
         toClient.write(buffer);
         toClient.flush();
         toClient.close();
      } catch (IOException ex) {
         ex.printStackTrace();
      }

      return RespHelper.successResp();
   }

   @PassToken
   @RequestMapping({"/dataAreaSynchronous"})
   public Response dataAreaSynchronous(HttpServletRequest request) {
      try {
         Map<String, Object> resMap = (Map)BufferUtil.parseBuffer(request, "Map");

         List<JSONObject> listNew = (List)resMap.get("data");
         for(JSONObject json : listNew) {
            TCoreDataAreaVO dataAreaVO = (TCoreDataAreaVO)JSON.parseObject(json.toString(), TCoreDataAreaVO.class);
            boolean result = this.searchRegexService.checkNameExitDataArea(dataAreaVO.getDataarea(), (String)null);
            if (!result) {
               TCoreDataArea tCoreDataArea = this.searchRegexService.saveDataArea(dataAreaVO);

               for(TCoreSearchregexVO regexVO : dataAreaVO.getRegexList()) {
                  regexVO.setTid(tCoreDataArea.getId());
                  regexVO.setDataarea(tCoreDataArea.getDataarea());
                  this.searchRegexService.saveSearchRegex(regexVO);
               }
            } else {
               for(TCoreSearchregexVO regexVO : dataAreaVO.getRegexList()) {
                  TCoreDataArea tCoreDataArea = this.searchRegexService.queryByDataArea(regexVO.getDataarea());
                  if (null != tCoreDataArea) {
                     String id = tCoreDataArea.getId();
                     String name = regexVO.getName();
                     regexVO.setTid(id);
                     regexVO.setDataarea(tCoreDataArea.getDataarea());
                     boolean a = this.searchRegexService.checkNameExit(name, id, (String)null);
                     if (a) {
                        boolean b = this.searchRegexService.checkNameExit(name, id, regexVO.getFlag(), (String)null);
                        regexVO.setName(regexVO.getName() + "-分类分级发现规则同步");
                        if (b) {
                           boolean c = this.searchRegexService.checkNameExit(name, id, regexVO.getFlag(), regexVO.getRegex());
                           if (!c) {
                              this.searchRegexService.saveSearchRegex(regexVO);
                           }
                        } else {
                           this.searchRegexService.saveSearchRegex(regexVO);
                        }
                     } else {
                        this.searchRegexService.saveSearchRegex(regexVO);
                     }
                  }
               }
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

      return RespHelper.successResp();
   }
}
