package com.usky.vpp.util;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usky.vpp.domain.VppResourcePoint;
import com.usky.vpp.domain.VppSite;
import com.usky.vpp.mapper.VppSiteMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 站点与资源点关联查询辅助
 */
@Component
public class VppSiteResourceHelper {

    private static VppSiteResourceHelper instance;

    @Autowired
    private VppSiteMapper siteMapper;

    @PostConstruct
    void register() {
        instance = this;
    }

    public static Integer resolveTenantIdByUnResourceId(String unResourceId) {
        if (instance == null || !StringUtils.hasText(unResourceId)) {
            return null;
        }
        VppSite site = instance.siteMapper.selectOne(new LambdaQueryWrapper<VppSite>()
                .eq(VppSite::getUnResourceId, unResourceId)
                .last("LIMIT 1"));
        return site != null ? site.getTenantId() : null;
    }

    public Map<Long, VppSite> loadSiteMap(List<VppResourcePoint> resources) {
        if (resources == null || resources.isEmpty()) {
            return Collections.emptyMap();
        }
        List<Long> siteIds = resources.stream()
                .map(VppResourcePoint::getSiteId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
        if (siteIds.isEmpty()) {
            return Collections.emptyMap();
        }
        return siteMapper.selectBatchIds(siteIds).stream()
                .filter(site -> !VppAuditHelper.isDeleted(site.getDeleteFlag()))
                .collect(Collectors.toMap(VppSite::getId, site -> site, (a, b) -> a));
    }

    public Long resolveCustomerId(VppResourcePoint resource, Map<Long, VppSite> siteMap) {
        if (resource == null || resource.getSiteId() == null || siteMap == null) {
            return null;
        }
        VppSite site = siteMap.get(resource.getSiteId());
        return site != null ? site.getCustomerId() : null;
    }
}
