package com.xjrsoft.module.authority.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.utils.RedisUtil;
import com.xjrsoft.module.authority.entity.DataAuthTableRelation;
import com.xjrsoft.module.authority.mapper.DataAuthTableRelationMapper;
import com.xjrsoft.module.authority.service.IDataAuthTableRelationService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 数据权限 与 表 关联关系表 服务实现类
 * </p>
 *
 * @author tzx
 * @since 2023-02-28
 */
@Service
@AllArgsConstructor
public class DataAuthTableRelationServiceImpl extends ServiceImpl<DataAuthTableRelationMapper, DataAuthTableRelation> implements IDataAuthTableRelationService {

    private final RedisUtil redisUtil;

    @Override
    public Boolean saveDataAuthTableRelations(String tableName, List<Long> dataAuthIdList) {
        List<DataAuthTableRelation> toSaveList = new ArrayList<>();
        // 先删除原有的关联关系
        boolean isRemoved = this.remove(Wrappers.<DataAuthTableRelation>query().lambda().eq(DataAuthTableRelation::getTableName, tableName));
        boolean isSuccessAdd = false;
        if (CollectionUtils.isNotEmpty(dataAuthIdList)) {
            for (Long id : dataAuthIdList) {
                DataAuthTableRelation item = new DataAuthTableRelation();
                item.setDataAuthId(id);
                item.setTableName(tableName);
                toSaveList.add(item);
            }
            isSuccessAdd = this.saveBatch(toSaveList);
        }
        if (isRemoved || isSuccessAdd) {
            // 更新缓存
            List<DataAuthTableRelation> list = this.list();
            redisUtil.set(GlobalConstant.DATA_AUTH_TABLE_RELATION_CACHE_KEY, list);
        }
        return isSuccessAdd;
    }
}
