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

import java.util.List;
import java.util.Map;
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 com.zhyc.module.produce.breed.mapper.ScMiscarriageRecordMapper;
import com.zhyc.module.produce.breed.domain.ScMiscarriageRecord;
import com.zhyc.module.produce.breed.service.IScMiscarriageRecordService;

/**
 * 流产记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-23
 */
@Service
public class ScMiscarriageRecordServiceImpl implements IScMiscarriageRecordService
{
    @Autowired
    private ScMiscarriageRecordMapper scMiscarriageRecordMapper;

    /**
     * 查询流产记录
     *
     * @param id 流产记录主键
     * @return 流产记录
     */
    @Override
    public ScMiscarriageRecord selectScMiscarriageRecordById(Long id)
    {
        return scMiscarriageRecordMapper.selectScMiscarriageRecordById(id);
    }

    /**
     * 查询流产记录列表
     *
     * @param scMiscarriageRecord 流产记录
     * @return 流产记录
     */
    @Override
    public List<ScMiscarriageRecord> selectScMiscarriageRecordList(ScMiscarriageRecord scMiscarriageRecord)
    {
        return scMiscarriageRecordMapper.selectScMiscarriageRecordList(scMiscarriageRecord);
    }

    /**
     * 新增流产记录
     * 增加性别验证：只允许母羊录入流产记录
     *
     * @param scMiscarriageRecord 流产记录
     * @return 结果
     */
    @Override
    public int insertScMiscarriageRecord(ScMiscarriageRecord scMiscarriageRecord)
    {
        // 验证羊只是否存在及性别
        validateSheepGender(scMiscarriageRecord.getSheepId());

        scMiscarriageRecord.setCreateTime(DateUtils.getNowDate());
        return scMiscarriageRecordMapper.insertScMiscarriageRecord(scMiscarriageRecord);
    }

    /**
     * 修改流产记录
     * 增加性别验证：只允许母羊录入流产记录
     *
     * @param scMiscarriageRecord 流产记录
     * @return 结果
     */
    @Override
    public int updateScMiscarriageRecord(ScMiscarriageRecord scMiscarriageRecord)
    {
        // 修改时也需要验证性别（防止前端绕过验证）
        validateSheepGender(scMiscarriageRecord.getSheepId());

        return scMiscarriageRecordMapper.updateScMiscarriageRecord(scMiscarriageRecord);
    }

    /**
     * 批量删除流产记录
     *
     * @param ids 需要删除的流产记录主键
     * @return 结果
     */
    @Override
    public int deleteScMiscarriageRecordByIds(Long[] ids)
    {
        return scMiscarriageRecordMapper.deleteScMiscarriageRecordByIds(ids);
    }

    /**
     * 删除流产记录信息
     *
     * @param id 流产记录主键
     * @return 结果
     */
    @Override
    public int deleteScMiscarriageRecordById(Long id)
    {
        return scMiscarriageRecordMapper.deleteScMiscarriageRecordById(id);
    }

    /**
     * 根据耳号查询羊只信息
     *
     * @param manageTags 管理耳号
     * @return 羊只信息
     */
    @Override
    public Map<String, Object> selectSheepByManageTags(String manageTags)
    {
        return scMiscarriageRecordMapper.selectSheepByManageTags(manageTags);
    }

    /**
     * 验证羊只性别 - 私有方法
     * 只允许母羊录入流产记录
     * gender字段：1=母羊，2=公羊
     *
     * @param manageTags 管理耳号
     * @throws ServiceException 如果不是母羊或羊只不存在
     */
    private void validateSheepGender(String manageTags) {
        if (manageTags == null || manageTags.trim().isEmpty()) {
            throw new ServiceException("羊只耳号不能为空");
        }

        // 查询羊只信息
        Map<String, Object> sheepInfo = scMiscarriageRecordMapper.selectSheepByManageTags(manageTags);

        if (sheepInfo == null || sheepInfo.isEmpty()) {
            throw new ServiceException("未找到耳号为【" + manageTags + "】的羊只信息，请检查耳号是否正确");
        }

        // 检查性别 - 注意：这里使用gender字段，不是sexType
        Object genderObj = sheepInfo.get("gender");
        if (genderObj == null) {
            throw new ServiceException("该羊只性别信息缺失，无法录入流产记录");
        }

        // 转换性别类型
        Integer gender = null;
        try {
            if (genderObj instanceof Integer) {
                gender = (Integer) genderObj;
            } else if (genderObj instanceof String) {
                gender = Integer.valueOf((String) genderObj);
            } else if (genderObj instanceof Long) {
                gender = ((Long) genderObj).intValue();
            }
        } catch (NumberFormatException e) {
            throw new ServiceException("该羊只性别信息格式错误，无法录入流产记录");
        }

        // 验证是否为母羊 - 1=母羊，2=公羊
        if (gender == null) {
            throw new ServiceException("该羊只性别信息为空，无法录入流产记录");
        } else if (gender == 2) {
            String variety = sheepInfo.get("variety") != null ? sheepInfo.get("variety").toString() : "未知品种";
            throw new ServiceException("流产记录只能录入母羊，耳号【" + manageTags + "】对应的是公羊（" + variety + "）");
        } else if (gender != 1) {
            throw new ServiceException("该羊只性别信息异常（值：" + gender + "），只允许母羊录入流产记录");
        }

        // 验证通过
    }

    @Override
    public List<String> searchEarNumbers(String query) {
        return scMiscarriageRecordMapper.searchEarNumbers(query);
    }
}