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

import java.util.Collections;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.industryservice.domain.BizPasture;
import com.ruoyi.web.modules.industryservice.domain.BizYakAsset;
import com.ruoyi.web.modules.industryservice.domain.BizYakBatchRel;
import com.ruoyi.web.modules.industryservice.domain.BizYakFeedingRecord;
import com.ruoyi.web.modules.industryservice.domain.BizYakPenRel;
import com.ruoyi.web.modules.industryservice.domain.BizYakGrowthRecord;
import com.ruoyi.web.modules.industryservice.domain.BizYakPhysioSeries;
import com.ruoyi.web.modules.industryservice.domain.BizYakReproductionRecord;
import com.ruoyi.web.modules.industryservice.domain.dto.YakAssetBundleDto;
import com.ruoyi.web.modules.industryservice.mapper.BizPastureMapper;
import com.ruoyi.web.modules.industryservice.mapper.BizYakAssetMapper;
import com.ruoyi.web.modules.industryservice.mapper.BizYakBatchRelMapper;
import com.ruoyi.web.modules.industryservice.mapper.BizYakFeedingRecordMapper;
import com.ruoyi.web.modules.industryservice.mapper.BizYakPenRelMapper;
import com.ruoyi.web.modules.industryservice.support.YakAssetStatusMapper;
import com.ruoyi.web.modules.industryservice.mapper.BizYakGrowthRecordMapper;
import com.ruoyi.web.modules.industryservice.mapper.BizYakPhysioSeriesMapper;
import com.ruoyi.web.modules.industryservice.mapper.BizYakReproductionRecordMapper;
import com.ruoyi.web.modules.industryservice.support.YakAssetRules;
import com.ruoyi.web.modules.industryservice.support.YakAssetValidation;

@Service
public class YakAssetBundleSyncTxService
{
    @Autowired
    private BizYakAssetMapper bizYakAssetMapper;

    @Autowired
    private BizPastureMapper bizPastureMapper;

    @Autowired
    private BizYakPhysioSeriesMapper physioSeriesMapper;

    @Autowired
    private BizYakGrowthRecordMapper growthRecordMapper;

    @Autowired
    private BizYakReproductionRecordMapper reproductionRecordMapper;

    @Autowired
    private BizYakFeedingRecordMapper feedingRecordMapper;

    @Autowired
    private BizYakPenRelMapper penRelMapper;

    @Autowired
    private BizYakBatchRelMapper batchRelMapper;

    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public boolean persistBundle(YakAssetBundleDto bundle, Date syncTime)
    {
        if (bundle == null || bundle.getAsset() == null)
        {
            throw new ServiceException("同步数据包无效");
        }
        BizYakAsset incoming = bundle.getAsset();
        YakAssetValidation.validateYakNoForSync(incoming.getYakNo());
        String yakNo = incoming.getYakNo().trim();
        incoming.setYakNo(yakNo);
        if (incoming.getAssetStatus() == null)
        {
            incoming.setAssetStatus(YakAssetRules.ASSET_STATUS_MIN);
        }
        else
        {
            incoming.setAssetStatus(YakAssetStatusMapper.normalizeLegacyNumericStatus(incoming.getAssetStatus()));
            YakAssetValidation.validateAssetStatus(incoming.getAssetStatus());
        }
        resolvePasture(incoming, bundle);
        if (incoming.getBirthDate() != null)
        {
            incoming.setAgeMonths(YakAssetValidation.resolveAgeMonths(incoming.getBirthDate(), syncTime));
        }
        incoming.setLastSyncTime(syncTime);
        incoming.setDelFlag(YakAssetRules.DEL_FLAG_NORMAL);

        BizYakAsset existing = resolveExisting(incoming);
        Long yakAssetId;
        boolean inserted;
        if (existing == null)
        {
            bizYakAssetMapper.insertBizYakAsset(incoming);
            yakAssetId = incoming.getId();
            inserted = true;
        }
        else
        {
            incoming.setId(existing.getId());
            bizYakAssetMapper.updateBizYakAsset(incoming);
            yakAssetId = existing.getId();
            inserted = false;
        }
        replaceChildRows(yakAssetId, bundle);
        return inserted;
    }

    private BizYakAsset resolveExisting(BizYakAsset incoming)
    {
        if (incoming.getExternalId() != null)
        {
            BizYakAsset byExternal = bizYakAssetMapper.selectBizYakAssetByExternalId(incoming.getExternalId());
            if (byExternal != null)
            {
                return byExternal;
            }
        }
        return bizYakAssetMapper.selectBizYakAssetByYakNo(incoming.getYakNo());
    }

    private void resolvePasture(BizYakAsset incoming, YakAssetBundleDto bundle)
    {
        BizPasture pasture = null;
        if (bundle != null && StringUtils.isNotEmpty(bundle.getThirdPartyPastureCode()))
        {
            try
            {
                Long farmId = Long.parseLong(bundle.getThirdPartyPastureCode().trim());
                pasture = bizPastureMapper.selectBizPastureByExternalId(farmId);
            }
            catch (NumberFormatException ignored)
            {
                // 非数字编码时回退名称匹配
            }
        }
        if (pasture == null && StringUtils.isNotEmpty(incoming.getPastureName()))
        {
            pasture = bizPastureMapper.selectBizPastureByExactName(incoming.getPastureName().trim());
        }
        if (pasture != null)
        {
            incoming.setPastureId(pasture.getId());
            incoming.setPastureName(pasture.getPastureName());
        }
        else if (StringUtils.isEmpty(incoming.getPastureName()))
        {
            incoming.setPastureName("未关联");
        }
    }

    private void replaceChildRows(Long yakAssetId, YakAssetBundleDto bundle)
    {
        if (bundle.getPhysioSeries() != null)
        {
            physioSeriesMapper.deleteByYakAssetId(yakAssetId);
        }
        if (bundle.getGrowthRecords() != null)
        {
            growthRecordMapper.deleteByYakAssetId(yakAssetId);
        }
        if (bundle.getReproductionRecords() != null)
        {
            reproductionRecordMapper.deleteByYakAssetId(yakAssetId);
        }
        if (bundle.getFeedingRecords() != null)
        {
            feedingRecordMapper.deleteByYakAssetId(yakAssetId);
        }
        if (bundle.getPenRecords() != null || StringUtils.isNotEmpty(bundle.getAsset().getPenLocation()))
        {
            penRelMapper.deleteByYakAssetId(yakAssetId);
        }
        if (bundle.getBatchRecords() != null || StringUtils.isNotEmpty(bundle.getAsset().getBatchNo()))
        {
            batchRelMapper.deleteByYakAssetId(yakAssetId);
        }

        if (!CollectionUtils.isEmpty(bundle.getPhysioSeries()))
        {
            for (BizYakPhysioSeries row : bundle.getPhysioSeries())
            {
                row.setYakAssetId(yakAssetId);
            }
            physioSeriesMapper.batchInsert(bundle.getPhysioSeries());
        }
        if (!CollectionUtils.isEmpty(bundle.getGrowthRecords()))
        {
            for (BizYakGrowthRecord row : bundle.getGrowthRecords())
            {
                row.setYakAssetId(yakAssetId);
                if (row.getDataKind() == null)
                {
                    row.setDataKind(YakAssetRules.DATA_KIND_ACTUAL);
                }
            }
            growthRecordMapper.batchInsert(bundle.getGrowthRecords());
        }
        if (!CollectionUtils.isEmpty(bundle.getReproductionRecords()))
        {
            for (BizYakReproductionRecord row : bundle.getReproductionRecords())
            {
                row.setYakAssetId(yakAssetId);
                if (row.getDystociaFlag() == null)
                {
                    row.setDystociaFlag("0");
                }
            }
            reproductionRecordMapper.batchInsert(bundle.getReproductionRecords());
        }
        if (!CollectionUtils.isEmpty(bundle.getFeedingRecords()))
        {
            for (BizYakFeedingRecord row : bundle.getFeedingRecords())
            {
                row.setYakAssetId(yakAssetId);
            }
            feedingRecordMapper.batchInsert(bundle.getFeedingRecords());
        }
        if (!CollectionUtils.isEmpty(bundle.getPenRecords()))
        {
            for (BizYakPenRel row : bundle.getPenRecords())
            {
                row.setYakAssetId(yakAssetId);
            }
            penRelMapper.batchInsert(bundle.getPenRecords());
        }
        else if (StringUtils.isNotEmpty(bundle.getAsset().getPenLocation()))
        {
            BizYakPenRel pen = new BizYakPenRel();
            pen.setYakAssetId(yakAssetId);
            pen.setPenName(bundle.getAsset().getPenLocation().trim());
            penRelMapper.batchInsert(Collections.singletonList(pen));
        }
        if (!CollectionUtils.isEmpty(bundle.getBatchRecords()))
        {
            for (BizYakBatchRel row : bundle.getBatchRecords())
            {
                row.setYakAssetId(yakAssetId);
            }
            batchRelMapper.batchInsert(bundle.getBatchRecords());
        }
        else if (StringUtils.isNotEmpty(bundle.getAsset().getBatchNo()))
        {
            BizYakBatchRel batch = new BizYakBatchRel();
            batch.setYakAssetId(yakAssetId);
            batch.setBatchNo(bundle.getAsset().getBatchNo().trim());
            batchRelMapper.batchInsert(Collections.singletonList(batch));
        }
    }
}
