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

import com.chenyang.nse.bussiness.commmon.json.RespHelper;
import com.chenyang.nse.bussiness.commmon.json.Response;
import com.chenyang.nse.bussiness.dao.table.base.TBaseUserDao;
import com.chenyang.nse.bussiness.dao.table.core.dataproject.TCoreProjectDatasourceDao;
import com.chenyang.nse.bussiness.entity.cache.LoginUser;
import com.chenyang.nse.bussiness.entity.orm.table.base.TBaseMenu;
import com.chenyang.nse.bussiness.entity.orm.table.base.TBaseUserproject;
import com.chenyang.nse.bussiness.entity.orm.table.console.TConsoleLog;
import com.chenyang.nse.bussiness.entity.orm.table.core.DgDefineRule;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasourceSchema;
import com.chenyang.nse.bussiness.entity.orm.table.core.dataproject.TCoreDataProject;
import com.chenyang.nse.bussiness.entity.orm.table.core.dataproject.TCoreDataProjectReqVO;
import com.chenyang.nse.bussiness.entity.orm.table.core.dataproject.TCoreProjectDatasource;
import com.chenyang.nse.bussiness.entity.orm.table.core.dataproject.TCoreProjectFindrule;
import com.chenyang.nse.bussiness.entity.orm.table.core.scopeproject.TProEditionScope;
import com.chenyang.nse.bussiness.entity.vo.UserVO;
import com.chenyang.nse.bussiness.entity.vo.dataproject.TCoreDataProjectVO;
import com.chenyang.nse.bussiness.entity.vo.dataproject.TCoreProjectDetailVO;
import com.chenyang.nse.bussiness.entity.vo.dataproject.TDataProjectReqVO;
import com.chenyang.nse.bussiness.jar.db.TCoreClientIpControlled;
import com.chenyang.nse.bussiness.jar.db.TCoreClientIpControlledDao;
import com.chenyang.nse.bussiness.service.console.MenuService;
import com.chenyang.nse.bussiness.service.console.OperationService;
import com.chenyang.nse.bussiness.service.console.UserService;
import com.chenyang.nse.bussiness.service.core.DataScopeService;
import com.chenyang.nse.bussiness.service.core.TdataProjectService;
import com.chenyang.nse.bussiness.tools.licensekey.LicenseKeyTool;
import com.chenyang.nse.bussiness.tools.msg.MesUtil;
import com.chenyang.nse.bussiness.tools.token.TokenUtil;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
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.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"/core/tdataproject"})
public class TdataProjectController {
   @Autowired
   private TdataProjectService tdataProjectService;
   @Autowired
   private MenuService menuService;
   @Autowired
   private UserService userService;
   @Autowired
   private DataScopeService dataScopeService;
   @Autowired
   private TBaseUserDao userDao;
   @Autowired
   private OperationService operationService;
   @Autowired
   private TCoreClientIpControlledDao clientIpControlledDao;
   @Autowired
   private TCoreProjectDatasourceDao tCoreProjectDatasourceDao;

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

   @ResponseBody
   @RequestMapping({"/checkDatasystem"})
   public Response<String> checkDatasystem() {
      int count = this.dataScopeService.checkDatasystem();
      return count == 0 ? RespHelper.successResp("无可选数据源，请添加数据源后新建项目") : RespHelper.successResp("ok");
   }

   @ResponseBody
   @RequestMapping({"/checkDatasystemName"})
   public Response<String> checkDatasystemName(@RequestBody Map<String, String> params) {
      String name = (String)params.get("name");
      String projectId = (String)params.get("projectId");
      return this.tdataProjectService.checkDatasystemName(name, projectId) ? RespHelper.successResp("true") : RespHelper.successResp("false");
   }

   @ResponseBody
   @RequestMapping({"/loadEditionList"})
   public Response<List<TProEditionScope>> loadEditionList() {
      List<TProEditionScope> list = this.dataScopeService.geteditionlistds();
      return RespHelper.<List<TProEditionScope>>successResp(list, list.size());
   }

   @ResponseBody
   @RequestMapping({"/addDataProject"})
   public Response<String> addDataProject(@RequestBody TCoreDataProjectVO vo, HttpServletRequest request) {
      String token = request.getHeader("token");
      String username = TokenUtil.getUserId(token);
      String userid = this.userDao.queryUserIdByName(TokenUtil.getUserId(token));
      TCoreDataProject projectObj = vo.getProject();
      projectObj.setCreateuser(username);
      projectObj.setCreatetime(new Date());
      projectObj.setUpdatetime(projectObj.getCreatetime());
      projectObj.setProjectType(vo.getProject().getProjectType());
      List<TCoreProjectDatasource> dataSourceList = vo.getDataSourceIdList();
      List<TCoreProjectFindrule> areaAndRuleList = vo.getAreaAndRuleList();
      List<TCoreDatasourceSchema> schemalist = vo.getSchemalist();
      this.tdataProjectService.addDataProject(projectObj, dataSourceList, areaAndRuleList, schemalist);
      TBaseUserproject userPro = new TBaseUserproject();
      userPro.setProid(projectObj.getId());
      userPro.setUserid(userid);
      userPro.setCrud("1");
      userPro.setUpdateuserid(userid);
      this.userService.saveUserPro(userPro);
      DgDefineRule record1 = new DgDefineRule();
      record1.setOperationUser(username);
      record1.setOperationtime(new Date());
      record1.setModule("项目绑定版本");
      record1.setFlag("2");
      record1.setProjectId(projectObj.getId());
      this.operationService.addDefineLog(record1);
      this.userService.changeGlobalOriginalConfig(1, projectObj.getId());
      String projectId = projectObj.getId();
      if (StringUtils.isNotEmpty(projectId)) {
         TCoreClientIpControlled tCoreClientIpControlled = new TCoreClientIpControlled();
         tCoreClientIpControlled.setContent("0.0.0.0/255.255.255.255");
         tCoreClientIpControlled.setType(1);
         tCoreClientIpControlled.setIs_equals("1");
         tCoreClientIpControlled.setProject_id(projectId);
         this.clientIpControlledDao.remove(new Criterion[]{Restrictions.eq("project_id", projectId)});
         this.clientIpControlledDao.save(tCoreClientIpControlled);
      }

      return RespHelper.<String>successResp(projectId);
   }

   @ResponseBody
   @RequestMapping({"/checkProjectNum"})
   public Response<String> checkProjectNum() {
      List<TCoreProjectDatasource> tCoreProjectDataSources = this.tCoreProjectDatasourceDao.queryAll();
      if (!CollectionUtils.isEmpty(tCoreProjectDataSources)) {
         int size = tCoreProjectDataSources.size();
         Map<String, String> map = LicenseKeyTool.map;

         try {
            if (!CollectionUtils.isEmpty(map)) {
               String projectNumStr = (String)map.get("projectNum");
               if (StringUtils.isEmpty(projectNumStr)) {
                  return RespHelper.<String>createResp(false, "POP_00037", MesUtil.getMsg("POP_00037", new String[0]));
               }

               int projectNum = Integer.parseInt(projectNumStr);
               if (size >= projectNum) {
                  return RespHelper.<String>createResp(false, "POP_00036", MesUtil.getMsg("POP_00036", new String[]{projectNumStr}));
               }
            }
         } catch (Exception e) {
            e.printStackTrace();
            return RespHelper.<String>createResp(false, "POP_00037", MesUtil.getMsg("POP_00037", new String[0]));
         }
      }

      return RespHelper.<String>successResp();
   }

   @ResponseBody
   @RequestMapping({"/getDataProjectDetail"})
   public Response<TCoreDataProjectVO> getDataProjectDetail(@RequestBody Map<String, String> map) {
      String projectId = (String)map.get("projectId");
      TCoreDataProjectVO vo = this.tdataProjectService.getDataProjectDetail(projectId);
      return RespHelper.<TCoreDataProjectVO>successResp(vo);
   }

   @ResponseBody
   @RequestMapping({"/updateDataProject"})
   public Response<String> updateDataProject(@RequestBody TCoreDataProjectVO vo) {
      String projectid = vo.getProject().getId();
      String eid = this.tdataProjectService.queryEdtionIdByProId(projectid);
      String edition_id = vo.getProject().getEdition_id();
      if (!eid.equals(edition_id)) {
         DgDefineRule record = new DgDefineRule();
         record.setOperationUser(vo.getLoginUser().getTsysUser().getUsername());
         record.setOperationtime(new Date());
         record.setModule("项目修改版本");
         record.setFlag("2");
         record.setProjectId(projectid);
         record.setLogmessage("项目修改版本为：" + this.dataScopeService.getEditionNameById(edition_id));
         this.operationService.addDefineLog(record);
      }

      this.tdataProjectService.updateDataProject(vo);
      return RespHelper.<String>successResp();
   }

   @ResponseBody
   @RequestMapping({"/saveDataProject"})
   public Response<String> saveDataProject(@RequestBody TCoreDataProjectReqVO vo) {
      LoginUser loginUser = vo.getLoginUser();
      TCoreDataProject obj = vo.getProject();
      obj.setCreateuser(loginUser.getTsysUser().getUsername());
      obj.setCreatetime(new Date());
      this.tdataProjectService.saveDataProject(obj);
      TBaseUserproject userPro = new TBaseUserproject();
      userPro.setProid(obj.getId());
      userPro.setUserid(loginUser.getTsysUser().getId());
      userPro.setCrud("1");
      userPro.setUpdateuserid(loginUser.getTsysUser().getId());
      this.userService.saveUserPro(userPro);
      TConsoleLog record = new TConsoleLog();
      String username = loginUser.getTsysUser().getUsername();
      record.setUser(username);
      record.setLogmessage("新增项目");
      record.setModule("项目模块");
      record.setOperationtime(new Date());
      record.setOperationObject(obj.getProject());
      this.operationService.add(record);
      return RespHelper.<String>successResp();
   }

   @ResponseBody
   @RequestMapping({"/editDataProject"})
   @Transactional
   public Response<String> editDataProject(@RequestBody TCoreDataProjectReqVO vo) {
      LoginUser loginUser = vo.getLoginUser();
      TCoreDataProject obj = vo.getProject();
      obj.setUpdateuser(loginUser.getTsysUser().getUsername());
      obj.setUpdatetime(new Date());
      this.tdataProjectService.editDataProject(obj);
      TConsoleLog record = new TConsoleLog();
      String username = loginUser.getTsysUser().getUsername();
      record.setUser(username);
      record.setLogmessage("编辑项目");
      record.setModule("项目模块");
      record.setOperationtime(new Date());
      record.setOperationObject(obj.getProject());
      this.operationService.add(record);
      return RespHelper.<String>successResp();
   }

   @ResponseBody
   @RequestMapping({"/deleteDataProject"})
   public Response<String> deleteDataProject(@RequestBody TCoreDataProjectReqVO vo, HttpServletRequest request) {
      String projectId = vo.getProject().getId();
      Map<String, String> map = this.tdataProjectService.deleteDataProject(projectId);
      String flag = (String)map.get("flag");
      if ("false".equals(flag)) {
         return RespHelper.<String>createResp(false, "202", (String)map.get("msg"));
      } else {
         String token = request.getHeader("token");
         String username = TokenUtil.getUserId(token);
         if (StringUtils.isNotEmpty(projectId)) {
            this.clientIpControlledDao.remove(new Criterion[]{Restrictions.eq("project_id", projectId)});
         }

         return RespHelper.<String>successResp();
      }
   }

   @ResponseBody
   @RequestMapping({"/deleteRelationdata"})
   public void deleteRelationdata(String id, String project, HttpServletRequest request, HttpServletResponse response, Model model) {
      this.tdataProjectService.deleteRelationdata(id);
   }

   @ResponseBody
   @RequestMapping({"/selectOneDataProject"})
   public TCoreDataProject selectOneDataProject(String id, HttpServletRequest request, HttpServletResponse response, Model model) {
      TCoreDataProject obj = this.tdataProjectService.selectOneDataProject(id);
      return obj;
   }

   @ResponseBody
   @RequestMapping({"/selectDataProject"})
   public Response<List<TCoreProjectDetailVO>> selectDataProject(@RequestBody TDataProjectReqVO vo) {
      LoginUser loginUser = vo.getLoginUser();
      String note = vo.getNote();
      String proName = vo.getProName();
      String uid = loginUser.getTsysUser().getId();
      String gid = loginUser.getTsysGroup() == null ? "" : loginUser.getTsysGroup().getId();
      String userid = "";
      if (!"1".equals(uid)) {
         userid = "('" + uid + "','" + gid + "')";
      }

      List<TCoreProjectDetailVO> proList = new ArrayList();
      new ArrayList();
      List<TCoreDataProject> list1 = new ArrayList();
      if (!loginUser.getTsysUser().getId().equals("1")) {
         List<TCoreDataProject> list2 = this.tdataProjectService.selectMyDataProject(loginUser.getTsysUser().getId(), proName, note);
         UserVO uservo = this.userService.queryByUserid(loginUser.getTsysUser().getId());
         if (uservo != null) {
            List<TCoreDataProject> list3 = this.tdataProjectService.selectMyDataProject(uservo.getGroupid(), proName, note);
            Map<String, TCoreDataProject> allProject = new HashMap();

            for(TCoreDataProject userpro : list2) {
               allProject.put(userpro.getId(), userpro);
            }

            for(TCoreDataProject userpro : list3) {
               allProject.put(userpro.getId(), userpro);
            }

            for(Map.Entry<String, TCoreDataProject> a : allProject.entrySet()) {
               list1.add(a.getValue());
            }
         }
      } else {
         list1 = this.tdataProjectService.selectDataProject(proName, note);
      }

      Collections.sort(list1, new Comparator<TCoreDataProject>() {
         public int compare(TCoreDataProject o1, TCoreDataProject o2) {
            if (o2.getUpdatetime() != null && o1.getUpdatetime() != null) {
               return o2.getUpdatetime().compareTo(o1.getUpdatetime());
            } else if (o2.getUpdatetime() == null) {
               return -1;
            } else {
               return o1.getUpdatetime() == null ? 1 : 0;
            }
         }
      });
      List list;
      if (list1.size() < vo.getPage() * vo.getEverypage()) {
         list = list1.subList((vo.getPage() - 1) * vo.getEverypage(), list1.size());
      } else {
         list = list1.subList((vo.getPage() - 1) * vo.getEverypage(), vo.getPage() * vo.getEverypage());
      }

      for(int i = 0; i < list.size(); ++i) {
         TCoreProjectDetailVO tCoreProjectDetailVO = new TCoreProjectDetailVO();
         String id = ((TCoreDataProject)list.get(i)).getId();
         String edition_id = ((TCoreDataProject)list.get(i)).getEdition_id();
         List<Map<String, Object>> sourceL = this.tdataProjectService.selectSource(id, "");
         List<Map<String, Object>> areaL = this.tdataProjectService.selectArea(id);
         List<Map<String, Object>> dataScopeL = this.tdataProjectService.selectDataScopeCount(id, edition_id);
         List<Map<String, Object>> sensitiveLevelL = this.tdataProjectService.selectSensitiveLevelCount(id, edition_id);
         List<Map<String, Object>> compliancedirL = this.tdataProjectService.selectComplianceDirCount1(edition_id);
         List<Map<String, Object>> findRuleL = this.tdataProjectService.selectFindRuleById(id);
         Map<String, Object> map = new HashMap();
         Map<String, Object> map1 = new HashMap();
         List<Map<String, Object>> maplist = new ArrayList();
         List<Map<String, Object>> maplist1 = new ArrayList();
         map.put("s", 0);
         maplist.add(map);
         map1.put("s", 1);
         maplist1.add(map1);
         sourceL.addAll(areaL);
         if (Integer.valueOf(((Map)findRuleL.get(0)).get("s").toString()) == 0) {
            sourceL.addAll(maplist);
         } else {
            sourceL.add(findRuleL.get(0));
         }

         if (Integer.valueOf(((Map)dataScopeL.get(0)).get("s").toString()) == 0) {
            sourceL.addAll(maplist);
         } else {
            sourceL.addAll(maplist1);
         }

         if (Integer.valueOf(((Map)sensitiveLevelL.get(0)).get("s").toString()) == 0) {
            sourceL.addAll(maplist);
         } else {
            sourceL.addAll(maplist1);
         }

         if (Integer.valueOf(((Map)compliancedirL.get(0)).get("s").toString()) == 0) {
            sourceL.addAll(maplist);
         } else {
            sourceL.addAll(maplist1);
         }

         tCoreProjectDetailVO.setEdition_id(((TCoreDataProject)list.get(i)).getEdition_id());
         tCoreProjectDetailVO.setList(sourceL);
         tCoreProjectDetailVO.setCreateTime((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(((TCoreDataProject)list.get(i)).getCreatetime()));
         tCoreProjectDetailVO.setCreateuser(((TCoreDataProject)list.get(i)).getCreateuser());
         tCoreProjectDetailVO.setId(((TCoreDataProject)list.get(i)).getId());
         tCoreProjectDetailVO.setNote(((TCoreDataProject)list.get(i)).getNote());
         tCoreProjectDetailVO.setProject(((TCoreDataProject)list.get(i)).getProject());
         proList.add(tCoreProjectDetailVO);
      }

      return RespHelper.<List<TCoreProjectDetailVO>>successResp(proList, list1.size());
   }

   public void addMenu(TCoreDataProject obj) {
      TBaseMenu baseMenu = new TBaseMenu();
      List<TBaseMenu> subMenu = new ArrayList();
      List<TBaseMenu> subMenu_is = new ArrayList();
      baseMenu.setMenuname(obj.getProject());
      baseMenu.setIcon("fa-cog");
      baseMenu.setFlag("1");
      baseMenu.setNote(obj.getId());
      String[] name = new String[]{"数据源", "数据域", "数据发现", "数据脱敏"};
      String[] url = new String[]{"/core/tdatasource?id=", "/core/tdataarea?id=", "/core/tdatadiscovery?id=", "/core/desensitizationtask?id="};
      this.menuService.add(baseMenu, subMenu);

      for(int i = 0; i < 4; ++i) {
         TBaseMenu baseMenu_is = new TBaseMenu();
         baseMenu_is.setMenuname(name[i]);
         baseMenu_is.setUrl(url[i] + obj.getId());
         baseMenu_is.setFlag("1");
         baseMenu_is.setNote(obj.getId());
         subMenu_is.add(baseMenu_is);
      }

      this.menuService.add((String)baseMenu.getId(), (String)null, (List)subMenu_is);
   }

   public void removeMenu(String id) {
      this.menuService.remove(id);
   }

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

   @ResponseBody
   @RequestMapping({"/allProject"})
   public Response<List<TCoreProjectDetailVO>> getAllProject(@RequestBody TDataProjectReqVO vo) {
      LoginUser loginUser = vo.getLoginUser();
      String note = vo.getNote();
      String proName = vo.getProName();
      String uid = loginUser.getTsysUser().getId();
      String gid = loginUser.getTsysGroup() == null ? "" : loginUser.getTsysGroup().getId();
      String userid = "";
      if (!"1".equals(uid)) {
         userid = "('" + uid + "','" + gid + "')";
      }

      List<TCoreProjectDetailVO> proList = new ArrayList();
      List<TCoreDataProject> list = new ArrayList();
      if (!loginUser.getTsysUser().getId().equals("1")) {
         List<TCoreDataProject> list2 = this.tdataProjectService.selectMyDataProject(loginUser.getTsysUser().getId(), proName, note);
         UserVO uservo = this.userService.queryByUserid(loginUser.getTsysUser().getId());
         if (uservo != null) {
            List<TCoreDataProject> list3 = this.tdataProjectService.selectMyDataProject(uservo.getGroupid(), proName, note);
            Map<String, TCoreDataProject> allProject = new HashMap();

            for(TCoreDataProject userpro : list2) {
               allProject.put(userpro.getId(), userpro);
            }

            for(TCoreDataProject userpro : list3) {
               allProject.put(userpro.getId(), userpro);
            }

            for(Map.Entry<String, TCoreDataProject> a : allProject.entrySet()) {
               list.add(a.getValue());
            }
         }
      } else {
         list = this.tdataProjectService.selectDataProject(proName, note);
      }

      for(int i = 0; i < list.size(); ++i) {
         TCoreProjectDetailVO tCoreProjectDetailVO = new TCoreProjectDetailVO();
         String id = ((TCoreDataProject)list.get(i)).getId();
         String edition_id = ((TCoreDataProject)list.get(i)).getEdition_id();
         List<Map<String, Object>> sourceL = this.tdataProjectService.selectSource(id, "");
         List<Map<String, Object>> areaL = this.tdataProjectService.selectArea(id);
         List<Map<String, Object>> dataScopeL = this.tdataProjectService.selectDataScopeCount(id, edition_id);
         List<Map<String, Object>> sensitiveLevelL = this.tdataProjectService.selectSensitiveLevelCount(id, edition_id);
         List<Map<String, Object>> compliancedirL = this.tdataProjectService.selectComplianceDirCount1(edition_id);
         Map<String, Object> map = new HashMap();
         Map<String, Object> map1 = new HashMap();
         List<Map<String, Object>> maplist = new ArrayList();
         List<Map<String, Object>> maplist1 = new ArrayList();
         map.put("s", 0);
         maplist.add(map);
         map1.put("s", 1);
         maplist1.add(map1);
         sourceL.addAll(areaL);
         if (Integer.valueOf(((Map)dataScopeL.get(0)).get("s").toString()) == 0) {
            sourceL.addAll(maplist);
         } else {
            sourceL.addAll(maplist1);
         }

         if (Integer.valueOf(((Map)sensitiveLevelL.get(0)).get("s").toString()) == 0) {
            sourceL.addAll(maplist);
         } else {
            sourceL.addAll(maplist1);
         }

         if (Integer.valueOf(((Map)compliancedirL.get(0)).get("s").toString()) == 0) {
            sourceL.addAll(maplist);
         } else {
            sourceL.addAll(maplist1);
         }

         tCoreProjectDetailVO.setEdition_id(((TCoreDataProject)list.get(i)).getEdition_id());
         tCoreProjectDetailVO.setList(sourceL);
         tCoreProjectDetailVO.setCreateTime((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(((TCoreDataProject)list.get(i)).getCreatetime()));
         tCoreProjectDetailVO.setCreateuser(((TCoreDataProject)list.get(i)).getCreateuser());
         tCoreProjectDetailVO.setId(((TCoreDataProject)list.get(i)).getId());
         tCoreProjectDetailVO.setNote(((TCoreDataProject)list.get(i)).getNote());
         tCoreProjectDetailVO.setProject(((TCoreDataProject)list.get(i)).getProject());
         proList.add(tCoreProjectDetailVO);
      }

      return RespHelper.<List<TCoreProjectDetailVO>>successResp(proList);
   }
}
