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.TCoreDataScopeDao;
import com.chenyang.nse.bussiness.entity.orm.table.core.DgDefineRule;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDataScope;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.entity.orm.table.core.dataproject.TCoreProjectVersion;
import com.chenyang.nse.bussiness.entity.orm.table.core.scopeproject.TProEditionScope;
import com.chenyang.nse.bussiness.entity.vo.datascope.DataScopeVO;
import com.chenyang.nse.bussiness.entity.vo.datascope.EditionProjectReqVO;
import com.chenyang.nse.bussiness.service.console.OperationService;
import com.chenyang.nse.bussiness.service.core.ComplianceDirectoryService;
import com.chenyang.nse.bussiness.service.core.DataScopeService;
import com.chenyang.nse.bussiness.service.core.DataSystemService;
import com.chenyang.nse.bussiness.service.core.SearchFieldService;
import com.chenyang.nse.bussiness.service.redis.RedisService;
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/datascope"})
public class DataScopeController {
   public static final String Excel_Model_Down = "datascope.xlsx";
   @Autowired
   private DataScopeService dataScopeService;
   @Autowired
   private ComplianceDirectoryService complianceDirectoryService;
   @Autowired
   private RedisService redisService;
   @Autowired
   private DataSystemService dataSystemService;
   @Autowired
   private SearchFieldService searchFieldService;
   @Autowired
   private OperationService operationService;
   @Autowired
   private TCoreDataScopeDao tCoreDataScopeDao;

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

   @ResponseBody
   @RequestMapping({"/querydatasystem"})
   public Response<List<TCoreDatasystem>> querydatasource(@RequestBody Map<String, String> map) {
      String projectId = (String)map.get("projectId");
      String userId = (String)map.get("userId");
      List<TCoreDatasystem> list = new ArrayList();
      list.addAll(this.dataSystemService.querydatasourceds(projectId, userId));
      List<TCoreDatasystem> reList = new ArrayList();

      for(int i = 0; i < list.size(); ++i) {
         String icon = ((TCoreDatasystem)list.get(i)).getDbtype().toLowerCase();
         ((TCoreDatasystem)list.get(i)).setIconCls(icon);
         if ("1".equals(((TCoreDatasystem)list.get(i)).getFlag())) {
            reList.add(list.get(i));
         }
      }

      return RespHelper.<List<TCoreDatasystem>>successResp(list);
   }

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

   @ResponseBody
   @RequestMapping({"/save"})
   public Response<String> save(@RequestBody EditionProjectReqVO vo, HttpServletRequest request) {
      DgDefineRule record = new DgDefineRule();
      record.setModule("分类定义");
      record.setFlag("1");
      record.setOperationtime(new Date());
      record.setOperationUser(vo.getLoginUser().getTsysUser().getUsername());
      vo.getDataScopeVO().setCreate_user(vo.getLoginUser().getTsysUser().getUsername());
      boolean isRepeat = false;
      String id = vo.getDataScopeVO().getTid();
      String fa_tid = vo.getDataScopeVO().getFa_tid() == null ? "全部" : vo.getDataScopeVO().getFa_tid();

      for(TCoreDataScope edition : this.tCoreDataScopeDao.queryAll(new Criterion[]{Restrictions.eq("scope_name", vo.getDataScopeVO().getText()), Restrictions.eq("edition_id", vo.getDataScopeVO().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 {
         this.dataScopeService.save(vo.getDataScopeVO());
         if (vo.getDataScopeVO().getTid() == null) {
            record.setLogmessage("新增分类定义");
         } else {
            record.setLogmessage("编辑分类定义");
         }

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

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

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

   @ResponseBody
   @RequestMapping({"/datacount"})
   public String datacount(String id, HttpServletRequest request, HttpServletResponse response, Model model) {
      this.dataScopeService.saveDataToRedis();
      this.dataScopeService.getDataFromTable();
      return "1";
   }

   @ResponseBody
   @RequestMapping({"/getprocess"})
   public String getprocess(String id, HttpServletRequest request, HttpServletResponse response, Model model) {
      String process = (String)this.redisService.get("proess");
      return process;
   }

   @ResponseBody
   @RequestMapping({"/removeDataRedis"})
   public String removeDataRedis(String id, HttpServletRequest request, HttpServletResponse response, Model model) {
      this.dataScopeService.removeDataToRedis();
      return "1";
   }

   @ResponseBody
   @RequestMapping({"/geteditionlist"})
   public Response<List<TProEditionScope>> geteditionlist(@RequestBody TCoreProjectVersion vo) {
      List<TProEditionScope> list = this.dataScopeService.geteditionlistds(vo.getProjectid());
      return RespHelper.<List<TProEditionScope>>successResp(list);
   }

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

      try {
         String name = "datascope.xlsx";
         if (!userAgent.contains("MSIE") && !userAgent.contains("Trident")) {
            name = new String("datascope.xlsx".getBytes("UTF-8"), "ISO-8859-1");
         } else {
            name = URLEncoder.encode("datascope.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.dataScopeService.removeByEdition(editionid);
         this.dataScopeService.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 scopename, String editionid) {
      String check = this.dataScopeService.checkName(scopename, editionid);
      return check;
   }

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

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