package com.itbaizhan.trave.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itbaizhan.trave.bean.PermissionWithStatus;
import com.itbaizhan.trave.mapper.PermissionMapper;
import com.itbaizhan.trave.mapper.RoleMapper;
import com.itbaizhan.trave.pojo.Permission;
import com.itbaizhan.trave.pojo.Role;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    //查询所有角色
    public Page<Role> findPages(Integer page,Integer size){
        Page selectPage = roleMapper.selectPage(new Page(page,size),null);
        return selectPage;
    }
    //新增角色
    public void add(Role role){
        roleMapper.insert(role);
    }

    //根据Id查询角色
    public Role findById(Integer rid){
        Role role = roleMapper.selectById(rid);
        return role;
    }

    //修改角色
    public void update(Role role){
        roleMapper.updateById(role);
    }

    //删除角色
    public void delete(Integer rid){
        roleMapper.deleteById(rid);
    }

    //查询角色的权限情况
    public List<PermissionWithStatus> findPermission(Integer rid){
        //查询所有权限
        List<Permission> permissions = permissionMapper.selectList(null);
        //查询角色拥有的所有权限id
        List<Integer> pids = permissionMapper.findPermissionIdRole(rid);
        //创建带有状态的角色集合
        List<PermissionWithStatus> permissionList = new ArrayList();
        //遍历所有角色
        for (Permission permission : permissions) {
           //创建带有状态的权限
            PermissionWithStatus permissionWithStatus = new PermissionWithStatus();
            //将权限属性复制给带有状态的权限
            BeanUtils.copyProperties(permission,permissionWithStatus);
            //如果角色拥有该权限
            if (pids.contains(permission.getPid())){
                permissionWithStatus.setRoleHas(true);
            }else {
                permissionWithStatus.setRoleHas(false);
            }
            permissionList.add(permissionWithStatus);
        }
        return permissionList;
    }

    //给角色重新分配权限
    public void updatePermissions(Integer rid,Integer[] ids){
        //删除用户所有权限
        roleMapper.deleteRoleAllPermissions(rid);
        //给用户重新添加权限
        for (Integer pid : ids) {
            roleMapper.addRolePermissions(rid,pid);
        }

    }


}
