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

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.industryservice.domain.*;
import com.ruoyi.web.modules.industryservice.domain.vo.LivestockFinanceSyncResultVo;
import com.ruoyi.web.modules.industryservice.domain.vo.YakAssetDetailVo;
import com.ruoyi.web.modules.industryservice.domain.vo.YakAssetGrowthChartVo;
import com.ruoyi.web.modules.industryservice.mapper.*;
import com.ruoyi.web.modules.industryservice.service.IBizYakAssetService;
import com.ruoyi.web.modules.industryservice.service.LivestockFinanceMasterSyncService;
import com.ruoyi.web.modules.industryservice.service.YakAssetGrowthLiveService;
import com.ruoyi.web.modules.industryservice.service.YakAssetPhysioLiveService;
import com.ruoyi.web.modules.industryservice.support.YakAssetRules;
import com.ruoyi.web.modules.industryservice.support.YakAssetValidation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * 牦牛资产档案业务实现。
 * <p>
 * 查询侧以本地库为主；详情「个体生理」与「生长性状（体重）」委托 IoT 开放接口实时读取。
 * 繁殖/饲喂子表仍从本地子表查询。
 * </p>
 */
@Service
public class BizYakAssetServiceImpl implements IBizYakAssetService
{
    @Autowired
    private BizYakAssetMapper bizYakAssetMapper;

    @Autowired
    private YakAssetPhysioLiveService yakAssetPhysioLiveService;

    @Autowired
    private YakAssetGrowthLiveService yakAssetGrowthLiveService;

    @Autowired
    private BizYakReproductionRecordMapper reproductionRecordMapper;

    @Autowired
    private BizYakFeedingRecordMapper feedingRecordMapper;

    @Autowired
    private LivestockFinanceMasterSyncService livestockFinanceMasterSyncService;

    @Override
    public List<BizYakAsset> selectBizYakAssetList(BizYakAsset query)
    {
        if (query == null)
        {
            query = new BizYakAsset();
        }
        query.setKeyword(YakAssetValidation.trimKeyword(query.getKeyword()));
        YakAssetValidation.validateAssetStatus(query.getAssetStatus());
        return bizYakAssetMapper.selectBizYakAssetList(query);
    }

    @Override
    public YakAssetDetailVo selectDetailById(Long id)
    {
        BizYakAsset asset = requireActiveAsset(id);
        return buildDetail(asset);
    }

    @Override
    public YakAssetDetailVo selectDetailByYakNo(String yakNo)
    {
        if (StringUtils.isEmpty(yakNo))
        {
            throw new ServiceException("牦牛编号不能为空");
        }
        BizYakAsset asset = bizYakAssetMapper.selectBizYakAssetByYakNo(yakNo.trim());
        if (asset == null)
        {
            throw new ServiceException("档案不存在或已删除");
        }
        return buildDetail(asset);
    }

    @Override
    public List<BizYakPhysioSeries> selectPhysioChart(Long id, Integer days)
    {
        BizYakAsset asset = requireActiveAsset(id);
        int d = days == null ? YakAssetRules.DEFAULT_PHYSIO_DAYS : days;
        YakAssetValidation.validatePhysioDays(d);
        return yakAssetPhysioLiveService.fetchPhysioChart(asset, d);
    }

    @Override
    public YakAssetGrowthChartVo selectGrowthChart(Long id, String metric)
    {
        BizYakAsset asset = requireActiveAsset(id);
        String m = StringUtils.isEmpty(metric) ? YakAssetRules.METRIC_WEIGHT : metric.trim().toLowerCase();
        YakAssetValidation.validateGrowthMetric(m);
        return yakAssetGrowthLiveService.fetchGrowthChart(asset, m);
    }

    /**
     * 牧业金融生物资产全量同步（含基础数据 + 入栏建档）。
     *
     * @see LivestockFinanceMasterSyncService#syncAll()
     */
    @Override
    public LivestockFinanceSyncResultVo syncFromThirdParty()
    {
        return livestockFinanceMasterSyncService.syncAll();
    }

    private YakAssetDetailVo buildDetail(BizYakAsset asset)
    {
        Long yakAssetId = asset.getId();
        YakAssetDetailVo vo = new YakAssetDetailVo();
        // 覆盖 asset 上 realtimeTemp / realtimeSteps / envTemp / physioCollectTime
        yakAssetPhysioLiveService.enrichRealtimePhysio(asset);
        vo.setAsset(asset);
        // 曲线由独立接口 physioChart 加载；详情节点保留空列表兼容旧前端结构
        vo.setPhysioSeries(Collections.emptyList());
        vo.setGrowthRecords(yakAssetGrowthLiveService.fetchGrowthRecords(asset));
        vo.setReproductionRecords(reproductionRecordMapper.selectByYakAssetId(yakAssetId));
        vo.setFeedingRecords(feedingRecordMapper.selectByYakAssetId(yakAssetId));
        return vo;
    }

    /** 校验档案存在且未逻辑删除 */
    private BizYakAsset requireActiveAsset(Long id)
    {
        if (id == null)
        {
            throw new ServiceException("主键不能为空");
        }
        BizYakAsset asset = bizYakAssetMapper.selectBizYakAssetById(id);
        if (asset == null)
        {
            throw new ServiceException("档案不存在或已删除");
        }
        return asset;
    }
}
