package com.pqs9900.controller.user;


import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.njcn.enums.LogTypeEnum;
import com.njcn.enums.RoleGroupEnum;
import com.njcn.pojo.commons.PatternRegex;
import com.njcn.pojo.commons.RedisDB;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.PubUtils;
import com.njcn.utils.SerializeUtil;
import com.njcn.utils.XssFilterUtil;
import com.njcn.utils.redis.JedisManager;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.commons.SimpleValue;
import com.njcn.pojo.user.Role;
import com.njcn.pojo.user.RoleGroup;
import com.njcn.sso.pojo.user.User;
import com.njcn.service.user.RoleGroupService;
import com.njcn.service.user.RoleService;
import com.njcn.service.user.UserService;

@Controller
@RequestMapping(value = "/role")
public class RoleController {
    @Resource
    private RoleService rs;
    @Resource
    private RoleGroupService rgs;
    @Autowired
    JedisManager jedisManager;
    @Autowired
    UserLogDetailService userLogservice;
    // 日志记录
    private static final Logger logger = LoggerFactory.getLogger(RoleController.class);

    //查询所有非管理角色
    @ResponseBody
    @RequestMapping(value = "selectAllName", method = RequestMethod.POST)
    public List<RoleGroup> selectAllName(HttpServletRequest request) {
        List<RoleGroup> list = new ArrayList<>();
        try {
            List<String> ManagerRolegroup=new ArrayList<>();
            ManagerRolegroup.add(RoleGroupEnum.SYSTEM.getEname());
            ManagerRolegroup.add(RoleGroupEnum.AUDIT.getEname());
            ManagerRolegroup.add(RoleGroupEnum.CHECK.getEname());
            ManagerRolegroup.add(RoleGroupEnum.BUSINESS.getEname());
            ManagerRolegroup.add(RoleGroupEnum.CASUAL.getEname());
            ManagerRolegroup.add(RoleGroupEnum.ROOT.getEname());
            list = rgs.selectAllName(ManagerRolegroup);
            userLogservice.getLog("查询角色", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        } catch (Exception e) {
            logger.error("查询所有正式用户异常，异常为" + e.toString());
            userLogservice.getLog("查询角色", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        }
        return list;
    }

    //查询所有角色
    @ResponseBody
    @RequestMapping(value = "selectAll", method = RequestMethod.POST)
    public List<Role> selectAll() {
        List<Role> list = new ArrayList<>();
        try {
            list = rs.selectAll();
        } catch (Exception e) {
            logger.error("查询所有角色异常，异常为" + e.toString());
        }
        return list;
    }

    //根据角色名查询所有角色
    @ResponseBody
    @RequestMapping(value = "queryNameAll", method = RequestMethod.POST)
    public List<Role> queryNameAll(@Param(value = "roleName") String roleName) {
        if (roleName == null) {
            roleName = "";
        }
        roleName = "%" + roleName + "%";
        List<Role> list = new ArrayList<>();
        try {
            list = rs.queryNameAll(roleName);
        } catch (Exception e) {
            logger.error("查询所有角色异常，异常为" + e.toString());
        }
        return list;
    }

    //添加角色
    @ResponseBody
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    public int insert(@Param(value = "roleName") String roleName, @Param(value = "updateTime") Date updateTime, @Param(value = "roleIndex") String roleIndex, @Param(value = "userIndex") String userIndex, @Param(value = "roleDescription") String roleDescription,HttpServletRequest request) {
        int flag = 0;
        if (rs.selName(roleName) > 0) {
            flag = 2;
            return flag;
        } else {
            Role role = new Role();
            try {
                roleIndex = java.util.UUID.randomUUID().toString();
                role.setRoleIndex(roleIndex);
                role.setRoleName(roleName);
                User user = new User();
                user.setUserIndex(userIndex);
                role.setUserIndex(user.getUserIndex());
                updateTime = new Date();
                role.setUpdateTime(updateTime);
                role.setRoleDescription(roleDescription);
                int state = 1;
                role.setState(state);
                rs.insertRole(role);
                flag = 1;
                userLogservice.getLog("新增角色", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
            } catch (Exception e) {
                logger.error("新增角色异常，异常为" + e.toString());
                userLogservice.getLog("新增角色", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
                flag = 0;
            }
            return flag;
        }
    }

    //修改角色
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public int updateRole(@Param(value = "roleName") String roleName, @Param(value = "updateTime") Date updateTime, @Param(value = "roleIndex") String roleIndex, @Param(value = "userIndex") String userIndex, @Param(value = "roleDescription") String roleDescription,HttpServletRequest request) {
        int flag = 0;
        if (rs.selName(roleName) > 0) {
            flag = 2;
            return flag;
        } else {
            Role role = new Role();
            try {
                role.setRoleIndex(roleIndex);
                role.setRoleName(roleName);
                User user = new User();
                user.setUserIndex(userIndex);
                role.setUserIndex(user.getUserIndex());
                updateTime = new Date();
                role.setUpdateTime(updateTime);
                role.setRoleDescription(roleDescription);
                int state = 1;
                role.setState(state);
                rs.updateRole(role);
                flag = 1;
                userLogservice.getLog("修改角色", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
            } catch (Exception e) {
                logger.error("修改角色异常，异常为" + e.toString());
                userLogservice.getLog("修改角色", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
                flag = 0;
            }

            return flag;
        }

    }

    @RequestMapping("/selectId")
    @ResponseBody
    public Role selectRoleIndex(@Param(value = "roleIndex") String roleIndex) {
        return rs.selectRoleIndex(roleIndex);
    }

    //删除角色
    @ResponseBody
    @RequestMapping("/delete")
    public int delete(@Param(value = "roleIndex") String roleIndex,HttpServletRequest request) {
        Role role = new Role();
        int flag = 0;
        try {
            role.setRoleIndex(roleIndex);
            rs.deleteRole(role);
            flag = 1;
            userLogservice.getLog("删除角色", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        } catch (Exception e) {
            logger.error("删除角色异常，异常为" + e.toString());
            userLogservice.getLog("删除角色", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
            flag = 0;
        }
        return flag;
    }


    /**
     * 获取当前所有的角色列表
     */
    @RequestMapping(value = "getRoleList", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getRoleList(HttpServletRequest request) {
        HttpResult result=PubUtils.initResult(TokenManager.getToken().getLoginName(),request,LogTypeEnum.SYSTEM.toString(),1);
        try {
            List<List> roleList = rs.getRoleList();
            if (roleList.isEmpty()) {
                result=PubUtils.assignmentResultLog(null,500,"获取角色信息为空","查询角色","成功",result);
            } else {
                result=PubUtils.assignmentResultLog(roleList,200,"获取角色信息成功","查询角色","成功",result);
            }
            userLogservice.getLog("查询角色", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        } catch (Exception e) {
            logger.error("获取角色异常，异常为" + e.toString());
            userLogservice.getLog("查询角色", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
            result=PubUtils.assignmentResultLog(null,500,"获取角色失败","查询角色","失败",result);
        }
        return result;
    }

    /**
     * 新增角色
     */
    @RequestMapping(value = "addRole", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult addRole(HttpServletRequest request, String roleName, String roleD) {
        HttpResult result=PubUtils.initResult(TokenManager.getToken().getLoginName(),request,LogTypeEnum.SYSTEM.toString(),2);
        //后台Xss攻击处理、包括html/js/sql
        roleName = XssFilterUtil.dealString(roleName);
        roleD = XssFilterUtil.dealString(roleD);
        try {
            if (StringUtils.isBlank(roleD)) {
                roleD = "暂无描述";
            }
            if(StringUtils.isBlank(roleName)){
                result=PubUtils.assignmentResultLog(null,500,"新增角色失败,角色名为空","新增角色","失败",result);
            }else {
                if(PubUtils.patternRole(roleName)){
                    String message = rs.saveRole(roleName, roleD);
                    if (message.equalsIgnoreCase("新增角色成功！")) {
                        result=PubUtils.assignmentResultLog("success",200,message,"新增角色","成功",result);
                    } else {
                        result=PubUtils.assignmentResultLog(null,500,message,"新增角色","成功",result);
                    }
                }else {
                    result=PubUtils.assignmentResultLog(null,500,"角色名不符合由字母、数字组成，且数字不可开头","新增角色","失败",result);
                }
            }
            userLogservice.getLog("新增角色", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        } catch (Exception e) {
            logger.error("新增角色异常，异常是" + e.toString());
            result=PubUtils.assignmentResultLog(null,500,"新增角色失败","新增角色","失败",result);
            userLogservice.getLog("新增角色", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        }
        return result;
    }

    /**
     * 根据角色索引删除角色
     */
    @RequestMapping(value = "deleteRoleByIndex", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult deleteRoleByIndex(HttpServletRequest request, String index) {
        HttpResult result=PubUtils.initResult(TokenManager.getToken().getLoginName(),request,LogTypeEnum.SYSTEM.toString(),2);
        try {
            String ip = PubUtils.getIpAddr(request);
            String username = TokenManager.getToken().getLoginName();

            byte[] value = jedisManager.getValueByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip));
            String key = SerializeUtil.deserialize(value, String.class);
            if(key.equals("success")){
                String message = rs.deleteRoleByIndex(index);
                if (message.equalsIgnoreCase("删除角色成功！")) {
                    result=PubUtils.assignmentResultLog("success",200,message,"删除角色","成功",result);
                } else {
                    result.setCode(500);
                    result.setMessage(message);
                    result=PubUtils.assignmentResultLog(null,500,message,"删除角色","成功",result);
                }
            }else{
                result.setCode(400);
                result.setMessage("密码验证失败!");
                result=PubUtils.assignmentResultLog(null,500,"密码验证失败!","删除角色","失败",result);
            }
            jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip));
            userLogservice.getLog("删除角色", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        } catch (Exception e) {
            logger.error("删除角色异常，异常是" + e.toString());
            result=PubUtils.assignmentResultLog(null,500,"删除角色失败","删除角色","失败",result);
            userLogservice.getLog("删除角色", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
        }
        return result;
    }

    /**
     * 获取所有用户信息，以及用户下角色的信息
     */
    @RequestMapping(value = "getUserRole", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getUserRole(HttpServletRequest request) {
        HttpResult result = new HttpResult();
        try {
            List<List> roleList = rs.getUserRole();
            if (roleList.isEmpty()) {
                result.setMessage("获取用户角色信息失败");
                result.setCode(500);
            } else {
                result.setCode(200);
                result.setMessage("获取用户角色信息成功");
                result.setBody(roleList);
            }
        } catch (Exception e) {
            logger.error("查询角色信息异常，异常是" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "查询角色信息失败");
        }
        return result;
    }

    /**
     * 回显用户角色，方便用户重新分配角色
     */
    @RequestMapping(value = "backRole", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult backRole(HttpServletRequest request, String roleGPIndex) {
        HttpResult result=PubUtils.initResult(TokenManager.getToken().getLoginName(),request,LogTypeEnum.SYSTEM.toString(),1);
        List<SimpleValue> lists;
        try {
            lists = rs.getBackRole(roleGPIndex);
            if (lists.isEmpty()) {
                result=PubUtils.assignmentResultLog(null,500,"获取用户角色信息为空","获取角色信息","成功",result);
            } else {
                result=PubUtils.assignmentResultLog(lists,200,"获取用户角色信息成功","获取角色信息","成功",result);
            }
        } catch (Exception e) {
            logger.error("查询用户角色信息异常，异常是" + e.toString());
            result=PubUtils.assignmentResultLog(null,500,"获取用户角色信息异常","获取角色信息","失败",result);
        }
        return result;
    }

    /**
     * 根据用户选择的角色索引，以及用户索引，为该用户重新分配角色
     */
    @RequestMapping(value = "disRole", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult disRole(HttpServletRequest request, String roleGPIndex, String roleIndex) {
        HttpResult result=PubUtils.initResult(TokenManager.getToken().getLoginName(),request,LogTypeEnum.SYSTEM.toString(),2);
        roleGPIndex=XssFilterUtil.dealString(roleGPIndex);
        roleIndex=XssFilterUtil.dealString(roleIndex);
        try {
            String message = rs.disRole(roleGPIndex, roleIndex);
            if (message.equalsIgnoreCase("分配角色成功")) {
                result=PubUtils.assignmentResultLog(null,200,message,"修改角色和角色组关系","成功",result);
            } else {
                result=PubUtils.assignmentResultLog(null,500,message,"修改角色和角色组关系","失败",result);
            }
        } catch (Exception e) {
            logger.error("分配角色异常，异常是" + e.toString());
            result=PubUtils.assignmentResultLog(null,500,"分配角色失败","修改角色和角色组关系","失败",result);
        }
        return result;
    }

}
