package com.ruoyi.web.modules.industryservice.service;

import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.industryservice.domain.vo.YakAssetSyncResultVo;
import com.ruoyi.web.modules.industryservice.support.FarmingDataSyncExecutor;
import com.ruoyi.web.modules.industryservice.support.FarmingSyncRules;
import com.ruoyi.web.modules.industryservice.support.IotSyncSupport.SyncQuery;
import com.ruoyi.web.modules.industryservice.support.ThirdPartyIotEnvMonitoringClient;

/**
 * 第三方<strong>环境监测</strong>数据同步编排。
 */
@Service
public class EnvMonitoringSyncService
{
    private final AtomicBoolean syncing = new AtomicBoolean(false);

    @Autowired
    private ThirdPartyIotEnvMonitoringClient thirdPartyIotEnvMonitoringClient;

    @Autowired
    private EnvMonitoringSyncTxService envMonitoringSyncTxService;

    /** 按编排层解析的窗口同步（全量或增量） */
    public YakAssetSyncResultVo syncIncremental(SyncQuery query)
    {
        if (!syncing.compareAndSet(false, true))
        {
            throw new ServiceException(FarmingSyncRules.MSG_SYNC_IN_PROGRESS);
        }
        try
        {
            SyncQuery syncQuery = query != null ? query : SyncQuery.fullSync();
            return FarmingDataSyncExecutor.execute(
                    thirdPartyIotEnvMonitoringClient.fetchIncremental(
                            syncQuery.getStartTime(), syncQuery.getEndTime(), syncQuery.getUpdatedAfter()),
                    envMonitoringSyncTxService::persistEnvMonitoring,
                    dto -> dto != null && dto.getId() != null ? String.valueOf(dto.getId()) : null);
        }
        finally
        {
            syncing.set(false);
        }
    }
}
