package com.njcn.product.cnuser.user.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.product.cnuser.user.mapper.SysRoleFunctionMapper;
import com.njcn.product.cnuser.user.pojo.po.SysFunction;
import com.njcn.product.cnuser.user.pojo.po.SysRoleFunction;
import com.njcn.product.cnuser.user.service.ISysRoleFunctionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author caozehui
 * @date 2024-11-12
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysRoleFunctionServiceImpl extends ServiceImpl<SysRoleFunctionMapper, SysRoleFunction> implements ISysRoleFunctionService {

    @Override
    public List<SysFunction> listFunctionByRoleId(String roleId) {
        return this.baseMapper.getFunctionListByRoleId(roleId);
    }

    @Override
    @Transactional
    public boolean updateRoleFunction(String roleId, List<String> functionIds) {
        //删除原有关系
        this.deleteRoleFunctionByRoleIds(Collections.singletonList(roleId));
        //新增关系
        List<SysRoleFunction> roleFunctions = new ArrayList<>();
        functionIds.forEach(functionId -> {
            SysRoleFunction roleFunction = new SysRoleFunction();
            roleFunction.setRoleId(roleId);
            roleFunction.setFunctionId(functionId);
            roleFunctions.add(roleFunction);
        });
        if (CollectionUtil.isEmpty(roleFunctions)) {
            return true;
        } else {
            return this.saveBatch(roleFunctions);
        }
    }

    @Override
    @Transactional
    public boolean deleteRoleFunctionByRoleIds(List<String> roleIds) {
        LambdaQueryWrapper<SysRoleFunction> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.in(SysRoleFunction::getRoleId, roleIds);
        return this.remove(lambdaQuery);
    }

    @Override
    @Transactional
    public boolean deleteRoleFunctionByFunctionIds(List<String> functionIds) {
        LambdaQueryWrapper<SysRoleFunction> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.in(SysRoleFunction::getFunctionId, functionIds);
        return this.remove(lambdaQuery);
    }
}
