package com.zhyc.module.produce.breed.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Calendar;

import com.zhyc.common.utils.DateUtils;
import com.zhyc.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.zhyc.module.produce.breed.mapper.ScPregnancyRecordMapper;
import com.zhyc.module.produce.breed.domain.ScPregnancyRecord;
import com.zhyc.module.produce.breed.service.IScPregnancyRecordService;

/**
 * 孕检记录Service业务层处理
 *
 * @author zhyc
 * @date 2025-01-21
 */
@Service
public class ScPregnancyRecordServiceImpl implements IScPregnancyRecordService
{
    @Autowired
    private ScPregnancyRecordMapper scPregnancyRecordMapper;

    /**
     * 查询孕检记录
     *
     * @param id 孕检记录主键
     * @return 孕检记录
     */
    @Override
    public ScPregnancyRecord selectScPregnancyRecordById(Long id)
    {
        return scPregnancyRecordMapper.selectScPregnancyRecordById(id);
    }

    /**
     * 查询孕检记录列表
     *
     * @param scPregnancyRecord 孕检记录
     * @return 孕检记录
     */
    @Override
    public List<ScPregnancyRecord> selectScPregnancyRecordList(ScPregnancyRecord scPregnancyRecord)
    {
        return scPregnancyRecordMapper.selectScPregnancyRecordList(scPregnancyRecord);
    }

    /**
     * 新增孕检记录
     *
     * @param scPregnancyRecord 孕检记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertScPregnancyRecord(ScPregnancyRecord scPregnancyRecord)
    {
        // 参数校验
        if (scPregnancyRecord.getManageTags() == null || scPregnancyRecord.getManageTags().trim().isEmpty()) {
            throw new ServiceException("管理耳号不能为空");
        }

        if (scPregnancyRecord.getDatetime() == null) {
            throw new ServiceException("孕检日期不能为空");
        }

        if (scPregnancyRecord.getResult() == null || scPregnancyRecord.getResult().trim().isEmpty()) {
            throw new ServiceException("孕检结果不能为空");
        }

        // 根据耳号获取羊只信息并验证
        Map<String, Object> sheepInfo = scPregnancyRecordMapper.selectSheepByManageTags(scPregnancyRecord.getManageTags().trim());
        if (sheepInfo == null) {
            throw new ServiceException("管理耳号[" + scPregnancyRecord.getManageTags() + "]对应的羊只不存在");
        }

        Long sheepId = sheepInfo.get("id") != null ? Long.valueOf(sheepInfo.get("id").toString()) : null;
        if (sheepId == null) {
            throw new ServiceException("无法获取羊只ID，请检查数据完整性");
        }
        scPregnancyRecord.setSheepId(sheepId);

        // 验证孕检结果和胎儿数量的一致性
        validatePregnancyResult(scPregnancyRecord);

        // 设置默认值
        scPregnancyRecord.setCreateTime(DateUtils.getNowDate());
        scPregnancyRecord.setIsDelete(0);

        // 如果孕检方式为空，默认设置为B超
        if (scPregnancyRecord.getWay() == null || scPregnancyRecord.getWay().trim().isEmpty()) {
            scPregnancyRecord.setWay("B超");
        }

        int result = scPregnancyRecordMapper.insertScPregnancyRecord(scPregnancyRecord);

        // 如果孕检结果为怀孕，更新羊只基础表相关字段
        if ("怀孕".equals(scPregnancyRecord.getResult()) && result > 0) {
            updateSheepPregnancyStatus(scPregnancyRecord);
        }

        return result;
    }

    /**
     * 修改孕检记录
     *
     * @param scPregnancyRecord 孕检记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateScPregnancyRecord(ScPregnancyRecord scPregnancyRecord)
    {
        // 参数校验
        if (scPregnancyRecord.getId() == null) {
            throw new ServiceException("记录ID不能为空");
        }

        if (scPregnancyRecord.getManageTags() == null || scPregnancyRecord.getManageTags().trim().isEmpty()) {
            throw new ServiceException("管理耳号不能为空");
        }

        // 根据耳号获取羊只信息并验证
        Map<String, Object> sheepInfo = scPregnancyRecordMapper.selectSheepByManageTags(scPregnancyRecord.getManageTags().trim());
        if (sheepInfo == null) {
            throw new ServiceException("管理耳号[" + scPregnancyRecord.getManageTags() + "]对应的羊只不存在");
        }

        Long sheepId = sheepInfo.get("id") != null ? Long.valueOf(sheepInfo.get("id").toString()) : null;
        if (sheepId == null) {
            throw new ServiceException("无法获取羊只ID，请检查数据完整性");
        }
        scPregnancyRecord.setSheepId(sheepId);

        // 验证孕检结果和胎儿数量的一致性
        validatePregnancyResult(scPregnancyRecord);

        scPregnancyRecord.setUpdateTime(DateUtils.getNowDate());

        int result = scPregnancyRecordMapper.updateScPregnancyRecord(scPregnancyRecord);

        // 如果孕检结果为怀孕，更新羊只基础表相关字段
        if ("怀孕".equals(scPregnancyRecord.getResult()) && result > 0) {
            updateSheepPregnancyStatus(scPregnancyRecord);
        }

        return result;
    }

    /**
     * 验证孕检结果和胎儿数量的一致性
     *
     * @param scPregnancyRecord 孕检记录
     */
    private void validatePregnancyResult(ScPregnancyRecord scPregnancyRecord) {
        String result = scPregnancyRecord.getResult();
        Integer fetusCount = scPregnancyRecord.getFetusCount();

        if ("怀孕".equals(result)) {
            if (fetusCount == null || fetusCount <= 0) {
                throw new ServiceException("孕检结果为怀孕时，胎儿数量必须填写且大于0");
            }
            if (fetusCount > 10) {
                throw new ServiceException("胎儿数量不能超过10个");
            }
        } else if ("未孕".equals(result) || "流产".equals(result)) {
            // 未孕或流产时，胎儿数量应为0或null
            scPregnancyRecord.setFetusCount(0);
        }
    }

    /**
     * 批量删除孕检记录
     *
     * @param ids 需要删除的孕检记录主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteScPregnancyRecordByIds(Long[] ids)
    {
        if (ids == null || ids.length == 0) {
            throw new ServiceException("删除的记录ID不能为空");
        }
        return scPregnancyRecordMapper.deleteScPregnancyRecordByIds(ids);
    }

    /**
     * 删除孕检记录信息
     *
     * @param id 孕检记录主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteScPregnancyRecordById(Long id)
    {
        if (id == null) {
            throw new ServiceException("删除的记录ID不能为空");
        }
        return scPregnancyRecordMapper.deleteScPregnancyRecordById(id);
    }

    /**
     * 根据耳号查询羊只信息
     *
     * @param manageTags 耳号
     * @return 羊只信息
     */
    @Override
    public Map<String, Object> getSheepByManageTags(String manageTags)
    {
        if (manageTags == null || manageTags.trim().isEmpty()) {
            throw new ServiceException("管理耳号不能为空");
        }
        return scPregnancyRecordMapper.selectSheepByManageTags(manageTags.trim());
    }

    /**
     * 根据耳号获取配种信息
     *
     * @param manageTags 耳号
     * @return 配种信息
     */
    @Override
    public Map<String, Object> getBreedInfoByManageTags(String manageTags)
    {
        if (manageTags == null || manageTags.trim().isEmpty()) {
            throw new ServiceException("管理耳号不能为空");
        }
        return scPregnancyRecordMapper.selectBreedInfoByManageTags(manageTags.trim());
    }

    /**
     * 更新羊只怀孕状态
     *
     * @param scPregnancyRecord 孕检记录
     */
    private void updateSheepPregnancyStatus(ScPregnancyRecord scPregnancyRecord) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("sheepId", scPregnancyRecord.getSheepId());
            params.put("pregDate", scPregnancyRecord.getDatetime());

            // 设置繁育状态为怀孕状态（假设怀孕状态ID为2）
            params.put("breedStatusId", 2);

            // 计算预产日期（羊的妊娠期大约150天）
            if (scPregnancyRecord.getDatetime() != null) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(scPregnancyRecord.getDatetime());
                cal.add(Calendar.DAY_OF_YEAR, 150);
                params.put("expectedDate", cal.getTime());
            }

            // 计算怀孕天数
            if (scPregnancyRecord.getDatetime() != null) {
                long days = (System.currentTimeMillis() - scPregnancyRecord.getDatetime().getTime()) / (1000 * 60 * 60 * 24);
                params.put("gestationDay", (int) days);
            }

            scPregnancyRecordMapper.updateSheepPregnancyInfo(params);
        } catch (Exception e) {
            // 记录日志但不影响主流程
            System.err.println("更新羊只怀孕状态失败: " + e.getMessage());
        }
    }
    @Override
    public List<String> searchEarNumbers(String query) {
        return scPregnancyRecordMapper.searchEarNumbers(query);
    }
}