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.dao.table.core.TCoreComplianceDirectoryDao;
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.TCoreAttachmentDirectory;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreComplianceDirectory;
import com.chenyang.nse.bussiness.entity.vo.datascope.ComplianceDirectoryReqVO;
import com.chenyang.nse.bussiness.entity.vo.datascope.ComplianceDirectoryVO;
import com.chenyang.nse.bussiness.service.console.OperationService;
import com.chenyang.nse.bussiness.service.core.ComplianceDirectoryService;
import com.chenyang.nse.bussiness.service.core.SearchFieldService;
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.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
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/compliancedirectory"})
public class ComplianceDirectoryController {
   public static final String Excel_Model_Down = "compliancedirectory.xlsx";
   @Autowired
   private ComplianceDirectoryService complianceDirectoryService;
   @Autowired
   private SearchFieldService searchFieldService;
   @Autowired
   private OperationService operationService;
   @Autowired
   TCoreComplianceDirectoryDao directoryDao;

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

   @ResponseBody
   @RequestMapping({"/saveInfo"})
   public Response<String> saveInfo(@RequestParam("file") MultipartFile file, @RequestParam("userName") String userName, @RequestParam("attachment_name") String attachment_name, @RequestParam("attachment_size") String attachment_size, @RequestParam("attachment_form") String attachment_form, @RequestParam("attachment_id") String attachment_id, @RequestParam("file_note") String file_note) {
      TCoreAttachmentDirectory dir = new TCoreAttachmentDirectory();
      dir.setCreate_user(userName);
      dir.setAttachment_name(attachment_name);
      dir.setAttachment_form(attachment_form);
      dir.setAttachment_size(attachment_size);
      dir.setFile_note(file_note);
      dir.setAttachment_id(attachment_id);
      this.complianceDirectoryService.complianceDirectorySave(file, dir);
      return RespHelper.<String>successResp();
   }

   @ResponseBody
   @RequestMapping({"/saveEdit"})
   public Response<String> saveEdit(@RequestBody Map<String, String> map) {
      String id = (String)map.get("id");
      String file_note = (String)map.get("file_note");
      String userName = (String)map.get("userName");
      TCoreAttachmentDirectory dir = new TCoreAttachmentDirectory();
      dir.setId(id);
      dir.setFile_note(file_note);
      dir.setCreate_user(userName);
      this.complianceDirectoryService.complianceDirectorySaveEdit(dir);
      return RespHelper.<String>successResp();
   }

   @ResponseBody
   @RequestMapping({"/selectfilelist"})
   public Response<List<TCoreAttachmentDirectory>> selectfilelist(@RequestBody TCoreAttachmentDirectory vo) {
      List<TCoreAttachmentDirectory> list = this.complianceDirectoryService.getselectfilelist(vo.getId());
      return RespHelper.<List<TCoreAttachmentDirectory>>successResp(list);
   }

   @ResponseBody
   @RequestMapping({"/save"})
   public Response<String> save(@RequestBody ComplianceDirectoryReqVO vo) {
      boolean isRepeat = false;
      String id = vo.getComplianceDirectoryVO().getTid();
      String fa_tid = vo.getComplianceDirectoryVO().getFa_tid() == null ? "全部" : vo.getComplianceDirectoryVO().getFa_tid();

      for(TCoreComplianceDirectory edition : this.directoryDao.queryAll(new Criterion[]{Restrictions.eq("directory_name", vo.getComplianceDirectoryVO().getText()), Restrictions.eq("edition_id", vo.getComplianceDirectoryVO().getEdition_id()), Restrictions.eq("fa_tid", fa_tid)})) {
         isRepeat = true;
         if (id == null) {
            return RespHelper.<String>errResp(ErrCode.DATA_IS_EXIST);
         }

         if (edition.getId().equals(id)) {
            isRepeat = false;
            break;
         }
      }

      if (isRepeat) {
         return RespHelper.<String>errResp(ErrCode.DATA_IS_EXIST);
      } else {
         LoginUser loginUser = vo.getLoginUser();
         DgDefineRule record = new DgDefineRule();
         record.setOperationUser(loginUser.getTsysUser().getUsername());
         record.setOperationtime(new Date());
         record.setModule("法律法规定义");
         record.setFlag("1");
         vo.getComplianceDirectoryVO().setCreate_user(loginUser.getTsysUser().getUsername());
         this.complianceDirectoryService.save(vo.getComplianceDirectoryVO());
         if (vo.getComplianceDirectoryVO().getTid() == null) {
            record.setLogmessage("新增法律法规定义");
         } else {
            record.setLogmessage("编辑法律法规定义");
         }

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

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

   @ResponseBody
   @RequestMapping({"/remove"})
   public Response<String> remove(@RequestBody ComplianceDirectoryVO vo) {
      this.complianceDirectoryService.remove(vo.getTid());
      DgDefineRule record = new DgDefineRule();
      record.setOperationUser(CommonUtils.loginUsername());
      record.setFlag("1");
      record.setOperationtime(new Date());
      record.setModule("法律法规定义");
      record.setLogmessage("删除法律法规定义");
      return RespHelper.<String>successResp();
   }

   @ResponseBody
   @RequestMapping({"/editbyid"})
   public Response<ComplianceDirectoryVO> editbyid(@RequestBody ComplianceDirectoryVO vo) {
      ComplianceDirectoryVO data = this.complianceDirectoryService.editbyid(vo.getTid());
      return RespHelper.<ComplianceDirectoryVO>successResp(data);
   }

   @RequestMapping({"/downloadfile"})
   public String downloadfile(String name, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
      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("complianceDir");
      path = path + File.separator + name;

      try {
         if (!userAgent.contains("MSIE") && !userAgent.contains("Trident")) {
            name = new String(name.getBytes("UTF-8"), "ISO-8859-1");
         } else {
            name = URLEncoder.encode(name, "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({"/editTask"})
   public Response<TCoreAttachmentDirectory> editTask(@RequestBody Map<String, String> map) {
      TCoreAttachmentDirectory data = this.complianceDirectoryService.editTask((String)map.get("fileid"));
      return RespHelper.<TCoreAttachmentDirectory>successResp(data);
   }

   @ResponseBody
   @RequestMapping({"/removeTask"})
   public Response<String> removeTask(@RequestBody Map<String, String> map) {
      String filename = (String)map.get("filename");
      String fileid = (String)map.get("fileid");
      Properties props = new Properties();

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

      String path = props.getProperty("complianceDir");
      path = path + filename;
      File fileTemp = new File(path);
      if (fileTemp.exists()) {
         fileTemp.delete();
      }

      this.complianceDirectoryService.removeTask(fileid);
      return RespHelper.<String>successResp();
   }

   @ResponseBody
   @RequestMapping({"/getmaxdatetid"})
   public Response<String> getmaxdatetid(@RequestBody ComplianceDirectoryVO vo) {
      String id = this.complianceDirectoryService.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 + "/" + "compliancedirectory.xlsx";

      try {
         String name = "compliancedirectory.xlsx";
         if (!userAgent.contains("MSIE") && !userAgent.contains("Trident")) {
            name = new String("compliancedirectory.xlsx".getBytes("UTF-8"), "ISO-8859-1");
         } else {
            name = URLEncoder.encode("compliancedirectory.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 user) {
      boolean flag = true;
      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.complianceDirectoryService.removeByEdition(editionid);
         this.complianceDirectoryService.saveExcelData(list, user, editionid);
         System.out.println(list);
      } catch (Exception e) {
         flag = false;
         e.printStackTrace();
      }

      return RespHelper.<String>successResp();
   }

   @ResponseBody
   @RequestMapping({"/checkname"})
   public String checkName(String directoryname, String projectId) {
      String check = this.complianceDirectoryService.checkName(directoryname, projectId);
      return check;
   }

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

      for(ComplianceDirectoryVO 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;
   }
}
