package com.qmth.teachcloud.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.teachcloud.common.entity.SysPrivilege;
import com.qmth.teachcloud.common.entity.SysRole;
import com.qmth.teachcloud.common.entity.SysRolePrivilege;
import com.qmth.teachcloud.common.mapper.SysRolePrivilegeMapper;
import com.qmth.teachcloud.common.service.SysPrivilegeService;
import com.qmth.teachcloud.common.service.SysRolePrivilegeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色和菜单关联表 服务实现类
 * </p>
 *
 * @author xf
 * @since 2021-03-23
 */
@Service
public class SysRolePrivilegeServiceImpl extends ServiceImpl<SysRolePrivilegeMapper, SysRolePrivilege> implements SysRolePrivilegeService {

    @Resource
    SysPrivilegeService sysPrivilegeService;

    @Override
    public void removeByRoleId(Long id) {
        UpdateWrapper<SysRolePrivilege> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(SysRolePrivilege::getRoleId, id);
        this.remove(updateWrapper);
    }

    @Override
    public void saveBatch(SysRole role) {
        QueryWrapper<SysPrivilege> sysPrivilegeQueryWrapper = new QueryWrapper<>();
        sysPrivilegeQueryWrapper.lambda().in(SysPrivilege::getId, role.getPrivilegeIds());
        List<SysPrivilege> sysPrivilegeList = sysPrivilegeService.list(sysPrivilegeQueryWrapper);
        Set<String> relatedSet = sysPrivilegeList.stream().filter(s -> Objects.nonNull(s.getRelated())).map(s -> s.getRelated()).collect(Collectors.toSet());
        Set<Long> finalRelatedSet = new HashSet<>();
        for (String s : relatedSet) {
            if (s.contains(",")) {
                String[] arrays = s.split(",");
                for (int i = 0; i < arrays.length; i++) {
                    finalRelatedSet.add(Long.parseLong(arrays[i].trim()));
                }
            } else {
                finalRelatedSet.add(Long.parseLong(s));
            }
        }
        finalRelatedSet.addAll(Arrays.asList(role.getPrivilegeIds()));
        List<SysRolePrivilege> list = new ArrayList<>();
        for (Long privilegeId : finalRelatedSet) {
            SysRolePrivilege sysRolePrivilege = new SysRolePrivilege();
            sysRolePrivilege.setRoleId(role.getId());
            sysRolePrivilege.setPrivilegeId(privilegeId);
            list.add(sysRolePrivilege);
        }
        this.saveBatch(list);
    }

    @Override
    public List<SysRolePrivilege> listByRoleId(Long roleId) {
        QueryWrapper<SysRolePrivilege> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysRolePrivilege::getRoleId, roleId);
        return this.list(queryWrapper);
    }
}
