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.BizFarmingPlan;
import com.ruoyi.web.modules.industryservice.domain.dto.OpenFarmingPlanDto;
import com.ruoyi.web.modules.industryservice.mapper.BizFarmEnclosureMapper;
import com.ruoyi.web.modules.industryservice.mapper.BizFarmingPlanMapper;
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 OpenFarmingPlanDto}（OpenFarmingPlanVo）映射为 {@link BizFarmingPlan}，
 * 按 {@code external_id} upsert。
 * </p>
 *
 * <h3>关联解析</h3>
 * <ul>
 *   <li>{@code farmId} → {@code pasture_id}</li>
 *   <li>{@code farmEnclosureId} → {@code enclosure_id}（需圈舍已同步）</li>
 *   <li>{@code planStatus}：0草稿 1已下发 2执行中 3已完成 4已取消（以第三方字典为准）</li>
 * </ul>
 */
@Service
public class FarmingPlanSyncTxService
{
    @Autowired
    private BizFarmingPlanMapper farmingPlanMapper;

    @Autowired
    private BizPastureMapper pastureMapper;

    @Autowired
    private BizFarmEnclosureMapper farmEnclosureMapper;

    /**
     * 持久化一条第三方生产计划。
     *
     * @param dto      OpenFarmingPlanVo 单条数据
     * @param syncTime 本次同步批次时间
     * @return {@code true}=新增，{@code false}=更新
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public boolean persistPlan(OpenFarmingPlanDto dto, Date syncTime)
    {
        if (dto == null || dto.getId() == null)
        {
            throw new ServiceException(FarmingSyncRules.MSG_EXTERNAL_ID_REQUIRED);
        }
        BizFarmingPlan row = new BizFarmingPlan();
        row.setExternalId(dto.getId());
        row.setFarmExternalId(dto.getFarmId());
        row.setPastureId(FarmingSyncSupport.resolvePastureId(pastureMapper, dto.getFarmId()));
        row.setRegionExternalId(dto.getRegionId());
        row.setRegionName(StringUtils.trim(dto.getRegionName()));
        row.setEnclosureExternalId(dto.getFarmEnclosureId());
        row.setEnclosureId(FarmingSyncSupport.resolveEnclosureId(farmEnclosureMapper, dto.getFarmEnclosureId()));
        row.setPlanBatch(StringUtils.trim(dto.getPlanBatch()));
        row.setPlanName(StringUtils.trim(dto.getPlanName()));
        row.setPlanStatus(StringUtils.trim(dto.getPlanStatus()));
        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));

        BizFarmingPlan existing = farmingPlanMapper.selectBizFarmingPlanByExternalId(dto.getId());
        if (existing == null)
        {
            row.setCreateBy(FarmingSyncSupport.SYNC_BY);
            row.setCreateTime(now);
            farmingPlanMapper.insertBizFarmingPlan(row);
            return true;
        }
        row.setId(existing.getId());
        row.setCreateTime(existing.getCreateTime());
        row.setUpdateTime(now);
        farmingPlanMapper.updateBizFarmingPlanFromSync(row);
        return false;
    }
}
