package com.fs.company.service.impl;

import com.fs.common.constant.UserConstants;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.CompanyRole;
import com.fs.company.domain.CompanyRoleDept;
import com.fs.company.domain.CompanyRoleMenu;
import com.fs.company.mapper.CompanyRoleDeptMapper;
import com.fs.company.mapper.CompanyRoleMapper;
import com.fs.company.mapper.CompanyRoleMenuMapper;
import com.fs.company.mapper.CompanyUserRoleMapper;
import com.fs.company.service.ICompanyRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 角色信息Service业务层处理
 *
 * @author fs
 * @date 2021-05-25
 */
@Service
public class CompanyRoleServiceImpl implements ICompanyRoleService
{
    @Autowired
    private CompanyRoleMapper companyRoleMapper;
    @Autowired
    private CompanyRoleMenuMapper roleMenuMapper;
    @Autowired
    private CompanyRoleDeptMapper roleDeptMapper;
    @Autowired
    private CompanyUserRoleMapper userRoleMapper;
    /**
     * 查询角色信息
     *
     * @param roleId 角色信息ID
     * @return 角色信息
     */
    @Override
    public CompanyRole selectCompanyRoleById(Long roleId)
    {
        return companyRoleMapper.selectCompanyRoleById(roleId);
    }

    /**
     * 查询角色信息列表
     *
     * @param companyRole 角色信息
     * @return 角色信息
     */
    @Override
    public List<CompanyRole> selectCompanyRoleList(CompanyRole companyRole)
    {
        return companyRoleMapper.selectCompanyRoleList(companyRole);
    }

    /**
     * 新增角色信息
     *
     * @param companyRole 角色信息
     * @return 结果
     */
    @Override
    public int insertCompanyRole(CompanyRole companyRole)
    {
        companyRole.setCreateTime(DateUtils.getNowDate());
        return companyRoleMapper.insertCompanyRole(companyRole);
    }

    /**
     * 修改角色信息
     *
     * @param companyRole 角色信息
     * @return 结果
     */
    @Override
    public int updateCompanyRole(CompanyRole companyRole)
    {
        companyRole.setUpdateTime(DateUtils.getNowDate());
        return companyRoleMapper.updateCompanyRole(companyRole);
    }

    /**
     * 批量删除角色信息
     *
     * @param roleIds 需要删除的角色信息ID
     * @return 结果
     */
    @Override
    public int deleteCompanyRoleByIds(Long[] roleIds)
    {
        return companyRoleMapper.deleteCompanyRoleByIds(roleIds);
    }

    /**
     * 删除角色信息信息
     *
     * @param roleId 角色信息ID
     * @return 结果
     */
    @Override
    public int deleteCompanyRoleById(Long roleId)
    {
        return companyRoleMapper.deleteCompanyRoleById(roleId);
    }

    @Override
    public Collection<? extends String> selectRolePermissionByUserId(Long userId) {
        List<CompanyRole> perms = companyRoleMapper.selectRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (CompanyRole perm : perms)
        {
            if (StringUtils.isNotNull(perm))
            {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }


    @Override
    public String checkRoleNameUnique(CompanyRole role) {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        CompanyRole info = companyRoleMapper.checkRoleNameUnique(role.getRoleName(),role.getCompanyId());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String checkRoleKeyUnique(CompanyRole role) {

        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        CompanyRole info = companyRoleMapper.checkRoleKeyUnique(role.getRoleKey(),role.getCompanyId());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;

    }

    @Override
    public int insertRole(CompanyRole role) {
        // 新增角色信息
        companyRoleMapper.insertCompanyRole(role);
        return insertRoleMenu(role);
    }



    @Override
    @Transactional
    public int updateRole(CompanyRole role) {
        // 修改角色信息
        companyRoleMapper.updateCompanyRole(role);
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
        return insertRoleMenu(role);
    }

    @Override
    public int authDataScope(CompanyRole role) {
        // 修改角色信息
        companyRoleMapper.updateCompanyRole(role);
        // 删除角色与部门关联
        roleDeptMapper.deleteCompanyRoleDeptById(role.getRoleId());
        // 新增角色和部门信息（数据权限）
        return insertRoleDept(role);
    }

    @Override
    public int updateRoleStatus(CompanyRole role) {
        return companyRoleMapper.updateCompanyRole(role);
    }

    @Override
    public String selectRoleAll() {
        return null;
    }

    @Override
    public int deleteRoleByIds(Long[] roleIds) {
        for (Long roleId : roleIds)
        {
            CompanyRole role = selectCompanyRoleById(roleId);
            if (countUserRoleByRoleId(roleId) > 0)
            {
                throw new CustomException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }
        }
        return companyRoleMapper.deleteCompanyRoleByIds(roleIds);
    }



    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    public int insertRoleMenu(CompanyRole role)
    {
        int rows = 1;
        // 新增用户与角色管理
        List<CompanyRoleMenu> list = new ArrayList<CompanyRoleMenu>();
        for (Long menuId : role.getMenuIds())
        {
            CompanyRoleMenu rm = new CompanyRoleMenu();
            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(CompanyRole role)
    {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<CompanyRoleDept> list = new ArrayList<CompanyRoleDept>();
        for (Long deptId : role.getDeptIds())
        {
            CompanyRoleDept rd = new CompanyRoleDept();
            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
    public int countUserRoleByRoleId(Long roleId)
    {
        return userRoleMapper.countUserRoleByRoleId(roleId);
    }

    @Override
    public List<Integer> selectRoleListByUserId(Long userId) {
        return companyRoleMapper.selectRoleListByUserId(userId);
    }

    @Override
    public List<CompanyRole> selectCompanyRoleByIds(List<Long> roleIds) {
        return companyRoleMapper.selectRoleListByIds(roleIds);
    }

    @Override
    public CompanyRole selectCompanyRoleByRoleKey(String roleKey) {
        return companyRoleMapper.selectCompanyRoleByRoleKey(roleKey);
    }

    @Override
    public int insertDefaultRole(CompanyRole role) {
        return companyRoleMapper.insertCompanyRole(role);
    }
}
