package com.usky.vpp.service.impl;

import com.usky.vpp.config.VppUnProperties;
import com.usky.vpp.config.VppUnPropertiesRegistry;
import com.usky.vpp.config.VppUnTenantContext;
import com.usky.vpp.service.VppUnIntegrationService;
import com.usky.vpp.service.VppUnRegisterTaskService;
import com.usky.vpp.service.VppUnReportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class VppUnRegisterTaskServiceImpl implements VppUnRegisterTaskService {

    private static final Logger log = LoggerFactory.getLogger(VppUnRegisterTaskServiceImpl.class);

    @Autowired
    private VppUnPropertiesRegistry propertiesRegistry;

    @Autowired
    private VppUnIntegrationService integrationService;

    @Autowired
    private VppUnReportService reportService;

    @Override
    public void registerUn(Integer tenantId) {
        log.info("registerUn start, tenantId={}", tenantId);
        VppUnProperties properties = propertiesRegistry.get(tenantId);
        if (properties == null) {
            log.warn("registerUn skipped: tenantId={} 未配置运管平台 UN 对接信息", tenantId);
            return;
        }
        if (!properties.isOutboundActive()) {
            log.info("registerUn skipped: outbound not active, tenantId={}", tenantId);
            return;
        }
        VppUnTenantContext.runWithTenant(tenantId, () -> {
            try {
                integrationService.refreshToken();
                integrationService.loadPersistedRegistrationId();
                boolean reregister = StringUtils.hasText(properties.getRegistrationId());
                if (reregister) {
                    log.info("租户 {} 使用已持久化的 registrationID={} 向 UN 重新注册",
                            tenantId, properties.getRegistrationId());
                }
                integrationService.register();
                log.info("租户 {} {} UN 完成 registrationID={}",
                        tenantId, reregister ? "重新注册" : "注册", properties.getRegistrationId());
            } catch (Exception ex) {
                log.warn("租户 {} UN 注册失败: {}", tenantId, ex.getMessage());
            }
            try {
                reportService.submitRegisterReport();
            } catch (Exception ex) {
                log.warn("租户 {} RegisterReport元数据报告请求 提交失败: {}", tenantId, ex.getMessage());
            }
            try {
                reportService.submitMomentDataReport();
            } catch (Exception ex) {
                log.warn("租户 {} MomentDataReport实时数据报告请求 提交失败: {}", tenantId, ex.getMessage());
            }
        });
    }
}
