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.ThirdPartyIotEarTagClient;

/**
 * 第三方<strong>耳标温度步数</strong>数据同步编排。
 */
@Service
public class YakEarTagSyncService
{
    private final AtomicBoolean syncing = new AtomicBoolean(false);

    @Autowired
    private ThirdPartyIotEarTagClient thirdPartyIotEarTagClient;

    @Autowired
    private YakEarTagSyncTxService yakEarTagSyncTxService;

    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(
                    thirdPartyIotEarTagClient.fetchIncremental(
                            syncQuery.getStartTime(), syncQuery.getEndTime(), syncQuery.getUpdatedAfter()),
                    yakEarTagSyncTxService::persistEarTag,
                    dto -> dto != null && dto.getId() != null ? String.valueOf(dto.getId()) : null);
        }
        finally
        {
            syncing.set(false);
        }
    }
}
