package com.zcloud.zcGbsServicer.service;

import com.alibaba.cola.dto.MultiResponse;
import com.jjb.saas.framework.repository.basedo.BaseDO;
import com.zcloud.gbscommon.zclouduser.facade.ZcloudUserFacade;
import com.zcloud.gbscommon.zclouduser.response.ZcloudUserCo;
import com.zcloud.zcGbsServicer.persistence.repository.AlarmUserRepository;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class FireAlarmUserResolver {

    @DubboReference(check = false)
    private ZcloudUserFacade zcloudUserFacade;

    private final AlarmUserRepository alarmUserRepository;

    public Map<Long, ZcloudUserCo> getUserMap(Collection<Long> userIds) {
        if (userIds == null || userIds.isEmpty()) {
            return Collections.emptyMap();
        }
        MultiResponse<ZcloudUserCo> response;
        try {
            response = zcloudUserFacade.listByUserIds(userIds);
        }
        catch (Exception ex) {
            return Collections.emptyMap();
        }
        if (response == null || response.getData() == null || response.getData().isEmpty()) {
            return Collections.emptyMap();
        }
        Map<Long, ZcloudUserCo> userMap = new LinkedHashMap<>();
        for (ZcloudUserCo user : response.getData()) {
            if (user != null && user.getId() != null) {
                userMap.put(user.getId(), user);
            }
        }
        return userMap;
    }

    /**
     * 从 alarm 库 user 视图查询用户所属 tenant_id。
     */
    public Long resolveUserTenantId(Long userId) {
        return alarmUserRepository.getTenantIdByUserId(userId);
    }

    public void applyLocalUserTenant(BaseDO dataObject, Long localUserId) {
        Long tenantId = resolveUserTenantId(localUserId);
        if (tenantId == null) {
            return;
        }
        dataObject.setTenantId(tenantId);
        dataObject.setOrgId(tenantId);
    }
}
