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

import java.util.Date;
import java.util.List;
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.web.modules.industryservice.domain.dto.YakAssetBundleDto;
import com.ruoyi.web.modules.industryservice.domain.vo.YakAssetSyncResultVo;
import com.ruoyi.web.modules.industryservice.support.ThirdPartyYakClient;
import com.ruoyi.web.modules.industryservice.support.YakAssetStatusMapper;

/**
 * 第三方档案同步编排（防并发重入；单头独立事务）。
 */
@Service
public class YakAssetSyncService
{
    private final Object syncLock = new Object();

    @Autowired
    private ThirdPartyYakClient thirdPartyYakClient;

    @Autowired
    private YakAssetBundleSyncTxService bundleSyncTxService;

    public YakAssetSyncResultVo syncFromThirdParty()
    {
        synchronized (syncLock)
        {
            List<YakAssetBundleDto> bundles;
            try
            {
                bundles = thirdPartyYakClient.fetchAll();
            }
            catch (ServiceException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw new ServiceException("第三方服务不可用：" + e.getMessage());
            }
            YakAssetSyncResultVo result = new YakAssetSyncResultVo();
            Date syncTime = new Date();
            if (CollectionUtils.isEmpty(bundles))
            {
                result.setSyncTime(syncTime);
                return result;
            }
            for (YakAssetBundleDto bundle : bundles)
            {
                try
                {
                    boolean inserted = bundleSyncTxService.persistBundle(bundle, syncTime);
                    if (inserted)
                    {
                        result.setInsertCount(result.getInsertCount() + 1);
                    }
                    else
                    {
                        result.setUpdateCount(result.getUpdateCount() + 1);
                    }
                }
                catch (Exception e)
                {
                    result.setFailCount(result.getFailCount() + 1);
                    String yakNo = bundle != null && bundle.getAsset() != null ? bundle.getAsset().getYakNo() : "?";
                    result.getFailMessages().add(yakNo + ": " + e.getMessage());
                }
            }
            result.setSyncTime(syncTime);
            return result;
        }
    }

    public static int mapThirdPartyStatus(String code)
    {
        return YakAssetStatusMapper.mapToLocalStatus(code);
    }
}
