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.BizFarmEnclosure;
import com.ruoyi.web.modules.industryservice.domain.dto.OpenFarmEnclosureDto;
import com.ruoyi.web.modules.industryservice.mapper.BizFarmEnclosureMapper;
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 OpenFarmEnclosureDto}（OpenFarmEnclosureVo）映射为 {@link BizFarmEnclosure}，
 * 按 {@code external_id} upsert 到 {@code biz_farm_enclosure}。
 * 每条记录独立事务（REQUIRES_NEW），避免批量同步中单条失败拖垮整批。
 * </p>
 *
 * <h3>关联解析</h3>
 * <ul>
 *   <li>{@code farmId} → {@code farm_external_id}，并尝试解析本地 {@code pasture_id}</li>
 *   <li>若养殖场尚未同步，{@code pasture_id} 暂为 null，后续全量同步会先补全养殖场</li>
 * </ul>
 */
@Service
public class FarmEnclosureSyncTxService
{
    @Autowired
    private BizFarmEnclosureMapper farmEnclosureMapper;

    @Autowired
    private BizPastureMapper pastureMapper;

    /**
     * 持久化一条第三方圈舍记录。
     *
     * @param dto      OpenFarmEnclosureVo 单条数据
     * @param syncTime 本次同步批次时间，写入 last_sync_time
     * @return {@code true}=新增，{@code false}=更新
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public boolean persistEnclosure(OpenFarmEnclosureDto dto, Date syncTime)
    {
        if (dto == null || dto.getId() == null)
        {
            throw new ServiceException(FarmingSyncRules.MSG_EXTERNAL_ID_REQUIRED);
        }
        if (StringUtils.isEmpty(dto.getEnclosureName()))
        {
            throw new ServiceException("圈舍名称不能为空");
        }
        BizFarmEnclosure row = new BizFarmEnclosure();
        row.setExternalId(dto.getId());
        row.setFarmExternalId(dto.getFarmId());
        // 依赖 biz_pasture.external_id = farmId，需先同步养殖场
        row.setPastureId(FarmingSyncSupport.resolvePastureId(pastureMapper, dto.getFarmId()));
        row.setFarmName(StringUtils.trim(dto.getFarmName()));
        row.setEnclosureName(dto.getEnclosureName().trim());
        row.setEnclosureNo(StringUtils.trim(dto.getEnclosureNo()));
        row.setQrCode(StringUtils.trim(dto.getQrCode()));
        row.setSupervisor(StringUtils.trim(dto.getSupervisor()));
        row.setIntroduction(StringUtils.trim(dto.getIntroduction()));
        // enclosureStatus: 0使用中 1空闲 2维护中
        row.setEnclosureStatus(StringUtils.trim(dto.getEnclosureStatus()));
        row.setAreaType(StringUtils.trim(dto.getAreaType()));
        row.setCattleQuantity(dto.getCattleQuantity());
        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.setExternalCreateTime(FarmingSyncSupport.parseThirdPartyTime(dto.getCreateTime(), now));

        BizFarmEnclosure existing = farmEnclosureMapper.selectBizFarmEnclosureByExternalId(dto.getId());
        if (existing == null)
        {
            row.setCreateBy(FarmingSyncSupport.SYNC_BY);
            row.setCreateTime(row.getExternalCreateTime() != null ? row.getExternalCreateTime() : now);
            farmEnclosureMapper.insertBizFarmEnclosure(row);
            return true;
        }
        row.setId(existing.getId());
        row.setCreateTime(existing.getCreateTime());
        row.setUpdateTime(now);
        farmEnclosureMapper.updateBizFarmEnclosureFromSync(row);
        return false;
    }
}
