package com.hxhq.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import com.hxhq.business.domain.SystemLog;
import com.hxhq.business.service.ISystemLogService;
import com.hxhq.business.utils.ObjectCompareUtil;
import com.hxhq.system.domain.SysMenu;
import com.hxhq.system.domain.SysRoleDept;
import com.hxhq.system.domain.SysRoleMenu;
import com.hxhq.system.domain.SysUserRole;
import com.hxhq.system.form.RoleSaveForm;
import com.hxhq.system.mapper.*;
import com.hxhq.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.hxhq.common.core.constant.UserConstants;
import com.hxhq.common.core.exception.ServiceException;
import com.hxhq.common.core.utils.SpringUtils;
import com.hxhq.common.core.utils.StringUtils;
import com.hxhq.common.datascope.annotation.DataScope;
import com.hxhq.common.security.utils.SecurityUtils;
import com.hxhq.system.api.domain.SysRole;
import com.hxhq.system.api.domain.SysUser;
import com.hxhq.system.service.ISysRoleService;

/**
 * 角色 业务层处理
 * 
 * @author hxhq
 */
@Service
public class SysRoleServiceImpl implements ISysRoleService
{
    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysRoleDeptMapper roleDeptMapper;

    @Autowired
    private SysMenuMapper menuMapper;

    @Autowired
    private ISystemLogService systemLogService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 根据条件分页查询角色数据
     * 
     * @param role 角色信息
     * @return 角色数据集合信息//    @DataScope(deptAlias = "d")
     */
    @Override

    public List<SysRole> selectRoleList(SysRole role)
    {
        return roleMapper.selectRoleList(role);
    }

    /**
     * 根据用户ID查询角色
     * 
     * @param userId 用户ID
     * @return 角色列表
     */
    @Override
    public List<SysRole> selectRolesByUserId(Long userId)
    {
        List<SysRole> userRoles = roleMapper.selectRolePermissionByUserId(userId);
        List<SysRole> roles = selectRoleAll();
        for (SysRole role : roles)
        {
            for (SysRole userRole : userRoles)
            {
                if (role.getRoleId().longValue() == userRole.getRoleId().longValue())
                {
                    role.setFlag(true);
                    break;
                }
            }
        }
        return roles;
    }

    /**
     * 根据用户ID查询权限
     * 
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRolePermissionByUserId(Long userId)
    {
        List<SysRole> perms = roleMapper.selectRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms)
        {
            if (StringUtils.isNotNull(perm))
            {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 查询所有角色
     * 
     * @return 角色列表
     */
    @Override
    public List<SysRole> selectRoleAll()
    {
        return roleMapper.selectRoleList(new SysRole());
    }

    /**
     * 根据用户ID获取角色选择框列表
     * 
     * @param userId 用户ID
     * @return 选中角色ID列表
     */
    @Override
    public List<Long> selectRoleListByUserId(Long userId)
    {
        return roleMapper.selectRoleListByUserId(userId);
    }

    @Override
    public List<String> selectRoleNameListByUserId(Long userId) {
        return roleMapper.selectRoleNameListByUserId(userId);
    }

    /**
     * 通过角色ID查询角色
     * 
     * @param roleId 角色ID
     * @return 角色对象信息
     */
    @Override
    public SysRole selectRoleById(Long roleId)
    {
        return roleMapper.selectRoleById(roleId);
    }

    /**
     * 校验角色名称是否唯一
     * 
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public boolean checkRoleNameUnique(SysRole role)
    {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        SysRole info = roleMapper.checkRoleNameUnique(role.getRoleName());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色权限是否唯一
     * 
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public boolean checkRoleKeyUnique(SysRole role)
    {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        SysRole info = roleMapper.checkRoleKeyUnique(role.getRoleKey());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色是否允许操作
     * 
     * @param role 角色信息
     */
    @Override
    public void checkRoleAllowed(SysRole role)
    {
        if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin())
        {
            throw new ServiceException("不允许操作超级管理员角色");
        }
    }

    /**
     * 校验角色是否有数据权限
     * 
     * @param roleIds 角色id
     */
    @Override
    public void checkRoleDataScope(Long... roleIds)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()))
        {
            for (Long roleId : roleIds)
            {
                SysRole role = new SysRole();
                role.setRoleId(roleId);
                List<SysRole> roles = roleMapper.selectRoleList(role);
                if (StringUtils.isEmpty(roles))
                {
                    throw new ServiceException("没有权限访问角色数据！");
                }
            }
        }
    }

    /**
     * 通过角色ID查询角色使用数量
     * 
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int countUserRoleByRoleId(Long roleId)
    {
        return userRoleMapper.countUserRoleByRoleId(roleId);
    }

    /**
     * 新增保存角色信息
     * 
     * @param form 角色信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertRole(RoleSaveForm form)
    {
        sysUserService.checkPassword(SecurityUtils.getLoginUser().getSysUser(),form.getSign().getQmrmm(),false);
        SysRole role = form.getRole();
        // 新增角色信息
        roleMapper.insertRole(role);
        int row = insertRoleMenu(role);
        systemLogService.saveInfo(role.getRoleName(),null,"新增角色","Create Role",null,null,SecurityUtils.getUserId(),SecurityUtils.getNickName(),SecurityUtils.getUsername(),form.getSign().getRemark());
        return row;
    }

    /**
     * 修改保存角色信息
     * 
     * @param form 角色信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateRole(RoleSaveForm form)
    {
        sysUserService.checkPassword(SecurityUtils.getLoginUser().getSysUser(),form.getSign().getQmrmm(),false);
        SysRole role = form.getRole();
        SysRole old = selectRoleById(role.getRoleId());
        List<SysMenu> oldMenuList = menuMapper.selectMenuByRoleId(role.getRoleId());

        // 修改角色信息
        roleMapper.updateRole(role);
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
        int row = insertRoleMenu(role);

        List<SystemLog> logList = getModifyLogList(role,old,oldMenuList);
        if(logList.size()>0){
            for(SystemLog systemLog : logList){
                systemLog.setRemark(form.getSign().getRemark());
            }
            systemLogService.saveBatch(logList);
        }

        return row;
    }

    /**
     * 修改角色状态
     * 
     * @param form 角色信息
     * @return 结果
     */
    @Override
    public int updateRoleStatus(RoleSaveForm form)
    {
        sysUserService.checkPassword(SecurityUtils.getLoginUser().getSysUser(),form.getSign().getQmrmm(),false);
        SysRole role = form.getRole();
        String disableStatus = "1";
        if(disableStatus.equals(role.getStatus()) && countUserRoleByRoleId(role.getRoleId()) > 0){
            throw new ServiceException("角色已分配,不能禁用");
        }
        SysRole info = selectRoleById(role.getRoleId());
        int row = roleMapper.updateRole(role);
        systemLogService.saveInfo(info.getRoleName(),null,"0".equals(role.getStatus())?"启用角色":"禁用角色","0".equals(role.getStatus())?"Enable Role":"Disable Role",null,null,SecurityUtils.getUserId(),SecurityUtils.getNickName(),SecurityUtils.getUsername(),form.getSign().getRemark());
        return row;
    }

    /**
     * 修改数据权限信息
     * 
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int authDataScope(SysRole role)
    {
        // 修改角色信息
        roleMapper.updateRole(role);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId());
        // 新增角色和部门信息（数据权限）
        return insertRoleDept(role);
    }

    /**
     * 新增角色菜单信息
     * 
     * @param role 角色对象
     */
    public int insertRoleMenu(SysRole role)
    {
        int rows = 1;
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        for (Long menuId : role.getMenuIds())
        {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0)
        {
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }

    /**
     * 新增角色部门信息(数据权限)
     *
     * @param role 角色对象
     */
    public int insertRoleDept(SysRole role)
    {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<SysRoleDept> list = new ArrayList<SysRoleDept>();
        for (Long deptId : role.getDeptIds())
        {
            SysRoleDept rd = new SysRoleDept();
            rd.setRoleId(role.getRoleId());
            rd.setDeptId(deptId);
            list.add(rd);
        }
        if (list.size() > 0)
        {
            rows = roleDeptMapper.batchRoleDept(list);
        }
        return rows;
    }

    /**
     * 通过角色ID删除角色
     * 
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteRoleById(Long roleId)
    {
        SysRole sysRole = selectRoleById(roleId);

        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(roleId);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDeptByRoleId(roleId);

        int row = roleMapper.deleteRoleById(roleId);

        systemLogService.saveInfo(sysRole.getRoleName(),null,"删除角色","Remove Role",null,null,SecurityUtils.getUserId(),SecurityUtils.getNickName(),SecurityUtils.getUsername(),null);
        return row;
    }

    /**
     * 批量删除角色信息
     * 
     * @param roleIds 需要删除的角色ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteRoleByIds(Long[] roleIds)
    {
        for (Long roleId : roleIds)
        {
            checkRoleAllowed(new SysRole(roleId));
            checkRoleDataScope(roleId);
            SysRole role = selectRoleById(roleId);
            if (countUserRoleByRoleId(roleId) > 0)
            {
                throw new ServiceException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }
        }
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenu(roleIds);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDept(roleIds);
        return roleMapper.deleteRoleByIds(roleIds);
    }

    /**
     * 取消授权用户角色
     * 
     * @param userRole 用户和角色关联信息
     * @return 结果
     */
    @Override
    public int deleteAuthUser(SysUserRole userRole)
    {
        return userRoleMapper.deleteUserRoleInfo(userRole);
    }

    /**
     * 批量取消授权用户角色
     * 
     * @param roleId 角色ID
     * @param userIds 需要取消授权的用户数据ID
     * @return 结果
     */
    @Override
    public int deleteAuthUsers(Long roleId, Long[] userIds)
    {
        return userRoleMapper.deleteUserRoleInfos(roleId, userIds);
    }

    /**
     * 批量选择授权用户角色
     * 
     * @param roleId 角色ID
     * @param userIds 需要授权的用户数据ID
     * @return 结果
     */
    @Override
    public int insertAuthUsers(Long roleId, Long[] userIds)
    {
        // 新增用户与角色管理
        List<SysUserRole> list = new ArrayList<SysUserRole>();
        for (Long userId : userIds)
        {
            SysUserRole ur = new SysUserRole();
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            list.add(ur);
        }
        return userRoleMapper.batchUserRole(list);
    }

    /**
     * 获取修改日志
     * @param info
     * @param old
     * @param oldMenuList
     * @return
     */
    private List<SystemLog> getModifyLogList(SysRole info, SysRole old,List<SysMenu> oldMenuList){
        List<SystemLog> list = new ArrayList<>();

        List<ObjectCompareUtil.FieldChange> fieldChanges = ObjectCompareUtil.compareObjects(old, info);
        for (ObjectCompareUtil.FieldChange fieldChange : fieldChanges) {
            SystemLog log = getLogInfo(old);
            log.setJcnr(fieldChange.toString());
            log.setJcnrEn(fieldChange.toEnString());
            list.add(log);
        }
        if(!info.getStatus().equals(old.getStatus())){
            SystemLog log = getLogInfo(old);
            log.setJcnr("[{\"name\":\"字段名\",\"value\":\"状态\"},{\"name\":\"原值\",\"value\":\""+("0".equals(old.getStatus())?"启用":"禁用")+"\"},{\"name\":\"新值\",\"value\":\""+("0".equals(info.getStatus())?"启用":"禁用")+"\"}]");
            log.setJcnrEn("[{\"name\":\"Field\",\"value\":\"Status\"},{\"name\":\"Old Value\",\"value\":\""+("0".equals(old.getStatus())?"Enabled":"Disabled")+"\"},{\"name\":\"New Value\",\"value\":\""+("0".equals(info.getStatus())?"Enabled":"Disabled")+"\"}]");
            list.add(log);
        }

        //判断菜单修改
        Boolean updateMenu = false;
        if(info.getMenuIds().length!=oldMenuList.size()){
            updateMenu = true;
        }else{
            List<Long> oldMenuIdList = oldMenuList.stream().map(o->o.getMenuId()).collect(Collectors.toList());
            for(Long newMenuId : info.getMenuIds()){
                if(!oldMenuIdList.contains(newMenuId)){
                    updateMenu = true;
                    break;
                }
            }
        }
        if(updateMenu){
            List<SysMenu> newMenuList = new ArrayList<>();
            if(info.getMenuIds()!=null && info.getMenuIds().length>0){
                List<SysMenu> allMenuList = menuMapper.selectMenuList(new SysMenu());
                for(Long newMenuId : info.getMenuIds()){
                    newMenuList.add(allMenuList.stream().filter(o->o.getMenuId().equals(newMenuId)).collect(Collectors.toList()).get(0));
                }
            }

            List<String> addNameList = new ArrayList<>();
            List<String> deleteNameList = new ArrayList<>();
            List<Long> oldMenuIdList = oldMenuList.stream().map(o->o.getMenuId()).collect(Collectors.toList());
            List<Long> newMenuIdList = newMenuList.stream().map(o->o.getMenuId()).collect(Collectors.toList());
            for(SysMenu newMenu : newMenuList){
                if(!oldMenuIdList.contains(newMenu.getMenuId())){
                    addNameList.add(newMenu.getMenuName());
                }
            }

            for(SysMenu oldMenu : oldMenuList){
                if(!newMenuIdList.contains(oldMenu.getMenuId())){
                    deleteNameList.add(oldMenu.getMenuName());
                }
            }

            if(addNameList.size()>0 || deleteNameList.size()>0){
                SystemLog log = getLogInfo(old);
                log.setJcnr((addNameList.size()>0?("新增权限："+String.join(",",addNameList)):"")+(deleteNameList.size()>0?("；删除权限："+String.join(",",deleteNameList)):""));
                log.setJcnrEn((addNameList.size()>0?("Add Permit："+String.join(",",addNameList)):"")+(deleteNameList.size()>0?("；Remove Permit："+String.join(",",deleteNameList)):""));
                list.add(log);
            }
        }

        return list;
    }

    /**
     * 获取日志基础信息
     * @return
     */
    private SystemLog getLogInfo(SysRole sysRole){
        SystemLog log = new SystemLog();
        log.setName(sysRole.getRoleName());
        log.setNameEn(sysRole.getRoleName());
        log.setJcmc("编辑角色");
        log.setJcmcEn("Edit Role");
        log.setQmrId(SecurityUtils.getUserId());
        log.setQmrMc(SecurityUtils.getNickName());
        log.setQmrMcEn(SecurityUtils.getUsername());
        return log;
    }

    @Override
    public List<SysRoleMenu> selectRoleMenuByRoleIdList(List<Long> roleIdList) {
        return roleMapper.selectRoleMenuByRoleIdList(roleIdList);
    }
}
