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.common.utils.StringUtils;
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.ThirdPartyIotCollarLocationClient;

/**
 * 第三方<strong>牦牛定位项圈</strong>数据同步编排。
 */
@Service
public class YakCollarLocationSyncService
{
    private final AtomicBoolean syncing = new AtomicBoolean(false);

    @Autowired
    private ThirdPartyIotCollarLocationClient thirdPartyIotCollarLocationClient;

    @Autowired
    private YakCollarLocationSyncTxService yakCollarLocationSyncTxService;

    /** 按编排层解析的窗口同步（全量或增量） */
    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(
                    thirdPartyIotCollarLocationClient.fetchIncremental(
                            syncQuery.getStartTime(), syncQuery.getEndTime(), syncQuery.getUpdatedAfter()),
                    yakCollarLocationSyncTxService::persistCollarLocation,
                    dto -> dto != null ? StringUtils.nvl(dto.getCattleNo(), "?") + "@"
                            + StringUtils.nvl(dto.getReportTime(), "?") : null);
        }
        finally
        {
            syncing.set(false);
        }
    }
}
