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

import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.industryservice.domain.dto.YakDiseaseWarningDto;
import com.ruoyi.web.modules.industryservice.domain.vo.YakAssetSyncResultVo;
import com.ruoyi.web.modules.industryservice.support.ThirdPartyYakAlertClient;
import com.ruoyi.web.modules.industryservice.support.YakDiseaseWarningRules;

/**
 * 第三方疾病预警同步编排。
 */
@Service
public class YakDiseaseWarningSyncService
{
    private final AtomicBoolean syncing = new AtomicBoolean(false);

    @Autowired
    private ThirdPartyYakAlertClient thirdPartyYakAlertClient;

    @Autowired
    private YakDiseaseWarningSyncTxService syncTxService;

    public YakAssetSyncResultVo syncFromThirdParty()
    {
        if (!syncing.compareAndSet(false, true))
        {
            throw new ServiceException(YakDiseaseWarningRules.MSG_SYNC_IN_PROGRESS);
        }
        try
        {
            List<YakDiseaseWarningDto> alerts;
            try
            {
                alerts = thirdPartyYakAlertClient.fetchAlerts();
            }
            catch (ServiceException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw new ServiceException("第三方服务不可用：" + e.getMessage());
            }
            YakAssetSyncResultVo result = new YakAssetSyncResultVo();
            Date syncTime = new Date();
            if (CollectionUtils.isEmpty(alerts))
            {
                result.setSyncTime(syncTime);
                return result;
            }
            for (YakDiseaseWarningDto dto : alerts)
            {
                try
                {
                    boolean inserted = syncTxService.persistAlert(dto, syncTime);
                    if (inserted)
                    {
                        result.setInsertCount(result.getInsertCount() + 1);
                    }
                    else
                    {
                        result.setUpdateCount(result.getUpdateCount() + 1);
                    }
                }
                catch (Exception e)
                {
                    result.setFailCount(result.getFailCount() + 1);
                    String key = dto != null && StringUtils.isNotEmpty(dto.getExternalAlertId())
                            ? dto.getExternalAlertId()
                            : "?";
                    result.getFailMessages().add(key + ": " + e.getMessage());
                }
            }
            result.setSyncTime(syncTime);
            return result;
        }
        finally
        {
            syncing.set(false);
        }
    }
}
