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

import com.alibaba.fastjson.JSONObject;
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.cache.LoginUser;
import com.chenyang.nse.bussiness.entity.orm.table.core.DgDefineRule;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreSensitiveLevel;
import com.chenyang.nse.bussiness.entity.orm.table.core.scopeproject.TProEditionScope;
import com.chenyang.nse.bussiness.entity.vo.SensitiveLevelReqVO;
import com.chenyang.nse.bussiness.entity.vo.datascope.SensitivelevelVO;
import com.chenyang.nse.bussiness.service.console.OperationService;
import com.chenyang.nse.bussiness.service.core.SearchFieldService;
import com.chenyang.nse.bussiness.service.core.SensitiveLevelService;
import com.chenyang.nse.bussiness.tools.io.FileTool;
import com.chenyang.nse.bussiness.tools.login.CommonUtils;
import com.chenyang.nse.bussiness.tools.office.ExcelTool;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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/sensitivelevel"})
public class SensitiveLevelController {
   public static final String Excel_Model_Down = "sensitivelevel.xlsx";
   @Autowired
   private SensitiveLevelService sensitiveLevelService;
   @Autowired
   private SearchFieldService searchFieldService;
   @Autowired
   private OperationService operationService;

   @RequestMapping
   public String index(HttpServletRequest request, HttpServletResponse response, Model model) {
      String id = request.getParameter("id");
      model.addAttribute("id", id);
      return "core/sensitivelevel/sensitivelevelbase";
   }

   @ResponseBody
   @RequestMapping({"/save"})
   public Response<String> save(@RequestBody SensitiveLevelReqVO vo) {
      LoginUser loginUser = vo.getLoginUser();
      DgDefineRule record = new DgDefineRule();
      record.setModule("分级定义");
      record.setOperationtime(new Date());
      record.setOperationUser(loginUser.getTsysUser().getUsername());
      record.setFlag("1");
      char maxOpenLevel = this.sensitiveLevelService.getMaxOpenLevel(vo.getSensitivelevelVO().getEdition_id());
      char insertOpenLevel = 'A';
      if (!String.valueOf(maxOpenLevel).isEmpty() && maxOpenLevel != 0) {
         insertOpenLevel = (char)(maxOpenLevel + 1);
      }

      if (vo.getSensitivelevelVO().getOpen_level() == 0) {
         vo.getSensitivelevelVO().setOpen_level(insertOpenLevel);
      }

      vo.getSensitivelevelVO().setCreate_user(loginUser.getTsysUser().getUsername());
      if (vo.getSensitivelevelVO().getTid() == null && this.sensitiveLevelService.dataScopeIsExistsByName(vo.getSensitivelevelVO().getText(), vo.getSensitivelevelVO().getEdition_id())) {
         return RespHelper.<String>errResp(ErrCode.DATA_IS_EXIST);
      } else {
         this.sensitiveLevelService.save(vo.getSensitivelevelVO());
         if (vo.getSensitivelevelVO().getTid() == null) {
            record.setLogmessage("新增分级定义");
         } else {
            record.setLogmessage("编辑分级定义");
         }

         this.operationService.addDefineLog(record);
         return RespHelper.<String>successResp();
      }
   }

   @ResponseBody
   @RequestMapping({"/savereorder"})
   public Response<String> saveReorder(@RequestBody Map<String, Object> vo) {
      String moveNodeId = (String)vo.get("moveNodeId");
      String toNodeId = (String)vo.get("toNodeId");
      String moveType = (String)vo.get("moveType");
      this.sensitiveLevelService.saveReorder(moveNodeId, toNodeId, moveType);
      return RespHelper.<String>successResp();
   }

   @ResponseBody
   @RequestMapping({"/getscopetable"})
   public Response<List<SensitivelevelVO>> getScopeTable(@RequestBody SensitivelevelVO vo) {
      List<SensitivelevelVO> table = this.sensitiveLevelService.getScopeTable(vo);
      return RespHelper.<List<SensitivelevelVO>>successResp(table);
   }

   @ResponseBody
   @RequestMapping({"/remove"})
   public Response<String> remove(@RequestBody TCoreSensitiveLevel vo) {
      DgDefineRule record = new DgDefineRule();
      record.setModule("分级定义");
      record.setOperationtime(new Date());
      record.setOperationUser(CommonUtils.loginUsername());
      record.setFlag("1");
      this.sensitiveLevelService.remove(vo.getId());
      record.setLogmessage("删除分级定义");
      this.operationService.addDefineLog(record);
      return RespHelper.<String>successResp();
   }

   @ResponseBody
   @RequestMapping({"/editbyid"})
   public Response<SensitivelevelVO> editbyid(@RequestBody SensitivelevelVO vo) {
      SensitivelevelVO data = this.sensitiveLevelService.editbyid(vo.getTid());
      return data == null ? RespHelper.errResp(ErrCode.DATA_NOT_FOUND) : RespHelper.successResp(data);
   }

   @ResponseBody
   @RequestMapping({"/geteditionlist"})
   public Response<List<TProEditionScope>> geteditionlist(@RequestBody Map<String, String> map) {
      List<TProEditionScope> list = this.sensitiveLevelService.geteditionlistds((String)map.get("projectid"));
      return RespHelper.<List<TProEditionScope>>successResp(list);
   }

   @ResponseBody
   @RequestMapping({"/getmaxdatetid"})
   public Response<String> getmaxdatetid(@RequestBody SensitivelevelVO vo) {
      String id = this.sensitiveLevelService.getmaxdatetid(vo.getEdition_id());
      return RespHelper.<String>successResp(id);
   }

   @ResponseBody
   @RequestMapping({"/excelmodeldown"})
   public String excelModelDown(HttpServletRequest request, HttpServletResponse response, Model model) {
      String userAgent = request.getHeader("User-Agent");
      Properties props = new Properties();

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

      String path = props.getProperty("excelModelDown");
      path = path + "/" + "sensitivelevel.xlsx";

      try {
         String name = "sensitivelevel.xlsx";
         if (!userAgent.contains("MSIE") && !userAgent.contains("Trident")) {
            name = new String("sensitivelevel.xlsx".getBytes("UTF-8"), "ISO-8859-1");
         } else {
            name = URLEncoder.encode("sensitivelevel.xlsx", "UTF-8");
         }

         response.setCharacterEncoding("utf-8");
         response.setContentType("multipart/form-data");
         response.setHeader("Content-Disposition", "attachment;fileName=" + name);
         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();
      } catch (Exception e) {
         e.printStackTrace();
      }

      return null;
   }

   @ResponseBody
   @RequestMapping({"/excelmodelup"})
   public Response<String> excelModelUp(@RequestParam("file") MultipartFile file, @RequestParam("editionid") String editionid, @RequestParam("userName") String userName) {
      boolean flag = true;
      String user = userName;
      new Properties();
      String filename = file.getOriginalFilename();
      new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

      try {
         Properties props = PropertiesLoaderUtils.loadAllProperties("config.properties");
         String path = props.getProperty("excelModelDown");
         if (!FileTool.isFileExit(path)) {
            FileTool.createFolder(path);
         }

         File mappletfile = new File(path, filename);
         mappletfile.createNewFile();
         file.transferTo(mappletfile);
         String filepath = path + "/" + filename;
         List<List<String>> list = ExcelTool.readExcel(filepath, 0);
         this.sensitiveLevelService.removeByEdition(editionid);
         this.sensitiveLevelService.saveExcelData(list, editionid, user);
         System.out.println(list);
         FileTool.removeFile(filepath);
      } catch (Exception e) {
         flag = false;
         e.printStackTrace();
      }

      return RespHelper.<String>successResp();
   }

   @ResponseBody
   @RequestMapping({"/checkname"})
   public String checkName(String sensitivename, String editionid) {
      String check = this.sensitiveLevelService.checkName(sensitivename, editionid);
      return check;
   }

   public List<Object> getChildren(String Id, List<SensitivelevelVO> fileDirectories, List<String> fieldScopeIdList) {
      List<Object> list = new ArrayList();

      for(SensitivelevelVO f : fileDirectories) {
         JSONObject obj = new JSONObject();
         obj.put("id", f.getTid());
         obj.put("title", f.getText());
         obj.put("pid", Id);
         obj.put("spread", true);
         if (fieldScopeIdList.contains(f.getTid())) {
            obj.put("checked", true);
         }

         if (f.getChildren() != null) {
            obj.put("children", this.getChildren(f.getId(), f.getChildren(), fieldScopeIdList));
         }

         list.add(obj);
      }

      return list;
   }
}
