package com.bweb.controller;

import com.github.pagehelper.PageInfo;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.AESEncodeUtil;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.SecPermission;
import com.hai.entity.SecRole;
import com.hai.entity.SecUser;
import com.hai.model.MenuTreeModel;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.SecPermissionService;
import com.hai.service.SecRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
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.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/secRole")
@Api(value = "角色管理")
public class SecRoleController {

    private static Logger log = LoggerFactory.getLogger(SecRoleController.class);

    @Resource
    private UserCenter userCenter;

    @Resource
    private SecRoleService secRoleService;

    @Resource
    private SecPermissionService secPermissionService;

    @RequestMapping(value = "/getRoleList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取角色列表")
    public ResponseData getRoleList(Integer roleType, String roleName, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        try {
            if (pageNum == null || pageSize == null) {
                log.error("SecRoleController --> getRoleList() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 登录人
            SessionObject sessionObject = userCenter.getSessionObject(request);
            if(sessionObject == null){
                log.error("SecRoleController --> getRoleList() error!", "");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            Long companyId = null;
            Integer templetType;
            if (userInfoModel.getSecRole().getRoleType() == 0) {
                templetType = 1;
            }else {
                companyId = userInfoModel.getBsCompany().getId();
                templetType = 0;
            }
            PageInfo<SecRole> roleList = secRoleService.findPage(companyId,templetType,roleType,roleName,pageNum,pageSize);
            return ResponseMsgUtil.success(roleList);
        } catch (Exception e) {
            log.error("SecRoleController --> getRoleList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/addRole", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "添加角色")
    public ResponseData addRole(@RequestBody SecRole secRole) {
        try {
            if (secRole.getRoleType() == null
                    || StringUtils.isBlank(secRole.getRoleName())
                    || secRole.getEnableStatus() == null
                    || secRole.getTempletType() == null
                    || (secRole.getTempletType() != 1 && secRole.getCompanyId() == null)) {
                log.error("SecRoleController --> addRole() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            //如果是角色模板 将公司这是为null
            if(secRole.getTempletType() == 1){
                secRole.setCompanyId(null);
            }

            if(secRole.getTempletType() != 1){
                SecRole role = secRoleService.findByName(secRole.getCompanyId(),secRole.getRoleName());
                if (role != null) {
                    log.error("SecRoleController --> addRole() error!", "该角色名已经存在，请更换");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.ROLE_NAME_IS_EXIST_ERROR, "");
                }
            }

            secRole.setPrimaryRole(0);
            secRole.setCreateTime(new Date());
            secRole.setUpdateTime(new Date());
            secRoleService.addRole(secRole);
            return ResponseMsgUtil.success(null);
        } catch (Exception e) {
            log.error("SecRoleController --> addRole() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/editRole", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改角色信息")
    public ResponseData editRole(@RequestBody SecRole secRole) {
        try {
            if (secRole.getId() == null
                    || StringUtils.isBlank(secRole.getRoleName())
                    ||  secRole.getEnableStatus() == null) {
                log.error("SecRoleController --> editRole() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            //查询角色信息
            SecRole role = secRoleService.findById(secRole.getId());
            if(role == null){
                log.error("SecRoleController --> editRole() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            if(role.getTempletType() != 1){
                if (secRoleService.findByName(secRole.getCompanyId(),secRole.getRoleName()) != null
                        && !role.getId().equals(secRole.getId())) {
                    log.error("SecRoleController --> editRole() error!", "该角色名已经存在，请更换");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.ROLE_NAME_IS_EXIST_ERROR, "");
                }
            }

            secRole.setUpdateTime(new Date());
            secRoleService.modifyRole(secRole);
            return ResponseMsgUtil.success(null);
        } catch (Exception e) {
            log.error("SecRoleController --> editRole() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/deleteRole", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "删除角色")
    public ResponseData deleteRole(Long sId) {
        try {
            if (sId == null) {
                log.error("SecRoleController --> editRole() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            List<SecUser> userList = secRoleService.getUsersByRoleId(sId);
            if (userList != null && userList.size() != 0) {
                log.error("SecRoleController --> editRole() error!", "该角色已分配给用户，不能删除");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_ROLE_HAS_ALLOT_ERROR, "");
            }
            SecRole role = secRoleService.findById(sId);
            role.setEnableStatus(2);
            secRoleService.modifyRole(role);
            return ResponseMsgUtil.success(null);
        } catch (Exception e) {
            log.error("SecRoleController --> deleteUser() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getAllRole", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询符合条件的角色集合")
    public ResponseData getAllRole(Long companyId,Integer primaryRole,Integer templetType) {
        try {
            if (primaryRole == null || templetType == null) {
                log.error("SecRoleController --> getAllRole() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            List<SecRole> roleList = secRoleService.getAllRole(companyId,null,0,0);
            return ResponseMsgUtil.success(roleList);
        } catch (Exception e) {
            log.error("SecRoleController --> getAllRole() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getAllRoleTemp", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询符合条件的角色模板集合")
    public ResponseData getAllRoleTemp(Long userId) {
        try {
            if (userId == null) {
                log.error("SecRoleController --> getAllRoleTemp() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            SecRole role = secRoleService.getRoleByUserId(userId);
            if (role == null) {
                log.error("SecRoleController --> getAllRoleTemp() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            Integer roleType = role.getRoleType();
            List<Integer> roleTypes = new ArrayList<>();
            if (roleType == 0) { // 超级管理员 可查询运营中心角色模板
                roleTypes.add(1);
                roleTypes.add(2);
            } else {
                log.error("SecRoleController --> getAllRoleTemp() error!", "除了admin，其他账号没有权限建立单位");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            //查询符合条件的角色模板
            List<SecRole> roleList = secRoleService.getAllRole(null,roleTypes,null,1);
            return ResponseMsgUtil.success(roleList);
        } catch (Exception e) {
            log.error("SecRoleController --> getAllRoleTemp() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getMainRoleByCompanyId", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据公司查询主角色")
    public ResponseData getMainRoleByCompanyId(Long companyId) {
        try {
            if (companyId == null) {
                log.error("SecRoleController --> getMainRoleByCompanyId() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            SecRole secMainRole = secRoleService.findMainRole(companyId);
            if (secMainRole == null) {
                log.error("SecRoleController --> getMainRoleByCompanyId() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            return ResponseMsgUtil.success(secMainRole);
        } catch (Exception e) {
            log.error("SecRoleController --> getAllRoleTemp() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/refreshRole", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "刷新角色")
    public ResponseData refreshRole(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 登录人员
            SessionObject sessionObject = userCenter.getSessionObject(request);
            if(sessionObject == null){
                log.error("SecRoleController --> refreshRole() error!", "");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (userInfoModel.getSecUser() == null) {
                log.error("SecRoleController --> refreshRole() error!", "用户信息错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }

            //查询用户
            SecUser secUser = userInfoModel.getSecUser();
            String aesStr = AESEncodeUtil.aesEncrypt(secUser.getId()+"");
            userInfoModel.setToken(aesStr);

            //查询用户角色
            SecRole secRole = secRoleService.getRoleByUserId(secUser.getId());
            if (secRole == null) {
                log.error("refreshRole error!","用户未分配角色");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_ROLE_PERMISSION_ALLOT_ERROR, "");
            }else if(secRole.getEnableStatus() != 1) {
                log.error("refreshRole error!","该角色已禁用");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_ROLE_PERMISSION_ALLOT_ERROR, "");
            }
            // 拥有的菜单权限集合
            List<MenuTreeModel> menuList = secPermissionService.findMenuByUserId(secUser.getId());
            // 拥有的按钮权限集合
            List<SecPermission> buttonList = secPermissionService.findBtnByUserId(secUser.getId());
            // 查询所有拥有权限集合
            List<SecPermission> permissionList = secPermissionService.findPermissionByUserId(secUser.getId());
            userInfoModel.setSecRole(secRole);
            userInfoModel.setMenuList(menuList);
            userInfoModel.setButtonList(buttonList);
            userInfoModel.setPermissionList(permissionList);

            SessionObject so = new SessionObject(secUser.getId()+"", 3, userInfoModel);
            userCenter.save(request, response, so);
            return ResponseMsgUtil.success(so);
        } catch (Exception e) {
            log.error("SecRoleController --> refreshRole() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


}
