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.BizEnvMonitoringRecord;
import com.ruoyi.web.modules.industryservice.domain.dto.OpenEnvMonitoringDto;
import com.ruoyi.web.modules.industryservice.mapper.BizEnvMonitoringRecordMapper;
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 OpenEnvMonitoringDto} 映射为 {@link BizEnvMonitoringRecord}，
 * 按 {@code external_id} upsert 到 {@code biz_env_monitoring_record}。
 * </p>
 */
@Service
public class EnvMonitoringSyncTxService
{
    @Autowired
    private BizEnvMonitoringRecordMapper envMonitoringRecordMapper;

    @Autowired
    private BizPastureMapper pastureMapper;

    @Autowired
    private BizFarmEnclosureMapper enclosureMapper;

    /**
     * 持久化一条第三方环境监测记录。
     *
     * @return {@code true}=新增，{@code false}=更新
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public boolean persistEnvMonitoring(OpenEnvMonitoringDto dto, Date syncTime)
    {
        if (dto == null || dto.getId() == null)
        {
            throw new ServiceException(FarmingSyncRules.MSG_EXTERNAL_ID_REQUIRED);
        }
        Date now = syncTime != null ? syncTime : new Date();

        BizEnvMonitoringRecord row = new BizEnvMonitoringRecord();
        row.setExternalId(dto.getId());
        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.setTemperature(FarmingSyncSupport.toDecimal(dto.getTemperature()));
        row.setHumidity(FarmingSyncSupport.toDecimal(dto.getHumidity()));
        row.setAmmonia(FarmingSyncSupport.toDecimal(dto.getAmmonia()));
        row.setH2s(FarmingSyncSupport.toDecimal(dto.getH2s()));
        row.setMonitoringTime(FarmingSyncSupport.parseThirdPartyTime(dto.getMonitoringTime(), now));
        row.setDataSource(FarmingSyncSupport.DATA_SOURCE_THIRD_PARTY);
        row.setLastSyncTime(syncTime);
        row.setDelFlag(PastureRules.DEL_FLAG_NORMAL);
        row.setUpdateBy(FarmingSyncSupport.SYNC_BY);

        BizEnvMonitoringRecord existing = envMonitoringRecordMapper.selectByExternalId(dto.getId());
        if (existing == null)
        {
            row.setCreateBy(FarmingSyncSupport.SYNC_BY);
            row.setCreateTime(now);
            envMonitoringRecordMapper.insertBizEnvMonitoringRecord(row);
            return true;
        }
        row.setId(existing.getId());
        row.setCreateTime(existing.getCreateTime());
        row.setUpdateTime(now);
        envMonitoringRecordMapper.updateBizEnvMonitoringRecordFromSync(row);
        return false;
    }
}
