package com.chenyang.nse.bussiness.controller;

import com.chenyang.nse.bussiness.annot.PassToken;
import com.chenyang.nse.bussiness.commmon.ApplicationConstants;
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.cache.LoginUser;
import com.chenyang.nse.bussiness.entity.orm.table.base.TBaseMenu;
import com.chenyang.nse.bussiness.entity.orm.table.base.TBaseResource;
import com.chenyang.nse.bussiness.entity.orm.table.base.TBaseRole;
import com.chenyang.nse.bussiness.entity.orm.table.base.TBaseUser;
import com.chenyang.nse.bussiness.entity.orm.table.console.TConsoleLog;
import com.chenyang.nse.bussiness.entity.orm.table.console.TConsolePrivilege;
import com.chenyang.nse.bussiness.entity.orm.table.console.TConsoleSystemSetting;
import com.chenyang.nse.bussiness.entity.vo.ResultVO;
import com.chenyang.nse.bussiness.enumeration.EroleFlag;
import com.chenyang.nse.bussiness.service.IndexService;
import com.chenyang.nse.bussiness.service.console.OperationService;
import com.chenyang.nse.bussiness.tools.encryption.SM3Utils;
import com.chenyang.nse.bussiness.tools.ha.HaInfo;
import com.chenyang.nse.bussiness.tools.licensekey.LicenseKeyTool;
import com.chenyang.nse.bussiness.tools.msg.MesUtil;
import com.chenyang.nse.bussiness.tools.object.JsonTool;
import com.chenyang.nse.bussiness.tools.string.PasswordEncryptTool;
import com.chenyang.nse.bussiness.tools.token.TokenUtil;
import com.ghca.sso.SSOClient;
import java.io.File;
import java.io.IOException;
import java.net.SocketException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class IndexController {
   private static Logger logger = LoggerFactory.getLogger(IndexController.class);
   @Autowired
   private IndexService indexService;
   @Autowired
   private OperationService operationService;

   @RequestMapping({"/"})
   public String index(HttpServletRequest request, HttpServletResponse response, Model model) {
      String webroot = request.getSession().getServletContext().getRealPath("/");
      ApplicationConstants.webRoot = webroot;
      Object obj = request.getSession().getAttribute("loginUser");
      if (obj == null) {
         if (null != HaInfo.primarySisInfo) {
            model.addAttribute("isPrimaryServer", HaInfo.isPrimaryServer);
            model.addAttribute("primaryIp", HaInfo.primarySisInfo.getIp());
            model.addAttribute("primaryTomcatPort", HaInfo.primarySisInfo.getPort());
            model.addAttribute("isExist", HaInfo.isExist);
         }

         return "login";
      } else {
         LoginUser loginUser = (LoginUser)obj;
         String flag = "1";
         if (EroleFlag.USER.getFlag().equals(flag)) {
            Boolean sysChpwdFlg = false;
            List<TConsoleSystemSetting> tcssLst = loginUser.getTcssLst();
            if (null != tcssLst && tcssLst.size() > 0) {
               for(TConsoleSystemSetting tcss : tcssLst) {
                  if (tcss.getId().equals("1") && "1".equals(tcss.getValue())) {
                     sysChpwdFlg = true;
                  }
               }
            }

            if (StringUtil.isBlank(loginUser.getTsysUser().getChpwdflg()) && sysChpwdFlg) {
               this.reflashMenu(loginUser);
               request.getSession().setAttribute("loginUser", loginUser);
               model.addAttribute("chpwdflg", "1");
            }
         }

         EroleFlag ef = EroleFlag.getEroleFlagByFlag("1");
         loginUser.setFlag(ef.getFlag());
         loginUser.setPrefix(ef.getCode());
         if (ef == EroleFlag.USER) {
            model.addAttribute("menus", loginUser.getMenus());
         }

         return loginUser.getPrefix() + "/index";
      }
   }

   public void reflashMenu(LoginUser loginUser) {
      String submenuname = "修改密码";
      List<TBaseMenu> mLst = loginUser.getMenus();
      TBaseMenu nMenu = null;

      for(int i = 0; i < mLst.size(); ++i) {
         TBaseMenu mInfo = (TBaseMenu)mLst.get(i);
         if (mInfo.getMenuname().equals("设置")) {
            nMenu = mInfo;
            break;
         }
      }

      TBaseMenu nSubMenu = null;
      if (null != nMenu) {
         for(int i = 0; i < nMenu.getSubmenu().size(); ++i) {
            TBaseMenu smInfo = (TBaseMenu)nMenu.getSubmenu().get(i);
            if (submenuname.equals(smInfo.getMenuname())) {
               nSubMenu = smInfo;
               break;
            }
         }
      }

      if (null != nSubMenu) {
         nMenu.getSubmenu().clear();
         nMenu.getSubmenu().add(nSubMenu);
         loginUser.getMenus().clear();
         loginUser.getMenus().add(nMenu);
      } else {
         TBaseMenu chpwdMenu = this.indexService.queryMenusBySubName(submenuname);
         if (null != chpwdMenu) {
            loginUser.getMenus().clear();
            loginUser.getMenus().add(chpwdMenu);
         }
      }

   }

   @RequestMapping({"/login"})
   public String login(TBaseUser tsysUser, HttpServletRequest request, HttpServletResponse response, Model model) {
      return "login";
   }

   @PassToken
   @PostMapping({"/doLogin"})
   @ResponseBody
   public Response<LoginUser> doLogin(@RequestBody TBaseUser user, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
      boolean result = Boolean.FALSE;
      Response resultContent = null;
      List<TBaseRole> trole = null;
      LoginUser loginUser = null;
      TBaseUser newuser = new TBaseUser();
      TBaseUser tBaseUser = null;
      Cookie[] cookies = request.getCookies();
      if (cookies != null) {
         String cardUserName = "";

         for(Cookie cookie : cookies) {
            if ("KOAL_CERT_CN".equalsIgnoreCase(cookie.getName())) {
               cardUserName = new String(URLDecoder.decode(cookie.getValue()).getBytes("ISO-8859-1"), "GBK");
               tBaseUser = this.indexService.querykeyByUsername(cardUserName);
               if (tBaseUser != null) {
                  newuser = this.indexService.login1(tBaseUser);
               } else {
                  newuser = null;
               }
               break;
            }
         }

         if ("".equals(cardUserName)) {
            tBaseUser = this.indexService.querykeyByUsername(user.getUsername());
            newuser = this.indexService.login1(user);
            List var38 = this.operationService.query("", "", "");
         }
      } else {
         tBaseUser = this.indexService.querykeyByUsername(user.getUsername());
         newuser = this.indexService.login1(user);
         List var34 = this.operationService.query("", "", "");
      }

      if (null != newuser) {
         boolean resultVOBool = true;
         Response resultVOResponse = null;

         try {
            ResultVO resultVO = LicenseKeyTool.verifyproperties(tBaseUser);
            resultVOBool = resultVO.getResult();
            resultVOResponse = resultVO.getResponse();
         } catch (Exception var26) {
            resultVOBool = false;
            resultVOResponse = RespHelper.createResp(false, "LGS_ERR_005", MesUtil.getMsg("LGS_ERR_005", new String[0]));
         }

         if (!newuser.getId().equals("1") && !resultVOBool) {
            resultContent = resultVOResponse;
         } else if (newuser.getIsenable() == 0) {
            resultContent = RespHelper.createResp(false, "LGS_ERR_005", MesUtil.getMsg("LGS_ERR_005", new String[0]));
         } else if (newuser.getLimitnum() != null) {
            int limitNum = Integer.parseInt(newuser.getLimitnum());
            if (!newuser.getId().equals("1") && 0 == limitNum) {
               resultContent = RespHelper.createResp(false, "LGS_ERR_006", MesUtil.getMsg("LGS_ERR_006", new String[0]));
            } else if (!newuser.getPassword().toUpperCase().equals(user.getPassword().toUpperCase())) {
               if (!newuser.getId().equals("1")) {
                  resultContent = RespHelper.createResp(false, "LGS_ERR_007", MesUtil.getMsg("LGS_ERR_007", new String[]{newuser.getLimitnum()}));
                  newuser.setLimitnum(limitNum - 1 + "");
               } else {
                  resultContent = RespHelper.createResp(false, "LGS_ERR_008", MesUtil.getMsg("LGS_ERR_008", new String[0]));
               }

               this.indexService.saveOrUpdate(newuser);
            } else {
               try {
                  new Properties();
                  Properties var45 = PropertiesLoaderUtils.loadAllProperties("config.properties");
                  String limitnum = var45.get("login_limit_num").toString();
                  result = Boolean.TRUE;
                  newuser.setLimitnum(limitnum);
                  this.indexService.saveOrUpdate(newuser);
                  String userId = newuser.getId();
                  loginUser = new LoginUser();
                  loginUser.setLicenseRst(true);
                  loginUser.setTsysUser(newuser);
                  trole = this.indexService.queryRoleByUserId(userId);
                  loginUser.setTrole(trole);
                  if (trole.size() == 0) {
                     if (!newuser.getId().equals("1")) {
                        List<TBaseMenu> menus = this.indexService.queryMenusByUserId(userId);
                        loginUser.setMenus(menus);
                     }
                  } else if (!newuser.getId().equals("1")) {
                     List<TBaseMenu> menus = this.indexService.queryMenusByUserId(userId);
                     loginUser.setMenus(menus);
                     List<TBaseResource> resourcesList = this.indexService.queryResourcesListByRoleId(trole);
                     Map<String, TBaseResource> urlMap = new HashMap();
                     if (!ObjectUtils.isEmpty(resourcesList)) {
                        for(TBaseResource tresources : resourcesList) {
                           urlMap.put(tresources.getUrl(), tresources);
                        }
                     }

                     loginUser.setUrlMap(urlMap);
                     List<TConsolePrivilege> privilegeList = this.indexService.queryPrivilegeByRoleId(trole);
                     List<String> privileges = new ArrayList();
                     if (privilegeList != null) {
                        for(TConsolePrivilege privilege : privilegeList) {
                           privileges.add(privilege.getPrivilege());
                        }
                     }

                     loginUser.setPrivileges(privileges);
                  } else {
                     List<TBaseMenu> menus = null;
                     if (!resultVOBool) {
                        menus = this.indexService.queryMenusByType("3");
                        loginUser.setLicenseRst(false);
                     } else {
                        menus = this.indexService.qeuryMenus();
                     }

                     loginUser.setMenus(menus);
                     List<TBaseResource> resourcesList = this.indexService.queryResourcesListByRoleId(trole);
                     Map<String, TBaseResource> urlMap = new HashMap();

                     for(TBaseResource tresources : resourcesList) {
                        urlMap.put(tresources.getUrl(), tresources);
                     }

                     loginUser.setUrlMap(urlMap);
                     List<TConsolePrivilege> privilegeList = this.indexService.queryPrivilegeByRoleId(trole);
                     List<String> privileges = new ArrayList();
                     if (privilegeList != null) {
                        for(TConsolePrivilege privilege : privilegeList) {
                           privileges.add(privilege.getPrivilege());
                        }
                     }

                     loginUser.setPrivileges(privileges);
                  }

                  List<TConsoleSystemSetting> tcssLst = this.indexService.querySystemSettings();
                  loginUser.setTcssLst(tcssLst);
               } catch (IOException e) {
                  e.printStackTrace();
               }

               Properties loadAllProperties = PropertiesLoaderUtils.loadAllProperties("config.properties");
               String passwordSwith = (String)loadAllProperties.get("passwordSwith");
               if ("1".equals(passwordSwith) && !newuser.getId().equals("1")) {
                  Calendar c = Calendar.getInstance();
                  int nowdayOfYear = c.get(6);
                  int nowdayOfMonth = c.get(5);
                  int nowmonth = c.get(2) + 1;
                  if (null == tBaseUser.getEditpasswordtime()) {
                     tBaseUser.setEditpasswordtime(new Date());
                  } else {
                     Calendar c1 = Calendar.getInstance();
                     c1.setTime(tBaseUser.getEditpasswordtime());
                     int olddayOfYear = c1.get(6);
                     int olddayOfMonth = c1.get(5);
                     int oldmonth = c1.get(2) + 1;
                     if (c.getWeekYear() - c1.getWeekYear() == 1 && 12 - oldmonth + nowmonth == 3 && nowdayOfMonth - olddayOfMonth >= 0) {
                        resultContent = RespHelper.createResp(false, "LGS_ERR_009", MesUtil.getMsg("LGS_ERR_009", new String[0]));
                        result = Boolean.FALSE;
                     } else if (c.getWeekYear() - c1.getWeekYear() == 1 && 12 - oldmonth + nowmonth > 3) {
                        resultContent = RespHelper.createResp(false, "LGS_ERR_009", MesUtil.getMsg("LGS_ERR_009", new String[0]));
                        result = Boolean.FALSE;
                     } else if (c.getWeekYear() - c1.getWeekYear() > 1) {
                        resultContent = RespHelper.createResp(false, "LGS_ERR_009", MesUtil.getMsg("LGS_ERR_009", new String[0]));
                        result = Boolean.FALSE;
                     } else if (c.getWeekYear() == c1.getWeekYear() && Math.abs(nowdayOfYear - olddayOfYear) > 90) {
                        resultContent = RespHelper.createResp(false, "LGS_ERR_009", MesUtil.getMsg("LGS_ERR_009", new String[0]));
                        result = Boolean.FALSE;
                     }
                  }
               }
            }
         } else {
            resultContent = RespHelper.createResp(false, "LGS_ERR_010", MesUtil.getMsg("LGS_ERR_010", new String[0]));
         }
      } else {
         resultContent = RespHelper.createResp(false, "LGS_ERR_011", MesUtil.getMsg("LGS_ERR_011", new String[0]));
      }

      request.getSession().setAttribute("loginUser", loginUser);
      TConsoleLog record = new TConsoleLog();
      record.setOperationObject("DDM_00000");
      record.setLogmessage("用户登录");
      record.setModule("系统模块");
      record.setOperationtime(new Date());
      if (loginUser != null) {
         record.setUser(loginUser.getTsysUser().getUsername());
         String token = TokenUtil.getToken(user.getUsername(), user.getPassword());
         loginUser.setToken(token);
         resultContent = RespHelper.successResp(loginUser);
         String column_enc = "";
         Date date = record.getOperationtime();
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         String dateString = sdf.format(date);

         try {
            column_enc = SM3Utils.encrypt(record.getOperationUser() + dateString + record.getLogmessage());
         } catch (Exception exception) {
            exception.printStackTrace();
         }

         record.setColumn_enc(column_enc);
      }

      this.operationService.add(record);
      return resultContent;
   }

   @RequestMapping({"/logout"})
   public Response logout(HttpServletRequest request, HttpServletResponse response, Model model) {
      Map map = new HashMap();
      TConsoleLog record = new TConsoleLog();
      String username = TokenUtil.getUserId(request.getHeader("token"));
      record.setLogmessage("用户退出");
      record.setModule("系统模块");
      record.setOperationObject("DDM_00000");
      record.setOperationtime(new Date());
      record.setUser(username);
      String column_enc = "";
      Date date = record.getOperationtime();
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      String dateString = sdf.format(date);

      try {
         column_enc = SM3Utils.encrypt(record.getOperationUser() + dateString + record.getLogmessage());
      } catch (Exception exception) {
         exception.printStackTrace();
      }

      record.setColumn_enc(column_enc);
      this.operationService.add(record);
      request.getSession().removeAttribute("loginUser");
      request.getSession().removeAttribute("datasystemtree");
      Cookie userCookie = new Cookie("user-cookie-sso", "");
      userCookie.setDomain("sso.ghca.com");
      userCookie.setMaxAge(0);
      response.addCookie(userCookie);
      Cookie ticketCookie = new Cookie("ticket-cookie-sso", "");
      ticketCookie.setDomain("sso.ghca.com");
      ticketCookie.setMaxAge(0);
      response.addCookie(ticketCookie);
      Cookie companyCookie = new Cookie("companykey-cookie-sso", "");
      companyCookie.setDomain("sso.ghca.com");
      companyCookie.setMaxAge(0);
      response.addCookie(companyCookie);
      SSOClient.logout(username, "127.0.0.1");
      map.put("flag", true);
      return RespHelper.successResp(map);
   }

   @RequestMapping({"/top"})
   public String top(HttpServletRequest request, HttpServletResponse response, Model model) {
      return "top";
   }

   @RequestMapping({"/bottom"})
   public String bottom(HttpServletRequest request, HttpServletResponse response, Model model) {
      return "bottom";
   }

   @RequestMapping({"/initMenu"})
   public String initMenu(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
      LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
      String menu_json = JsonTool.toJsonString(loginUser.getMenus());
      if (menu_json == null) {
         return null;
      } else {
         model.addAttribute("menu", menu_json);
         return "menu";
      }
   }

   @RequestMapping({"/checkpwd"})
   @ResponseBody
   public Map<String, Object> checkpwd(String pwd, HttpServletRequest request, HttpServletResponse response, Model model) {
      String p = PasswordEncryptTool.generatePassword(pwd);
      LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
      String realpwd = loginUser.getTsysUser().getPassword();
      boolean result = p.equals(realpwd);
      Map<String, Object> map = new HashMap();
      map.put("result", result);
      return map;
   }

   @RequestMapping({"/updatepwd"})
   public void updatepwd(String pwd, HttpServletRequest request, HttpServletResponse response, Model model) {
      String p = PasswordEncryptTool.generatePassword(pwd);
      LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
      TBaseUser user = loginUser.getTsysUser();
      user.setPassword(p);
      user.setChpwdflg(p);
      this.indexService.saveOrUpdate(user);
   }

   @PostMapping({"/uploadlic"})
   @ResponseBody
   public Response handleFileUpload(@RequestParam("file") MultipartFile file) {
      if (file.isEmpty()) {
         return RespHelper.createResp(false, "FIS_001", MesUtil.getMsg("FIS_001", new String[0]));
      } else {
         String fileName = file.getOriginalFilename();
         System.out.println("上传的文件名为：" + fileName);
         String suffixName = fileName.substring(fileName.lastIndexOf("."));
         if (!".dat".equals(suffixName)) {
            return RespHelper.createResp(false, "FIS_002", MesUtil.getMsg("FIS_002", new String[0]));
         } else {
            System.out.println("上传的后缀名为：" + suffixName);
            Properties props = new Properties();

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

            String url = props.getProperty("licensedir");
            File dest = new File(url + "/gtconfig.dat");
            if (!dest.getParentFile().exists()) {
               dest.getParentFile().mkdirs();
            }

            try {
               file.transferTo(dest);
               return RespHelper.successResp();
            } catch (IllegalStateException var8) {
               return RespHelper.createResp(false, "FIS_003", MesUtil.getMsg("FIS_003", new String[0]));
            } catch (IOException var9) {
               return RespHelper.createResp(false, "FIS_003", MesUtil.getMsg("FIS_003", new String[0]));
            }
         }
      }
   }

   @GetMapping({"/getlicinfo"})
   @ResponseBody
   public Response getLicInfo() {
      Map map = LicenseKeyTool.map;

      try {
         LicenseKeyTool.verifyproperties((TBaseUser)null);
      } catch (Exception e) {
         e.printStackTrace();
         map.put("flag", "0");
         map.put("status", "2");
         map.put("msg", MesUtil.getMsg("LGS_ERR_004", new String[0]));
      }

      if (!map.containsKey("flag")) {
         map.put("flag", "1");
         map.put("msg", MesUtil.getMsg("LGS_001", new String[0]));
      }

      if (!map.containsKey("status")) {
         map.put("status", "3");
      }

      new ArrayList();
      List<Map<String, String>> list = new ArrayList();
      List<String> ipList = LicenseKeyTool.getLinuxLocalUUID();

      for(int i = 0; i < ipList.size(); ++i) {
         Map<String, String> x = new HashMap();
         String ip = (String)ipList.get(i);
         String mac = null;

         try {
            mac = LicenseKeyTool.getLocalMacLiunx();
         } catch (SocketException e) {
            throw new RuntimeException(e);
         }

         x.put("ip", ip);
         x.put("mac", mac);
         list.add(x);
      }

      map.put("ipMacList", list);
      return RespHelper.successResp(map);
   }

   @GetMapping({"/getlicuuid"})
   @ResponseBody
   public Response getlicuuid() throws SocketException {
      Map map = LicenseKeyTool.map;

      try {
         LicenseKeyTool.verifyproperties((TBaseUser)null);
      } catch (Exception e) {
         e.printStackTrace();
         map.put("flag", "0");
         map.put("status", "2");
         map.put("msg", MesUtil.getMsg("LGS_ERR_004", new String[0]));
      }

      if (!map.containsKey("flag")) {
         map.put("flag", "1");
         map.put("msg", MesUtil.getMsg("LGS_001", new String[0]));
      }

      if (!map.containsKey("status")) {
         map.put("status", "3");
      }

      map.put("uuidList", LicenseKeyTool.getLinuxLocalUUID());
      return RespHelper.successResp(map);
   }
}
