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.OpenFarmDto;
import com.ruoyi.web.modules.industryservice.domain.vo.YakAssetSyncResultVo;
import com.ruoyi.web.modules.industryservice.support.PastureSyncRules;
import com.ruoyi.web.modules.industryservice.support.ThirdPartyFarmClient;

/**
 * 第三方<strong>养殖场</strong>同步编排。
 * <p>
 * 接口：{@code GET /open-api/v1/farming/farms} → 落库 {@code biz_pasture}。
 * 既可由牧场管理页 {@code POST /dataModel/pasture/sync} 单独触发，
 * 也是 {@link LivestockFinanceMasterSyncService} 全量同步的<strong>第一步</strong>。
 * </p>
 * <p>
 * 牦牛/圈舍/批次等数据的 {@code pasture_id} 解析均依赖本步骤先写入养殖场台账。
 * </p>
 */
@Service
public class PastureSyncService
{
    private final AtomicBoolean syncing = new AtomicBoolean(false);

    @Autowired
    private ThirdPartyFarmClient thirdPartyFarmClient;

    @Autowired
    private PastureSyncTxService pastureSyncTxService;

    /**
     * 从第三方拉取全量养殖场并 upsert。
     */
    public YakAssetSyncResultVo syncFromThirdParty()
    {
        if (!syncing.compareAndSet(false, true))
        {
            throw new ServiceException(PastureSyncRules.MSG_SYNC_IN_PROGRESS);
        }
        try
        {
            List<OpenFarmDto> farms;
            try
            {
                farms = thirdPartyFarmClient.fetchAllFarms();
            }
            catch (ServiceException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw new ServiceException("第三方服务不可用：" + e.getMessage());
            }
            YakAssetSyncResultVo result = new YakAssetSyncResultVo();
            Date syncTime = new Date();
            if (CollectionUtils.isEmpty(farms))
            {
                result.setSyncTime(syncTime);
                return result;
            }
            for (OpenFarmDto dto : farms)
            {
                try
                {
                    boolean inserted = pastureSyncTxService.persistFarm(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 && dto.getId() != null
                            ? String.valueOf(dto.getId())
                            : StringUtils.nvl(dto != null ? dto.getFarmName() : null, "?");
                    result.getFailMessages().add(key + ": " + e.getMessage());
                }
            }
            result.setSyncTime(syncTime);
            return result;
        }
        finally
        {
            syncing.set(false);
        }
    }
}
