package com.hzs.system.sys.service.impl;

import java.util.*;

import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.domain.system.sys.*;
import com.hzs.system.sys.param.SysRoleParam;
import com.hzs.system.sys.param.SysRoleQueryParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.hzs.common.core.constant.UserConstants;
import com.hzs.common.core.exception.ServiceException;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.system.sys.mapper.SysRoleScopeMapper;
import com.hzs.system.sys.mapper.SysRoleMapper;
import com.hzs.system.sys.mapper.SysUserRoleMapper;
import com.hzs.system.sys.service.ISysRoleService;
import org.springframework.util.CollectionUtils;

/**
 * 角色 业务层处理
 *
 * @author hzs
 */
@Service
public class SysRoleServiceImpl implements ISysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysRoleScopeMapper sysRoleScopeMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 根据条件分页查询角色数据
     *
     * @param param
     * @return
     */
    @Override
    public List<SysRole> selectRoleList(SysRoleQueryParam param) {
        return sysRoleMapper.selectRoleList(param);
    }

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

    /**
     * 校验角色名称是否唯一
     *
     * @param param
     * @return
     */
    @Override
    public String checkRoleNameUnique(SysRoleParam param) {
        long roleId = StringUtils.isNull(param.getRoleId()) ? -1L : param.getRoleId();
        SysRole info = sysRoleMapper.checkRoleNameUnique(param.getRoleName());
        if (StringUtils.isNotNull(info) && info.getRoleId() != roleId) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色权限是否唯一
     *
     * @param param
     * @return
     */
    @Override
    public String checkRoleKeyUnique(SysRoleParam param) {
        long roleId = StringUtils.isNull(param.getRoleId()) ? -1L : param.getRoleId();
        SysRole info = sysRoleMapper.checkRoleKeyUnique(param.getRoleKey());
        if (StringUtils.isNotNull(info) && info.getRoleId() != roleId) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色是否允许操作
     *
     * @param roleId 角色ID
     */
    @Override
    public void checkRoleAllowed(Long roleId) {
        if (SysRole.isAdmin(roleId)) {
            throw new ServiceException("不允许操作超级管理员角色");
        }
    }

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

    /**
     * 新增保存角色信息
     *
     * @param param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertRole(SysRoleParam param, Long userId) {
        SysRole sysRole = new SysRole();
        sysRole.setRoleName(param.getRoleName());
        sysRole.setRoleKey(param.getRoleKey());
        sysRole.setRoleSort(param.getRoleSort());
        sysRole.setStatus(param.getStatus());
        sysRole.setDataScope(param.getDataScope());
        sysRole.setPkCreator(userId);
        if (sysRoleMapper.insertRole(sysRole) > 0) {
            // 如果存在角色范围，需要处理角色范围
            if (!CollectionUtils.isEmpty(param.getScopeIdList())) {
                List<SysRoleScope> list = new ArrayList<>(param.getScopeIdList().size());
                for (Long scopeId : param.getScopeIdList()) {
                    SysRoleScope sysRoleScope = new SysRoleScope();
                    sysRoleScope.setRoleId(sysRole.getRoleId());
                    sysRoleScope.setScopeId(scopeId);
                    sysRoleScope.setPkCreator(userId);
                    list.add(sysRoleScope);
                }
                sysRoleScopeMapper.batchRoleScope(list);
            }
            return 1;
        }
        return 0;
    }

    /**
     * 修改保存角色信息
     *
     * @param param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateRole(SysRoleParam param, Long userId) {
        Date nowDate = new Date();

        SysRole sysRole = new SysRole();
        sysRole.setRoleId(param.getRoleId());
        sysRole.setRoleName(param.getRoleName());
        sysRole.setRoleKey(param.getRoleKey());
        sysRole.setRoleSort(param.getRoleSort());
        sysRole.setStatus(param.getStatus());
        sysRole.setDataScope(param.getDataScope());
        sysRole.setPkModified(userId);
        sysRole.setModifiedTime(nowDate);
        sysRoleMapper.updateRole(sysRole);

        sysRoleScopeMapper.deleteRoleScope(param.getRoleId(), userId);
        // 如果存在角色范围，需要处理角色范围
        if (!CollectionUtils.isEmpty(param.getScopeIdList())) {
            List<SysRoleScope> list = new ArrayList<>(param.getScopeIdList().size());
            for (Long scopeId : param.getScopeIdList()) {
                SysRoleScope sysRoleScope = new SysRoleScope();
                sysRoleScope.setRoleId(sysRole.getRoleId());
                sysRoleScope.setScopeId(scopeId);
                sysRoleScope.setPkCreator(userId);
                list.add(sysRoleScope);
            }
            sysRoleScopeMapper.batchRoleScope(list);
        }
        return 1;
    }

    /**
     * 批量删除角色信息
     *
     * @param roleIds 需要删除的角色ID
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteRoleByIds(Long[] roleIds, Long userId) {
        for (Long roleId : roleIds) {
            checkRoleAllowed(roleId);

            SysRole role = selectRoleById(roleId);
            if (countUserRoleByRoleId(roleId) > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }

            sysRoleScopeMapper.deleteRoleScope(roleId, userId);
        }
        return sysRoleMapper.deleteRoleByIds(roleIds, userId);
    }

    @Override
    public Map<Long, SysRole> getAllRoleMap() {
        Map<Long, SysRole> resultMap = new HashMap<>();
        List<SysRole> roleList = sysRoleMapper.selectRoleList(new SysRoleQueryParam());
        if (CollectionUtil.isNotEmpty(roleList)) {
            for (SysRole sysRole : roleList) {
                resultMap.put(sysRole.getRoleId(), sysRole);
            }
        }
        return resultMap;
    }

    @Override
    public List<Long> queryRoleIdListByUser(Long userId) {
        return sysUserRoleMapper.queryRoleIdListByUser(userId);
    }

}
