package com.wsk.travelf.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wsk.travelf.bean.PermissionWithStatus;
import com.wsk.travelf.mapper.PermissionMapper;
import com.wsk.travelf.mapper.RoleMapper;
import com.wsk.travelf.pojo.Permission;
import com.wsk.travelf.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> findPage(int page,int size) {
        return roleMapper.selectPage(new Page<>(page,size),null);
    }

    //新增角色
    public void add(Role role) {
        roleMapper.insert(role);
    }

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

        return role;
    }

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

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

    //查询角色的权限情况
    public List<PermissionWithStatus> findPermission(Integer rid) {
        //查询所有权限
        List<Permission> permissions = permissionMapper.selectList(null);
        //查询角色拥有的所有权限id
        List<Integer> pids = permissionMapper.findPermissionIdByRole(rid);
        //构建带有状态的权限集合
        List<PermissionWithStatus> permissionWithStatuses = 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);
            }

            permissionWithStatuses.add(permissionWithStatus);
        }

        return permissionWithStatuses;
    }

    //相关角色权限
    public void updatePermission(Integer rid,Integer pids[]) {

        //删除用户权限
        roleMapper.deleteRoleAllPermissions(rid);

        //给用户添加权限
        for (Integer pid : pids) {
            roleMapper.addRolePermission(rid,pid);
        }

    }

}
