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

import java.util.Date;
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.LivestockFinanceSyncResultVo;

/**
 * 牧业金融生物资产<strong>全量同步编排</strong>服务。
 * <p>
 * 由 {@code POST /dataModel/yakAsset/sync} 触发，按第三方数据依赖关系<strong>严格顺序</strong>执行五段同步，
 * 确保入栏建档（牦牛资产）落库前，养殖场、圈舍、生产计划、批次等基础台账已就绪。
 * </p>
 * <p>
 * 牛只称重、耳标温度步数、定位项圈、环境监测由 {@link IotDataIncrementalSyncService} 独立定时增量同步，不在此接口内执行。
 * </p>
 *
 * <h3>同步顺序与落库表</h3>
 * <ol>
 *   <li>养殖场 → {@code biz_pasture}（{@link PastureSyncService}）</li>
 *   <li>养殖圈舍 → {@code biz_farm_enclosure}（{@link FarmEnclosureSyncService}）</li>
 *   <li>养殖生产计划 → {@code biz_farming_plan}（{@link FarmingPlanSyncService}）</li>
 *   <li>养殖批次 → {@code biz_farming_batch}（{@link FarmingBatchSyncService}）</li>
 *   <li>入栏建档 → {@code biz_yak_asset}（{@link YakAssetSyncService}）</li>
 * </ol>
 *
 * @see LivestockFinanceSyncResultVo
 * @see com.ruoyi.web.modules.industryservice.service.impl.BizYakAssetServiceImpl#syncFromThirdParty()
 */
@Service
public class LivestockFinanceMasterSyncService
{
    /** 全量同步互斥锁，防止重复点击或并发请求 */
    private final Object syncLock = new Object();

    @Autowired
    private PastureSyncService pastureSyncService;

    @Autowired
    private FarmEnclosureSyncService farmEnclosureSyncService;

    @Autowired
    private FarmingPlanSyncService farmingPlanSyncService;

    @Autowired
    private FarmingBatchSyncService farmingBatchSyncService;

    @Autowired
    private YakAssetSyncService yakAssetSyncService;

    /**
     * 执行牧业金融生物资产全量同步（五段顺序执行）。
     *
     * @return 各步骤的新增/更新/失败统计；顶层 {@code insertCount} 等字段兼容旧前端，取自入栏建档步骤
     */
    public LivestockFinanceSyncResultVo syncAll()
    {
        synchronized (syncLock)
        {
            LivestockFinanceSyncResultVo result = new LivestockFinanceSyncResultVo();
            Date syncTime = new Date();
            try
            {
                result.setPasture(pastureSyncService.syncFromThirdParty());
                result.setEnclosure(farmEnclosureSyncService.syncFromThirdParty());
                result.setPlan(farmingPlanSyncService.syncFromThirdParty());
                result.setBatch(farmingBatchSyncService.syncFromThirdParty());
                result.setYakAsset(yakAssetSyncService.syncFromThirdParty());
            }
            catch (ServiceException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw new ServiceException("牧业金融生物资产同步失败：" + e.getMessage());
            }
            result.setSyncTime(syncTime);
            return result;
        }
    }
}
