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

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 com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.industrypolicy.support.PastureRules;
import com.ruoyi.web.modules.industryservice.domain.BizFarmingBatch;
import com.ruoyi.web.modules.industryservice.domain.dto.OpenFarmingBatchDto;
import com.ruoyi.web.modules.industryservice.mapper.BizFarmEnclosureMapper;
import com.ruoyi.web.modules.industryservice.mapper.BizFarmingBatchMapper;
import com.ruoyi.web.modules.industryservice.mapper.BizPastureMapper;
import com.ruoyi.web.modules.industryservice.support.FarmingSyncRules;
import com.ruoyi.web.modules.industryservice.support.FarmingSyncSupport;

/**
 * 单条养殖批次同步事务服务。
 * <p>
 * 将 {@link OpenFarmingBatchDto} 映射为 {@link BizFarmingBatch}，按 {@code external_id} upsert。
 * 批次编号 {@code batchNo} 与入栏建档接口的 {@code entryCycle} 对应，供牦牛资产关联查询。
 * </p>
 */
@Service
public class FarmingBatchSyncTxService
{
    @Autowired
    private BizFarmingBatchMapper farmingBatchMapper;

    @Autowired
    private BizPastureMapper pastureMapper;

    @Autowired
    private BizFarmEnclosureMapper farmEnclosureMapper;

    /**
     * 持久化一条第三方养殖批次。
     *
     * @param dto      开放接口单条批次
     * @param syncTime 本次同步批次时间
     * @return {@code true}=新增，{@code false}=更新
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public boolean persistBatch(OpenFarmingBatchDto dto, Date syncTime)
    {
        if (dto == null || dto.getId() == null)
        {
            throw new ServiceException(FarmingSyncRules.MSG_EXTERNAL_ID_REQUIRED);
        }
        if (StringUtils.isEmpty(dto.getBatchNo()))
        {
            throw new ServiceException("批次编号不能为空");
        }
        BizFarmingBatch row = new BizFarmingBatch();
        row.setExternalId(dto.getId());
        row.setBatchNo(dto.getBatchNo().trim());
        row.setBatchName(StringUtils.trim(dto.getBatchName()));
        row.setFarmExternalId(dto.getFarmId());
        row.setPastureId(FarmingSyncSupport.resolvePastureId(pastureMapper, dto.getFarmId()));
        row.setEnclosureExternalId(dto.getEnclosureId());
        row.setEnclosureId(FarmingSyncSupport.resolveEnclosureId(farmEnclosureMapper, dto.getEnclosureId()));
        row.setPlanExternalId(dto.getPlanId());
        row.setCattleVariety(StringUtils.trim(dto.getCattleVariety()));
        row.setPlannedQuantity(dto.getPlannedQuantity());
        row.setEntryQuantity(dto.getEntryQuantity());
        row.setCurrentQuantity(dto.getCurrentQuantity());
        row.setLeaveQuantity(dto.getLeaveQuantity());
        row.setDeathQuantity(dto.getDeathQuantity());
        row.setManagerUserId(dto.getManagerUserId());
        row.setBatchStatus(StringUtils.trim(dto.getBatchStatus()));
        row.setRemark(StringUtils.trim(dto.getRemark()));
        row.setDataSource(FarmingSyncSupport.DATA_SOURCE_THIRD_PARTY);
        row.setLastSyncTime(syncTime);
        row.setDelFlag(PastureRules.DEL_FLAG_NORMAL);
        row.setUpdateBy(FarmingSyncSupport.SYNC_BY);

        Date now = syncTime != null ? syncTime : new Date();
        row.setStartTime(FarmingSyncSupport.parseThirdPartyTime(dto.getStartTime(), null));
        row.setEndTime(FarmingSyncSupport.parseThirdPartyTime(dto.getEndTime(), null));
        row.setExternalCreateTime(FarmingSyncSupport.parseThirdPartyTime(dto.getCreateTime(), now));

        BizFarmingBatch existing = farmingBatchMapper.selectBizFarmingBatchByExternalId(dto.getId());
        if (existing == null)
        {
            row.setCreateBy(FarmingSyncSupport.SYNC_BY);
            row.setCreateTime(row.getExternalCreateTime() != null ? row.getExternalCreateTime() : now);
            farmingBatchMapper.insertBizFarmingBatch(row);
            return true;
        }
        row.setId(existing.getId());
        row.setCreateTime(existing.getCreateTime());
        row.setUpdateTime(now);
        farmingBatchMapper.updateBizFarmingBatchFromSync(row);
        return false;
    }
}
