package com.fs.qw.cache;

import com.fs.qw.dto.QwUserDTO;
import com.fs.qw.mapper.QwUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class QwUserCacheService {

    @Autowired
    private QwUserMapper qwUserMapper;

    private Map<String, Map<String, String>> qwUserCache = new ConcurrentHashMap<>();


    @PostConstruct
    public void initCache() {
        refreshCache();
    }

    public void refreshCache() {
        List<QwUserDTO> allUsers = qwUserMapper.selectAllQwUserMapping();
        Map<String, Map<String, String>> newCache = new ConcurrentHashMap<>();

        for (QwUserDTO user : allUsers) {
            newCache.computeIfAbsent(user.getCorpId(), k -> new ConcurrentHashMap<>())
                    .put(user.getQwUserId(), user.getId());
        }

        this.qwUserCache = newCache;
    }

    // 根据qwUserId和corpId获取id
    public String getIdByQwUserIdAndCorpId(String qwUserId, String corpId) {
        Map<String, String> corpUsers = qwUserCache.get(corpId);
        return corpUsers != null ? corpUsers.get(qwUserId) : null;
    }

    public Map<String, String> batchGetIds(List<String> qwUserIds, String corpId) {
        Map<String, String> result = new HashMap<>();
        Map<String, String> corpUsers = qwUserCache.get(corpId);

        if (corpUsers != null) {
            for (String qwUserId : qwUserIds) {
                String id = corpUsers.get(qwUserId);
                if (id != null) {
                    result.put(qwUserId, id);
                }
            }
        }

        return result;
    }
}
