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

import com.chenyang.nse.bussiness.annot.PassToken;
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.PageInfo;
import com.chenyang.nse.bussiness.entity.cache.LoginUser;
import com.chenyang.nse.bussiness.entity.orm.table.base.TBaseButton;
import com.chenyang.nse.bussiness.entity.orm.table.base.TBaseGroup;
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.base.TBaseUsergroup;
import com.chenyang.nse.bussiness.entity.orm.table.base.TBaseUserproject;
import com.chenyang.nse.bussiness.entity.orm.table.base.TBaseUserrole;
import com.chenyang.nse.bussiness.entity.orm.table.base.TBaseUsersys;
import com.chenyang.nse.bussiness.entity.orm.table.console.TConsoleLog;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.entity.vo.AppUserVO;
import com.chenyang.nse.bussiness.entity.vo.DataProjectVO;
import com.chenyang.nse.bussiness.entity.vo.DataSystemVO;
import com.chenyang.nse.bussiness.entity.vo.DutyPersonVO;
import com.chenyang.nse.bussiness.entity.vo.ResultVO;
import com.chenyang.nse.bussiness.entity.vo.TUserProjReqVO;
import com.chenyang.nse.bussiness.entity.vo.UserVO;
import com.chenyang.nse.bussiness.service.IndexService;
import com.chenyang.nse.bussiness.service.console.ButtonService;
import com.chenyang.nse.bussiness.service.console.OperationService;
import com.chenyang.nse.bussiness.service.console.RoleService;
import com.chenyang.nse.bussiness.service.console.UserGroupService;
import com.chenyang.nse.bussiness.service.console.UserService;
import com.chenyang.nse.bussiness.service.core.DataSystemService;
import com.chenyang.nse.bussiness.service.core.TdataProjectService;
import com.chenyang.nse.bussiness.service.core.encryption.EncryptionProxyService;
import com.chenyang.nse.bussiness.sso.SSOUserManager;
import com.chenyang.nse.bussiness.tools.login.CommonUtils;
import com.chenyang.nse.bussiness.tools.msg.MesUtil;
import com.chenyang.nse.bussiness.tools.string.PasswordEncryptTool;
import com.chenyang.nse.bussiness.tools.string.StringTool;
import java.io.IOException;
import java.text.ParseException;
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.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"/console/user"})
public class UserController {
   @Autowired
   EncryptionProxyService proxyService;
   @Autowired
   private UserService userService;
   @Autowired
   private RoleService roleService;
   @Autowired
   private UserGroupService userGroupService;
   @Autowired
   private OperationService operationService;
   @Autowired
   private DataSystemService dataSystemService;
   @Autowired
   private TdataProjectService tdataProjectService;
   @Autowired
   private IndexService indexService;
   @Autowired
   SSOUserManager ssoUserManager;
   @Autowired
   private ButtonService buttonService;
   private static final Logger ddmauditLogger = LoggerFactory.getLogger("ddmauditLogger");
   private static final Logger operationLogger = LoggerFactory.getLogger("operationLogger");

   @RequestMapping({"/initEdit"})
   @ResponseBody
   public Response<UserVO> initUser(@RequestParam Map<String, String> params) {
      String userId = String.valueOf(params.get("userId"));
      ddmauditLogger.info(MesUtil.getMsg("DDM_00104", new String[]{CommonUtils.loginUsername(), this.userService.queryByUserid(userId).getUsername()}));
      if (userId != null && userId.toString().length() != 0) {
         UserVO userVO = this.userService.initUser(userId);
         return RespHelper.<UserVO>successResp(userVO);
      } else {
         return RespHelper.<UserVO>paramErrResp();
      }
   }

   @PostMapping({"/add"})
   @ResponseBody
   public Response<UserVO> addUser(@RequestBody UserVO userVO, HttpServletRequest request) {
      if (StringUtils.isBlank(userVO.getId()) && !ObjectUtils.isEmpty(this.userService.queryByusername(userVO.getUsername()))) {
         return RespHelper.<UserVO>createResp(false, "POP_00010", MesUtil.getMsg("POP_00010", new String[0]));
      } else {
         if (StringUtils.isBlank(userVO.getId())) {
            ddmauditLogger.info(MesUtil.getMsg("DDM_00106", new String[]{CommonUtils.loginUsername(), userVO.getUsername()}));
         } else {
            ddmauditLogger.info(MesUtil.getMsg("DDM_00105", new String[]{CommonUtils.loginUsername(), userVO.getUsername()}));
         }

         this.userService.addUser(userVO, request);
         (new Thread(() -> this.proxyService.sendGatewatUserOriginalToTargetProxy((String)null, "push"))).start();
         return RespHelper.<UserVO>successResp(userVO);
      }
   }

   @PostMapping({"/addAppUser"})
   @ResponseBody
   public Response<AppUserVO> addAppUser(@RequestBody AppUserVO appUserVO, HttpServletRequest request) {
      if (StringUtils.isBlank(appUserVO.getId()) && !ObjectUtils.isEmpty(this.userService.queryByappusername(appUserVO.getUsername()))) {
         return RespHelper.<AppUserVO>createResp(false, "POP_000100", MesUtil.getMsg("POP_000100", new String[0]));
      } else if (StringUtils.isBlank(appUserVO.getId()) && !ObjectUtils.isEmpty(this.userService.queryByuseridentifier(appUserVO.getUseridentifier()))) {
         return RespHelper.<AppUserVO>createResp(false, "POP_000101", MesUtil.getMsg("POP_000101", new String[0]));
      } else {
         if (StringUtils.isBlank(appUserVO.getId())) {
            ddmauditLogger.info(MesUtil.getMsg("DDM_001066", new String[]{CommonUtils.loginUsername(), appUserVO.getUsername()}));
         } else {
            ddmauditLogger.info(MesUtil.getMsg("DDM_001055", new String[]{CommonUtils.loginUsername(), appUserVO.getUsername()}));
         }

         this.userService.addAppUser(appUserVO, request);
         this.proxyService.sendAppUserOriginalToTargetProxy((String)null, "push");
         return RespHelper.<AppUserVO>successResp(appUserVO);
      }
   }

   @PostMapping({"/delAppUser"})
   @ResponseBody
   public Response removeAppUser(@RequestBody Map<String, Object> params, HttpServletRequest request, HttpServletResponse response, Model model) {
      String id = (String)params.get("id");
      ddmauditLogger.info(MesUtil.getMsg("DDM_001077", new String[]{CommonUtils.loginUsername(), this.userService.queryByAppUserid(id).getUsername()}));
      this.userService.removeAppUser(id);
      return RespHelper.successResp();
   }

   @PostMapping({"/del"})
   @ResponseBody
   public Response remove(@RequestBody Map<String, Object> params, HttpServletRequest request, HttpServletResponse response, Model model) {
      String id = (String)params.get("id");
      ddmauditLogger.info(MesUtil.getMsg("DDM_00107", new String[]{CommonUtils.loginUsername(), this.userService.queryByUserid(id).getUsername()}));
      this.userService.remove(id);
      this.userService.deleteUserMenuByUserid(id);
      this.userService.deleteUserRoleByUserid(id);
      this.userService.deleteUserGroupByUserid(id);
      return RespHelper.successResp();
   }

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

   @RequestMapping({"/queryAll"})
   @ResponseBody
   public Response<List<TBaseUser>> queryAll() {
      return RespHelper.<List<TBaseUser>>successResp(this.userService.queryAll());
   }

   @RequestMapping({"/query"})
   @ResponseBody
   public Response query(@RequestParam Map<String, String> params, Integer pageno, Integer pagesize, PageInfo pageInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
      pageInfo.setPageno(pageno);
      pageInfo.setPagesize(pagesize);
      List<UserVO> list = this.userService.queryuservo(pageInfo, params);
      ddmauditLogger.info(MesUtil.getMsg("DDM_00103", new String[]{CommonUtils.loginUsername()}));
      return RespHelper.updateResp(pageInfo, list);
   }

   @RequestMapping({"/queryAppuser"})
   @ResponseBody
   public Response queryAppuser(@RequestParam Map<String, String> params, Integer pageno, Integer pagesize, PageInfo pageInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
      pageInfo.setPageno(pageno);
      pageInfo.setPagesize(pagesize);
      List<AppUserVO> list = this.userService.queryappuservo(pageInfo, params);
      ddmauditLogger.info(MesUtil.getMsg("DDM_001033", new String[]{CommonUtils.loginUsername()}));
      return RespHelper.updateResp(pageInfo, list);
   }

   @RequestMapping({"/queryNoProjectCrudUser"})
   @ResponseBody
   public Response<List<UserVO>> queryNoProjectCrudUser(@RequestBody TBaseUserproject vo) {
      List<UserVO> list = this.userService.queryNoProjectCrudUser(vo.getProid());
      Collections.sort(list, new Comparator<UserVO>() {
         public int compare(UserVO o1, UserVO o2) {
            return o1.getUsername().compareTo(o2.getUsername());
         }
      });
      return RespHelper.<List<UserVO>>successResp(list);
   }

   @RequestMapping({"/queryProjectCrudUser"})
   @ResponseBody
   public Response<List<UserVO>> queryProjectCrudUser(@RequestBody TBaseUserproject vo) {
      List<UserVO> list1 = this.userService.queryProjectCrudUser(vo.getProid());
      Collections.sort(list1, new Comparator<UserVO>() {
         public int compare(UserVO o1, UserVO o2) {
            return o1.getUsername().compareTo(o2.getUsername());
         }
      });
      return RespHelper.<List<UserVO>>successResp(list1);
   }

   @RequestMapping({"/addProjectCrudUser"})
   @ResponseBody
   public Response<TBaseUserproject> addProjectCrudUser(@RequestBody TBaseUserproject vo) {
      this.userService.addProjectCrudUser(vo);
      return RespHelper.<TBaseUserproject>successResp();
   }

   @RequestMapping({"/delProjectCrudUser"})
   @ResponseBody
   public Response<String> delProjectCrudUserById(@RequestBody Map<String, String> param) {
      String id = (String)param.get("tid");
      this.userService.delProjectCrudUserById(id);
      return RespHelper.<String>successResp();
   }

   @RequestMapping({"/remove"})
   @ResponseBody
   public void remove(@RequestParam("idlist[]") List<String> idlist, HttpServletRequest request, HttpServletResponse response, Model model) {
      this.userService.remove(idlist);

      for(String id : idlist) {
         this.userService.deleteUserRoleByUserId(id);
      }

      for(String id : idlist) {
         this.userGroupService.removeUserGroupByUserId(id);
      }

      for(String id : idlist) {
         this.userService.removeUsersysByUserId(id);
      }

      TConsoleLog record = new TConsoleLog();
      LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
      String username = loginUser.getTsysUser().getUsername();
      record.setModule("用户管理");
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      String stringdate = sdf.format(new Date());
      Date newdate = null;

      try {
         newdate = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).parse(stringdate);
      } catch (ParseException e) {
         e.printStackTrace();
      }

      record.setOperationtime(newdate);
      record.setUser(username);
      record.setLogmessage("删除用户");
      this.operationService.add(record);
   }

   @RequestMapping({"/checkNameExit"})
   @ResponseBody
   public ResultVO checkNameExit(String username, HttpServletRequest request, HttpServletResponse response, Model model) {
      boolean result = this.userService.checkNameExit(username);
      ResultVO vo = new ResultVO((String)null, result);
      return vo;
   }

   @RequestMapping({"/editcheckNameExit"})
   @ResponseBody
   public ResultVO editcheckNameExit(String username, String oldname, HttpServletRequest request, HttpServletResponse response, Model model) {
      ResultVO vo;
      if (username.equals(oldname)) {
         vo = new ResultVO((String)null, false);
      } else {
         boolean result = this.userService.checkNameExit(username);
         vo = new ResultVO((String)null, result);
      }

      return vo;
   }

   @RequestMapping({"/add"})
   public void add(String username, String password, String roleid, String groupid, String syslist, String flag, int isenable, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
      try {
         TBaseUser user = new TBaseUser();
         user.setUsername(username);
         user.setIsenable(isenable);
         user.setPassword(password);
         user.setEditpasswordtime(new Date());
         user.setFlag(flag);
         user.setCreatetime(new Date());
         new Properties();
         Properties props = PropertiesLoaderUtils.loadAllProperties("config.properties");
         String limitnum = props.get("login_limit_num").toString();
         user.setLimitnum(limitnum);
         this.userService.save(user);
         if (roleid != null && roleid != "") {
            TBaseUserrole userRole = new TBaseUserrole();
            userRole.setUserid(user.getId());
            userRole.setRoleid(roleid);
            this.userService.saveUserRole(userRole);
         }

         if (StringUtils.isNotBlank(syslist)) {
            String[] sysIdLst = syslist.split(",");

            for(int i = 0; i < sysIdLst.length; ++i) {
               TBaseUsersys userSys = new TBaseUsersys();
               userSys.setUserid(user.getId());
               userSys.setSysid(sysIdLst[i]);
               this.userService.saveUserSys(userSys);
            }
         }

         TConsoleLog record = new TConsoleLog();
         LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
         String loginusername = loginUser.getTsysUser().getUsername();
         record.setModule("用户管理");
         record.setOperationtime(new Date());
         record.setOperationObject(username);
         record.setUser(loginusername);
         record.setLogmessage("新增用户");
         this.operationService.add(record);
         if (groupid != null && groupid != "") {
            TBaseUsergroup userGroup = new TBaseUsergroup();
            TBaseGroup group = new TBaseGroup();
            group.setCreatetime(new Date());
            userGroup.setUserid(user.getId());
            TBaseGroup tBaseGroup = this.userGroupService.queryGroupByid(groupid);
            if (null == tBaseGroup) {
               String id = StringTool.getTablePrimaryKey();
               userGroup.setGroupid(id);
               group.setId(id);
               group.setGroupname(groupid);
               this.userGroupService.saveUserGroup(userGroup);
               this.userGroupService.saveGroup(group);
            } else {
               userGroup.setGroupid(groupid);
               this.userGroupService.saveUserGroup(userGroup);
            }
         } else {
            this.userGroupService.queryGroupByFlag("1");
         }
      } catch (IOException e) {
         e.printStackTrace();
      }

   }

   @RequestMapping({"/modify"})
   public void modify(String roleid, String groupid, String oldpwd, String editPasswordTime, String flag, int isenable, TBaseUser user, String oldcreatetime, String edit_syslist, HttpServletRequest request, HttpServletResponse response, Model model) {
      System.out.println(oldpwd.equals(user.getPassword()));
      user.setFlag(flag);
      user.setIsenable(isenable);
      SimpleDateFormat sdfcreate = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
      SimpleDateFormat sdf = null;

      try {
         user.setCreatetime(sdfcreate.parse(oldcreatetime));
      } catch (ParseException e1) {
         e1.printStackTrace();
      }

      if (!oldpwd.equals(user.getPassword())) {
         user.setPassword(PasswordEncryptTool.generatePassword(user.getPassword()));
         if (!oldpwd.equals(user.getPassword())) {
            user.setEditpasswordtime(new Date());
         } else {
            sdf = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");

            try {
               if (!"".equals(editPasswordTime) && null != editPasswordTime) {
                  user.setEditpasswordtime(sdf.parse(editPasswordTime));
               } else {
                  user.setEditpasswordtime(new Date());
               }
            } catch (ParseException e) {
               e.printStackTrace();
            }
         }
      } else {
         try {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            user.setEditpasswordtime(sdf.parse(editPasswordTime));
         } catch (ParseException e) {
            e.printStackTrace();
         }
      }

      try {
         new Properties();
         Properties record = PropertiesLoaderUtils.loadAllProperties("config.properties");
         String limitnum = record.get("login_limit_num").toString();
         user.setLimitnum(limitnum);
      } catch (IOException e) {
         e.printStackTrace();
      }

      this.userService.save(user);
      this.userService.deleteUserRoleByUserId(user.getId());
      if (roleid != null && roleid != "") {
         TBaseUserrole userRole = new TBaseUserrole();
         userRole.setUserid(user.getId());
         userRole.setRoleid(roleid);
         this.userService.saveUserRole(userRole);
      }

      this.userService.deleteUserSysByUserId(user.getId());
      if (StringUtils.isNotBlank(edit_syslist)) {
         String[] sysIdLst = edit_syslist.split(",");

         for(int i = 0; i < sysIdLst.length; ++i) {
            TBaseUsersys userSys = new TBaseUsersys();
            userSys.setUserid(user.getId());
            userSys.setSysid(sysIdLst[i]);
            this.userService.saveUserSys(userSys);
         }
      }

      TConsoleLog record = new TConsoleLog();
      LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
      String loginusername = loginUser.getTsysUser().getUsername();
      record.setModule("用户管理");
      record.setOperationtime(new Date());
      record.setUser(loginusername);
      record.setOperationObject(user.getUsername());
      record.setLogmessage("修改用户");
      record.setModifieduser(user.getUsername());
      this.operationService.add(record);
      this.userGroupService.removeUserGroupByUserId(user.getId());
      if (groupid != null && groupid != "") {
         TBaseUsergroup userGroup = new TBaseUsergroup();
         TBaseGroup group = new TBaseGroup();
         group.setCreatetime(new Date());
         userGroup.setUserid(user.getId());
         TBaseGroup tBaseGroup = this.userGroupService.queryGroupByid(groupid);
         if (null == tBaseGroup) {
            String id = StringTool.getTablePrimaryKey();
            userGroup.setGroupid(id);
            group.setId(id);
            group.setGroupname(groupid);
            this.userGroupService.saveUserGroup(userGroup);
            this.userGroupService.saveGroup(group);
         } else {
            userGroup.setGroupid(groupid);
            this.userGroupService.saveUserGroup(userGroup);
         }
      }

   }

   @RequestMapping({"/queryuserrolebyuserid"})
   @ResponseBody
   public TBaseUserrole queryuserrolebyuserid(String userid, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<TBaseUserrole> list = this.userService.queryuserrolebyuserid(userid);
      TBaseUserrole userRole = null;
      if (list != null && list.size() > 0) {
         userRole = (TBaseUserrole)list.get(0);
      }

      return userRole;
   }

   @RequestMapping({"/queryallroles"})
   @ResponseBody
   public List<TBaseRole> queryallroles(String flag, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<TBaseRole> list = this.roleService.queryRoleByFlag(flag);
      return list;
   }

   @RequestMapping({"/queryallgroups"})
   @ResponseBody
   public List<TBaseGroup> queryallgroups(HttpServletRequest request, HttpServletResponse response, Model model) {
      List<TBaseGroup> list = this.userGroupService.queryallgroups();
      return list;
   }

   @RequestMapping({"/querydatasystem"})
   @ResponseBody
   public List<TCoreDatasystem> querydatasource(HttpServletRequest request, HttpServletResponse response, Model model) {
      List<TCoreDatasystem> allDataSystem = this.dataSystemService.querydataAllsource();
      return allDataSystem;
   }

   @RequestMapping({"/queryDatasystemCrudByUserid"})
   @ResponseBody
   public List<DataSystemVO> queryDatasystemCrudByUserid(String userid, HttpServletRequest request, HttpServletResponse response, Model model) {
      UserVO user = this.userService.queryByUserid(userid);
      List<String> useridlist = new ArrayList();
      if (user != null) {
         useridlist.add(user.getGroupid());
      }

      useridlist.add(userid);
      List<DataSystemVO> allDataSystem = this.dataSystemService.queryDatasystemCrudByUserid(useridlist);
      Map<String, DataSystemVO> dataStstemMap = new HashMap();

      for(DataSystemVO dataSystemVO : allDataSystem) {
         DataSystemVO olddataSystemVO = (DataSystemVO)dataStstemMap.get(dataSystemVO.getId());
         if (olddataSystemVO != null) {
            String oldcrud = olddataSystemVO.getCrud();
            String newcrud = dataSystemVO.getCrud();
            if (oldcrud != null && !oldcrud.equals("") && newcrud != null && !newcrud.equals("") && Integer.parseInt(oldcrud) < Integer.parseInt(newcrud)) {
               dataStstemMap.put(dataSystemVO.getId(), dataSystemVO);
            }
         } else {
            dataStstemMap.put(dataSystemVO.getId(), dataSystemVO);
         }
      }

      List<DataSystemVO> dscl = new ArrayList();

      for(Map.Entry<String, DataSystemVO> a : dataStstemMap.entrySet()) {
         dscl.add(a.getValue());
      }

      return dscl;
   }

   @RequestMapping({"/queryDataprojectCrudByUserid"})
   @ResponseBody
   public List<DataProjectVO> queryDataprojectCrudByUserid(String userid, HttpServletRequest request, HttpServletResponse response, Model model) {
      UserVO user = this.userService.queryByUserid(userid);
      List<String> useridlist = new ArrayList();
      if (user != null) {
         useridlist.add(user.getGroupid());
      }

      useridlist.add(userid);
      List<DataProjectVO> allDataProject = this.tdataProjectService.queryDataprojectCrudByUserid(useridlist);
      Map<String, DataProjectVO> dataProjectMap = new LinkedHashMap();

      for(DataProjectVO dataProjectVO : allDataProject) {
         DataProjectVO olddataProjectVO = (DataProjectVO)dataProjectMap.get(dataProjectVO.getId());
         if (olddataProjectVO != null) {
            String oldcrud = olddataProjectVO.getCrud();
            String newcrud = dataProjectVO.getCrud();
            if (oldcrud != null && !oldcrud.equals("") && newcrud != null && !newcrud.equals("") && Integer.parseInt(oldcrud) < Integer.parseInt(newcrud)) {
               dataProjectMap.put(dataProjectVO.getId(), dataProjectVO);
            }
         } else {
            dataProjectMap.put(dataProjectVO.getId(), dataProjectVO);
         }
      }

      List<DataProjectVO> dpcl = new ArrayList();

      for(Map.Entry<String, DataProjectVO> a : dataProjectMap.entrySet()) {
         dpcl.add(a.getValue());
      }

      return dpcl;
   }

   @ResponseBody
   @RequestMapping({"/queryUserSys"})
   public List<TBaseUsersys> queryUserSys(String userid, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<TBaseUsersys> list = this.userService.queryusersysbyuserid(userid);
      return list;
   }

   @RequestMapping(
      value = {"/updateuserisenable"},
      method = {RequestMethod.POST}
   )
   @ResponseBody
   public void updateuserisenable(String userid, Integer isenable, HttpServletRequest request, HttpServletResponse response, Model model) {
      this.userService.updateUser(userid, isenable);
      new TConsoleLog();
      LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
   }

   @ResponseBody
   @RequestMapping({"/queryUserById"})
   public UserVO queryUserById(String userid, HttpServletRequest request, HttpServletResponse response, Model model) {
      UserVO uservo = this.userService.queryByUserid(userid);
      return uservo;
   }

   @ResponseBody
   @RequestMapping({"/queryAllUserSysByUserid"})
   public List<TBaseUsersys> queryUserSysByUserid(String userid, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<TBaseUsersys> userSysLst = this.userService.queryusersysbyuserid(userid);
      UserVO uservo = this.userService.queryByUserid(userid);
      if (uservo == null) {
         return userSysLst;
      } else {
         List<TBaseUsersys> groupSysLst = this.userService.queryusersysbyuserid(uservo.getGroupid());
         Map<String, TBaseUsersys> mapAllSys = new HashMap();

         for(TBaseUsersys usersys : userSysLst) {
            mapAllSys.put(usersys.getSysid(), usersys);
         }

         for(TBaseUsersys groupsys : groupSysLst) {
            if (mapAllSys.get(groupsys.getSysid()) != null) {
               if (Integer.parseInt(((TBaseUsersys)mapAllSys.get(groupsys.getSysid())).getCrud()) < Integer.parseInt(groupsys.getCrud())) {
                  mapAllSys.put(groupsys.getSysid(), groupsys);
               }
            } else {
               mapAllSys.put(groupsys.getSysid(), groupsys);
            }
         }

         List<TBaseUsersys> allSysList = new ArrayList();

         for(Map.Entry<String, TBaseUsersys> a : mapAllSys.entrySet()) {
            allSysList.add(a.getValue());
         }

         return allSysList;
      }
   }

   @ResponseBody
   @RequestMapping({"/removeUsersysByUserId"})
   public void removeUsersysByUserId(String userid, HttpServletRequest request, HttpServletResponse response, Model model) {
      this.userService.removeUsersysByUserId(userid);
   }

   @ResponseBody
   @RequestMapping({"/updateUserSysByUserid"})
   public void updateUserSysByUserid(String[] sysid, String crud, String userid, String updateuserid, HttpServletRequest request, HttpServletResponse response, Model model) {
      for(int i = 0; i < sysid.length; ++i) {
         TBaseUsersys userSys = new TBaseUsersys();
         userSys.setSysid(sysid[i]);
         userSys.setUserid(userid);
         userSys.setCrud(crud);
         userSys.setUpdateuserid(updateuserid);
         this.userService.saveUserSys(userSys);
      }

   }

   @ResponseBody
   @RequestMapping({"/queryUserProjectByUserid"})
   public List<TBaseUserproject> queryUserProjectByUserid(String userid, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<TBaseUserproject> userProList = this.tdataProjectService.queryuserprobyuserid(userid);
      UserVO uservo = this.userService.queryByUserid(userid);
      if (uservo == null) {
         return userProList;
      } else {
         List<TBaseUserproject> groupProList = this.tdataProjectService.queryuserprobyuserid(uservo.getGroupid());
         Map<String, TBaseUserproject> mapAllPro = new HashMap();

         for(TBaseUserproject userpro : userProList) {
            mapAllPro.put(userpro.getProid(), userpro);
         }

         for(TBaseUserproject grouppro : groupProList) {
            if (mapAllPro.get(grouppro.getProid()) != null) {
               if (Integer.parseInt(((TBaseUserproject)mapAllPro.get(grouppro.getProid())).getCrud()) < Integer.parseInt(grouppro.getCrud())) {
                  mapAllPro.put(grouppro.getProid(), grouppro);
               }
            } else {
               mapAllPro.put(grouppro.getProid(), grouppro);
            }
         }

         List<TBaseUserproject> allProList = new ArrayList();

         for(Map.Entry<String, TBaseUserproject> a : mapAllPro.entrySet()) {
            allProList.add(a.getValue());
         }

         return allProList;
      }
   }

   @ResponseBody
   @RequestMapping({"/removeUserprojectByUserId"})
   public void removeUserprojectByUserId(String userid, HttpServletRequest request, HttpServletResponse response, Model model) {
      this.userService.removeUserprojectByUserId(userid);
   }

   @ResponseBody
   @RequestMapping({"/removeUserprojectByUpdateuserId"})
   public void removeUserprojectByUpdateuserid(String proid, String updateuserid, HttpServletRequest request, HttpServletResponse response, Model model) {
      this.userService.removeUserprojectByUpdateuserid(proid, updateuserid);
   }

   @ResponseBody
   @RequestMapping({"/removeUsersysByUpdateuserId"})
   public void removeUsersysByUpdateuserId(String sysid, String updateuserid, HttpServletRequest request, HttpServletResponse response, Model model) {
      this.userService.removeUsersystByUpdateuserid(sysid, updateuserid);
   }

   @ResponseBody
   @RequestMapping({"/removeUserprojectByProjectId"})
   public void removeUserprojectByProjectId(@RequestBody TBaseUserproject vo) {
      this.userService.removeUserprojectByProjectid(vo.getProid());
   }

   @ResponseBody
   @RequestMapping({"/removeUsersysBysysId"})
   public void removeUsersysBysysId(String sysid, HttpServletRequest request, HttpServletResponse response, Model model) {
      this.userService.removeUsersysBySysId(sysid);
   }

   @ResponseBody
   @RequestMapping({"/updateUserProjectByUserid"})
   public Response<String> updateUserProjectByUserid(@RequestBody TUserProjReqVO vo) {
      try {
         this.userService.removeUserprojectByProjectid(vo.getProjectid());
         vo.getUcMap().entrySet().forEach((m) -> {
            TBaseUserproject userPro = new TBaseUserproject();
            userPro.setProid(vo.getProjectid());
            userPro.setUserid((String)m.getKey());
            userPro.setCrud((String)m.getValue());
            userPro.setUpdateuserid(vo.getUpdateuserid());
            this.userService.saveUserPro(userPro);
         });
      } catch (Exception var3) {
         return RespHelper.<String>errResp(ErrCode.SERVER_EXCEPTION);
      }

      return RespHelper.<String>successResp();
   }

   @ResponseBody
   @RequestMapping({"/updateUsersysByUserid"})
   public void updateUsersysByUserid(String[] sysid, String crud, String userid, String updateuserid, HttpServletRequest request, HttpServletResponse response, Model model) {
      for(int i = 0; i < sysid.length; ++i) {
         TBaseUsersys userSys = new TBaseUsersys();
         userSys.setSysid(sysid[i]);
         userSys.setUserid(userid);
         userSys.setCrud(crud);
         userSys.setUpdateuserid(updateuserid);
         this.userService.saveUserSyscrud(userSys);
      }

   }

   @RequestMapping({"/removeuser"})
   public void removeuser(String userid, String groupid, String username, HttpServletRequest request, HttpServletResponse response, Model model) {
      this.userGroupService.queryGroupByid(groupid);
      List<TBaseUsergroup> queryUsergroupBygroupid = this.userGroupService.queryUsergroupBygroupid(groupid);
      if (queryUsergroupBygroupid.size() == 1) {
         this.userGroupService.removeGroupByid(groupid);
      }

      this.userService.removeuser(userid);
      this.userService.deleteUserRoleByUserId(userid);
      this.userGroupService.removeUserGroupByUserId(userid);
      this.userService.removeUsersysByUserId(userid);
      this.userService.removeUserprojectByUserId(userid);
      TConsoleLog record = new TConsoleLog();
      LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
      String username1 = loginUser.getTsysUser().getUsername();
      record.setModule("用户管理");
      record.setOperationObject(username);
      record.setOperationtime(new Date());
      record.setUser(username1);
      record.setLogmessage("删除用户");
      this.operationService.add(record);
   }

   @ResponseBody
   @RequestMapping({"/queryButtonCRUD"})
   public List<TBaseButton> queryButtomCRUD(String userid, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<TBaseRole> trole = this.indexService.queryRoleByUserId(userid);
      return this.buttonService.queryButtonCRUDByRoleids(trole);
   }

   @ResponseBody
   @RequestMapping({"/queryButtonNotCRUD"})
   public List<TBaseButton> queryButtomNotCRUD(String userid, HttpServletRequest request, HttpServletResponse response, Model model) {
      List<TBaseRole> trole = this.indexService.queryRoleByUserId(userid);
      return this.buttonService.queryButtonNotCRUDByRoleids(trole);
   }

   @ResponseBody
   @RequestMapping({"/editUserPassword"})
   public ResultVO editUserPassword(String userid, String password) throws Exception {
      UserVO user = this.userService.queryByUserid(userid);
      if (user == null) {
         ResultVO vo = new ResultVO((String)null, true);
         return vo;
      } else if (password.equals(user.getPassword())) {
         ResultVO vo = new ResultVO((String)null, false);
         return vo;
      } else {
         ResultVO vo = new ResultVO((String)null, true);
         return vo;
      }
   }

   @ResponseBody
   @RequestMapping({"/selectDutyPerson"})
   public Response<List<DutyPersonVO>> selectDutyPerson(@RequestBody DutyPersonVO vo) throws Exception {
      List<DutyPersonVO> dutyPersonVOS = this.userService.selectDutyPerson(vo);
      return RespHelper.<List<DutyPersonVO>>successResp(dutyPersonVOS);
   }

   @ResponseBody
   @RequestMapping({"/saveDutyPerson"})
   public Response<String> saveDutyPerson(@RequestBody Map<String, Object> params) throws Exception {
      List<Map<String, Object>> paramsList = (List)params.get("duty");
      for(Map<String, Object> map : paramsList) {
         DutyPersonVO vo = new DutyPersonVO();
         vo.setDatasystemid((String)map.get("datasystemid"));
         vo.setDuty_id((String)map.get("duty_id"));
         vo.setDuty_name((String)map.get("duty_name"));
         vo.setDuty_scope((String)map.get("duty_scope"));
         vo.setDuty_main((String)map.get("duty_main"));
         vo.setProjectid((String)map.get("projectid"));
         if ("".equals(map.get("id"))) {
            List<DutyPersonVO> existPerson = this.userService.isExistPerson(vo);
            if (existPerson.isEmpty()) {
               this.userService.saveDutyPerson(vo);
            }
         } else {
            vo.setId(Integer.valueOf(String.valueOf(map.get("id"))));
            this.userService.updateDutyPerson(vo);
         }
      }

      return RespHelper.<String>successResp();
   }

   @ResponseBody
   @RequestMapping({"/delDutyPersonById"})
   public Response<String> delDutyPersonById(@RequestBody DutyPersonVO vo) throws Exception {
      try {
         this.userService.delDutyPersonById(vo);
      } catch (Exception var3) {
         RespHelper.errResp(ErrCode.SERVER_EXCEPTION);
      }

      return RespHelper.<String>successResp();
   }

   @ResponseBody
   @RequestMapping({"/modifyPassword"})
   public Response<String> modifyPassword(@RequestBody UserVO userVo, HttpServletRequest request, HttpServletResponse response, Model model) {
      TBaseUser user = this.userService.queryByusername(userVo.getUsername());
      System.out.println(userVo.getPassword().equals(user.getPassword()));
      SimpleDateFormat sdf = null;
      user.setUpdatetime(new Date());
      if (!userVo.getPassword().equals(user.getPassword())) {
         user.setPassword(userVo.getPassword());
         user.setEditpasswordtime(new Date());

         try {
            new Properties();
            Properties record = PropertiesLoaderUtils.loadAllProperties("config.properties");
            String limitnum = record.get("login_limit_num").toString();
            user.setLimitnum(limitnum);
         } catch (IOException e) {
            e.printStackTrace();
         }

         this.userService.save(user);
         TConsoleLog record = new TConsoleLog();
         LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
         String loginusername = loginUser.getTsysUser().getUsername();
         record.setModule("用户管理");
         record.setOperationtime(new Date());
         record.setUser(loginusername);
         record.setOperationObject(user.getUsername());
         record.setLogmessage("修改用户密码");
         record.setModifieduser(user.getUsername());
         this.operationService.add(record);
         return RespHelper.<String>successResp();
      } else {
         return RespHelper.<String>errResp(ErrCode.PASSWORD_ERROR_CODE);
      }
   }

   @ResponseBody
   @RequestMapping({"/changeGlobalOriginalConfig"})
   @PassToken
   public Response<String> changeGlobalOriginalConfig(@RequestBody Map<String, Object> param) throws Exception {
      Integer status = Integer.valueOf((String)param.get("status"));
      String projectId = (String)param.get("projectId");

      try {
         this.userService.changeGlobalOriginalConfig(status, projectId);
      } catch (Exception var5) {
         RespHelper.errResp(ErrCode.SERVER_EXCEPTION);
      }

      return RespHelper.<String>successResp();
   }

   @ResponseBody
   @RequestMapping({"/getGlobalOriginalConfig"})
   @PassToken
   public Response<Integer> getGlobalOriginalConfig(@RequestBody Map<String, Object> param) throws Exception {
      String projectId = (String)param.get("projectId");

      try {
         Integer globalOriginalConfig = this.userService.getGlobalOriginalConfig(projectId);
         return RespHelper.<Integer>successResp(globalOriginalConfig);
      } catch (Exception var4) {
         RespHelper.errResp(ErrCode.SERVER_EXCEPTION);
         return RespHelper.<Integer>successResp();
      }
   }
}
