package com.njzscloud.dispose.sys.resource.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njzscloud.common.security.permission.PermissionLoader;
import com.njzscloud.common.security.permission.RolePermission;
import com.njzscloud.dispose.sys.resource.contant.ResourceOrigin;
import com.njzscloud.dispose.sys.resource.mapper.ResourceMapper;
import com.njzscloud.dispose.sys.resource.pojo.entity.ResourceEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 系统资源表
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ResourceService extends ServiceImpl<ResourceMapper, ResourceEntity> implements PermissionLoader, IService<ResourceEntity> {
    /**
     * 删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void delRes(List<Long> ids, ResourceOrigin resourceOrigin) {
        this.remove(Wrappers.<ResourceEntity>lambdaQuery()
            .eq(ResourceEntity::getTableName, resourceOrigin.getVal())
            .in(ResourceEntity::getDataId, ids)
        );
    }

    /**
     * 校验是否被占用
     */
    public boolean occupied(List<Long> dataIds, ResourceOrigin resourceOrigin) {
        List<String> roles = baseMapper.occupied(Wrappers.query()
            .eq("a.table_name", resourceOrigin.getVal())
            .in("a.data_id", dataIds));
        return !roles.isEmpty();
    }

    public List<ResourceEntity> listRoleRes(String roleId, String tableName) {
        return baseMapper.listRoleRes(Wrappers.query()
            .eq("b.role_id", roleId)
            .eq(StrUtil.isNotBlank(tableName), "a.table_name", tableName));
    }

    @Override
    public List<RolePermission> load() {
        return baseMapper.loadPermission();
    }
}
