package com.cf.imes.module.system.util.redis;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.cf.imes.framework.common.util.json.JsonUtils;
import com.cf.imes.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;

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

import static com.cf.imes.module.system.dal.redis.RedisKeyConstants.OAUTH2_ACCESS_TOKEN;

/**
 * system 模块 redis处理工具
 *
 * @author Gqr
 * @since 2025/9/9 17:42
 */
@AllArgsConstructor
public class SystemRedisUtils {

    private StringRedisTemplate stringRedisTemplate;

    /**
     * 轮训redis token，移除对应部门下的用户的token
     *
     * @param deptId
     */
    public void scanAndCompareDeptAndDelToken(Long deptId) {
        // 根据keyPattern scan匹配的redis key
        List<String> matchKeys = new ArrayList<>();
        Cursor<String> cursor = stringRedisTemplate.scan(ScanOptions.scanOptions().match(String.format(OAUTH2_ACCESS_TOKEN, "*")).count(200).build());
        while (cursor.hasNext()) {
            matchKeys.add(cursor.next());
        }
        cursor.close();
        if (CollUtil.isNotEmpty(matchKeys)) {
            for (String key : matchKeys) {
                // 获取key下的用户信息
                OAuth2AccessTokenDO oAuth2AccessTokenDO = JsonUtils.parseObject(stringRedisTemplate.opsForValue().get(key), OAuth2AccessTokenDO.class);
                if (ObjectUtil.equal(deptId, oAuth2AccessTokenDO.getDeptId())) {
                    // 用户id匹配上了删除redis中的token缓存
                    stringRedisTemplate.delete(key);
                    return;
                }
            }
        }
    }
}
