package com.ssyf.module.auth.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ssyf.module.auth.domain.entity.RoleMenuPermissionRelation;
import com.ssyf.module.auth.mapper.RoleMenuPermissionRelationMapper;
import com.ssyf.module.auth.service.RoleMenuPermissionRelationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author auth
 * @since 2022-12-12
 */
@Service
public class RoleMenuPermissionRelationServiceImpl extends ServiceImpl<RoleMenuPermissionRelationMapper, RoleMenuPermissionRelation> implements RoleMenuPermissionRelationService {

    @Override
    public void removeInMenuPermissionUids(List<String> menuPermissionUids) {
        this.remove(new LambdaQueryWrapper<RoleMenuPermissionRelation>().in(RoleMenuPermissionRelation::getMenuPermissionUid,menuPermissionUids));
    }

    @Override
    public void removeByRoleUids(List<String> roleUids) {
        this.remove(new LambdaQueryWrapper<RoleMenuPermissionRelation>().in(RoleMenuPermissionRelation::getRoleUid,roleUids));
    }

    @Override
    public List<RoleMenuPermissionRelation> getListInRoleUid(List<String> roleUids) {
        return this.list(new LambdaQueryWrapper<RoleMenuPermissionRelation>().in(RoleMenuPermissionRelation::getRoleUid,roleUids));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignAndRemoveOld(String roleUid, List<String> menuPermissionUids) {
        //删除旧数据
        this.removeByRoleUids(Arrays.asList(roleUid));
        //重建关联
        if(CollectionUtil.isEmpty(menuPermissionUids)){
            return;
        }
        List<RoleMenuPermissionRelation> relationList = new ArrayList<>();
        menuPermissionUids.forEach(menuPermissionUid->{
            RoleMenuPermissionRelation relation = new RoleMenuPermissionRelation();
            relation.setRoleUid(roleUid).setMenuPermissionUid(menuPermissionUid);
            relationList.add(relation);
        });
        //可优化
        List<List<RoleMenuPermissionRelation>> pages = CollectionUtil.split(relationList, 1000);
        for (List<RoleMenuPermissionRelation> page : pages){
            this.baseMapper.insertBatch(page);
        }
    }


}
