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.BizYakWeighingRecord;
import com.ruoyi.web.modules.industryservice.domain.dto.OpenWeighingDto;
import com.ruoyi.web.modules.industryservice.mapper.BizFarmEnclosureMapper;
import com.ruoyi.web.modules.industryservice.mapper.BizPastureMapper;
import com.ruoyi.web.modules.industryservice.mapper.BizYakAssetMapper;
import com.ruoyi.web.modules.industryservice.mapper.BizYakWeighingRecordMapper;
import com.ruoyi.web.modules.industryservice.support.FarmingSyncRules;
import com.ruoyi.web.modules.industryservice.support.FarmingSyncSupport;

/**
 * 单条牛只称重数据同步事务服务。
 * <p>
 * 将 {@link OpenWeighingDto} 映射为 {@link BizYakWeighingRecord}，
 * 按 {@code external_id} upsert 到 {@code biz_yak_weighing_record}。
 * </p>
 */
@Service
public class YakWeighingSyncTxService
{
    @Autowired
    private BizYakWeighingRecordMapper weighingRecordMapper;

    @Autowired
    private BizPastureMapper pastureMapper;

    @Autowired
    private BizFarmEnclosureMapper enclosureMapper;

    @Autowired
    private BizYakAssetMapper yakAssetMapper;

    /**
     * 持久化一条第三方称重记录。
     *
     * @return {@code true}=新增，{@code false}=更新
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public boolean persistWeighing(OpenWeighingDto dto, Date syncTime)
    {
        if (dto == null || dto.getId() == null)
        {
            throw new ServiceException(FarmingSyncRules.MSG_EXTERNAL_ID_REQUIRED);
        }
        Date now = syncTime != null ? syncTime : new Date();
        String earTagNumber = StringUtils.isNotEmpty(dto.getEarTagNumber()) ? dto.getEarTagNumber().trim() : null;
        String yakNo = FarmingSyncSupport.firstNonBlank(dto.getEarTagNumber(), dto.getCattleNo());

        BizYakWeighingRecord row = new BizYakWeighingRecord();
        row.setExternalId(dto.getId());
        row.setEarTagNumber(earTagNumber);
        row.setCattleExternalId(dto.getCattleId());
        row.setYakNo(yakNo);
        row.setYakAssetId(FarmingSyncSupport.resolveYakAssetId(yakAssetMapper, dto.getCattleId(),
                dto.getEarTagNumber(), dto.getCattleNo()));
        row.setFarmExternalId(dto.getFarmId());
        row.setFarmName(StringUtils.trim(dto.getFarmName()));
        row.setPastureId(FarmingSyncSupport.resolvePastureId(pastureMapper, dto.getFarmId()));
        row.setEnclosureExternalId(dto.getEnclosureId());
        row.setEnclosureName(StringUtils.trim(dto.getEnclosureName()));
        row.setEnclosureId(FarmingSyncSupport.resolveEnclosureId(enclosureMapper, dto.getEnclosureId()));
        row.setWeightKg(FarmingSyncSupport.parseDecimal(dto.getWeight()));
        row.setWeighingTime(FarmingSyncSupport.parseThirdPartyTime(dto.getWeighingTime(), now));
        row.setDataSource(FarmingSyncSupport.DATA_SOURCE_THIRD_PARTY);
        row.setLastSyncTime(syncTime);
        row.setDelFlag(PastureRules.DEL_FLAG_NORMAL);
        row.setUpdateBy(FarmingSyncSupport.SYNC_BY);

        BizYakWeighingRecord existing = weighingRecordMapper.selectByExternalId(dto.getId());
        if (existing == null)
        {
            row.setCreateBy(FarmingSyncSupport.SYNC_BY);
            row.setCreateTime(now);
            weighingRecordMapper.insertBizYakWeighingRecord(row);
            return true;
        }
        row.setId(existing.getId());
        row.setCreateTime(existing.getCreateTime());
        row.setUpdateTime(now);
        weighingRecordMapper.updateBizYakWeighingRecordFromSync(row);
        return false;
    }
}
