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.industryservice.domain.BizPasture;
import com.ruoyi.web.modules.industryservice.domain.BizYakDiseaseWarning;
import com.ruoyi.web.modules.industryservice.domain.dto.YakDiseaseWarningDto;
import com.ruoyi.web.modules.industryservice.mapper.BizPastureMapper;
import com.ruoyi.web.modules.industryservice.mapper.BizYakDiseaseWarningMapper;
import com.ruoyi.web.modules.industryservice.support.YakDiseaseWarningRules;
import com.ruoyi.web.modules.industryservice.support.YakDiseaseWarningValidation;

/**
 * 牦牛疾病预警落库（独立事务）。
 * <p>
 * 使用 {@code REQUIRES_NEW}：单条预警插入失败不影响分析器外层事务中其他分组的处理。<br>
 * 牧场映射：按第三方农场名称精确匹配 {@code biz_pasture}；匹配失败仅冗余名称、{@code pasture_id} 置空。
 * </p>
 */
@Service
public class YakDiseaseWarningSyncTxService
{
    @Autowired
    private BizYakDiseaseWarningMapper warningMapper;

    @Autowired
    private BizPastureMapper bizPastureMapper;

    /**
     * 将分析 DTO 写入 {@code biz_yak_disease_warning}。
     *
     * @param dto      必填 {@code alertTime}；可选类型、实测值、参考范围、预置文案等
     * @param syncTime 本轮同步时间，写入 {@code last_sync_time} / 审计时间
     * @return 当前实现固定返回 true（插入成功）；校验失败抛异常
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public boolean persistAlert(YakDiseaseWarningDto dto, Date syncTime)
    {
        if (dto == null)
        {
            throw new ServiceException("预警数据无效");
        }
        if (dto.getAlertTime() == null)
        {
            throw new ServiceException("预警时间不能为空");
        }
        if (dto.getWarningType() != null && !YakDiseaseWarningRules.isValidWarningType(dto.getWarningType()))
        {
            throw new ServiceException("预警类型无效");
        }
        BizYakDiseaseWarning row = new BizYakDiseaseWarning();
        row.setAlertTime(dto.getAlertTime());
        row.setWarningType(dto.getWarningType());
        row.setMeasuredValue(StringUtils.trim(dto.getMeasuredValue()));
        row.setReferenceRange(StringUtils.trim(dto.getReferenceRange()));
        row.setDeviceNo(StringUtils.trim(dto.getDeviceNo()));
        row.setCollectTime(dto.getCollectTime());
        row.setYakAvatarUrl(StringUtils.trim(dto.getYakAvatarUrl()));
        // 优先使用分析器给出的自然语言文案；否则按类型模板拼装
        row.setAlertMessage(YakDiseaseWarningValidation.buildAlertMessage(dto.getWarningType(), row.getMeasuredValue(),
                row.getReferenceRange(), dto.getAlertMessage()));
        row.setDataSource(YakDiseaseWarningRules.DATA_SOURCE_LOCAL);
        row.setLastSyncTime(syncTime);
        resolvePasture(row, dto.getPastureName());

        Date now = syncTime != null ? syncTime : new Date();
        row.setCreateTime(now);
        row.setUpdateTime(now);
        warningMapper.insertBizYakDiseaseWarning(row);
        return true;
    }

    /**
     * 按牧场名称精确匹配；空名称记为「未关联」。
     * 未匹配到系统牧场时仍保留第三方名称，便于列表展示与人工排查。
     */
    private void resolvePasture(BizYakDiseaseWarning row, String pastureName)
    {
        String name = StringUtils.trim(pastureName);
        if (StringUtils.isEmpty(name))
        {
            row.setPastureName("未关联");
            return;
        }
        BizPasture pasture = bizPastureMapper.selectBizPastureByExactName(name);
        if (pasture != null)
        {
            row.setPastureId(pasture.getId());
            row.setPastureName(pasture.getPastureName());
        }
        else
        {
            row.setPastureId(null);
            row.setPastureName(name);
        }
    }
}
