package com.qmth.distributed.print;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.*;
import com.qmth.teachcloud.common.enums.PrivilegeEnum;
import com.qmth.teachcloud.common.service.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;


import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description: 专门用来插入权限的帮助类
 * @Author: CaoZixuan
 * @Date: 2021-08-11
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class AuthHelpTest {
    @Resource
    SysUserService sysUserService;
    @Resource
    SysRoleService sysRoleService;
    @Resource
    SysUserRoleService sysUserRoleService;
    @Resource
    SysRolePrivilegeService sysRolePrivilegeService;
    @Resource
    SysPrivilegeService sysPrivilegeService;

    @Test
    public void createUserPrivilege(){
        Long userId = 10L;
        Long roleId = 2L;
        List<Long> privilegeIdList = new ArrayList<>();
        for (int i = 1; i<389 ;i ++){
            privilegeIdList.add((long) i);
        }


        List<SysRolePrivilege> sysRolePrivilegeList = new ArrayList<>();
        List<SysUserRole> sysUserRoleList = new ArrayList<>();


        for (Long privilegeId : privilegeIdList) {
            SysPrivilege sysPrivilege = sysPrivilegeService.getById(privilegeId);
            if (Objects.isNull(sysPrivilege) || sysPrivilege.getType().equals(PrivilegeEnum.MENU)){
                continue;
            }
            // 创建'sys_role_privilege' 表
            SysRolePrivilege sysRolePrivilege = new SysRolePrivilege();
            sysRolePrivilege.setEnable(true);
            sysRolePrivilege.setId(SystemConstant.getDbUuid());
            sysRolePrivilege.setPrivilegeId(privilegeId);
            sysRolePrivilege.setRoleId(roleId);
            sysRolePrivilegeList.add(sysRolePrivilege);

            // 创建 'sys_user_role' 表
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setEnable(true);
            sysUserRole.setId(SystemConstant.getDbUuid());
            sysUserRole.setPrivilegeId(privilegeId);
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(userId);
            sysUserRoleList.add(sysUserRole);
        }
        sysRolePrivilegeService.remove(new QueryWrapper<SysRolePrivilege>().lambda().eq(SysRolePrivilege::getRoleId,roleId));
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId,userId));
        sysRolePrivilegeService.saveBatch(sysRolePrivilegeList);
        sysUserRoleService.saveBatch(sysUserRoleList);
    }
}
