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.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zhyc.module.produce.breed.mapper.RawSpermRecordMapper;
import com.zhyc.module.produce.breed.domain.RawSpermRecord;
import com.zhyc.module.produce.breed.service.IRawSpermRecordService;

/**
 * 采精记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-23
 */
@Service
public class RawSpermRecordServiceImpl implements IRawSpermRecordService
{
    @Autowired
    private RawSpermRecordMapper rawSpermRecordMapper;

    /**
     * 查询采精记录
     *
     * @param id 采精记录主键
     * @return 采精记录
     */
    @Override
    public RawSpermRecord selectRawSpermRecordById(Long id)
    {
        return rawSpermRecordMapper.selectRawSpermRecordById(id);
    }

    /**
     * 查询采精记录列表
     *
     * @param rawSpermRecord 采精记录
     * @return 采精记录
     */
    @Override
    public List<RawSpermRecord> selectRawSpermRecordList(RawSpermRecord rawSpermRecord)
    {
        return rawSpermRecordMapper.selectRawSpermRecordList(rawSpermRecord);
    }

    /**
     * 新增采精记录
     *
     * @param rawSpermRecord 采精记录
     * @return 结果
     */
    @Override
    public int insertRawSpermRecord(RawSpermRecord rawSpermRecord)
    {
        // 如果传入的是耳号，需要先根据耳号查询羊只信息并验证性别
        if (StringUtils.isNotEmpty(rawSpermRecord.getManageTags())) {
            Map<String, Object> sheepInfo = getSheepInfoByManageTags(rawSpermRecord.getManageTags());
            if (sheepInfo == null) {
                throw new RuntimeException("未找到耳号为[" + rawSpermRecord.getManageTags() + "]的羊只信息");
            }

            // 安全的类型转换
            Integer sheepId = convertToInteger(sheepInfo.get("id"));
            Integer gender = convertToInteger(sheepInfo.get("gender"));
            Integer monthAge = convertToInteger(sheepInfo.get("monthAge"));
            String electronicTags = (String) sheepInfo.get("electronicTags");

            // 关键验证：必须是公羊（gender=2）
            if (gender == null || gender != 2) {
                throw new RuntimeException("采精记录只能针对公羊，耳号[" + rawSpermRecord.getManageTags() + "]对应的羊只不是公羊");
            }

            // 设置关联信息
            rawSpermRecord.setSheepId(sheepId);
            if (rawSpermRecord.getMonthAge() == null && monthAge != null) {
                rawSpermRecord.setMonthAge(monthAge);
            }
            if (StringUtils.isEmpty(rawSpermRecord.getElectronicTags()) && StringUtils.isNotEmpty(electronicTags)) {
                rawSpermRecord.setElectronicTags(electronicTags);
            }
        }

        // 设置默认值
        if (rawSpermRecord.getControlled() == null) {
            rawSpermRecord.setControlled(0); // 默认不性控
        }

        rawSpermRecord.setCreateTime(DateUtils.getNowDate());
        return rawSpermRecordMapper.insertRawSpermRecord(rawSpermRecord);
    }

    /**
     * 修改采精记录
     *
     * @param rawSpermRecord 采精记录
     * @return 结果
     */
    @Override
    public int updateRawSpermRecord(RawSpermRecord rawSpermRecord)
    {
        // 如果修改了耳号，需要重新验证
        if (StringUtils.isNotEmpty(rawSpermRecord.getManageTags())) {
            Map<String, Object> sheepInfo = getSheepInfoByManageTags(rawSpermRecord.getManageTags());
            if (sheepInfo == null) {
                throw new RuntimeException("未找到耳号为[" + rawSpermRecord.getManageTags() + "]的羊只信息");
            }

            Integer sheepId = convertToInteger(sheepInfo.get("id"));
            Integer gender = convertToInteger(sheepInfo.get("gender"));

            // 验证性别
            if (gender == null || gender != 2) {
                throw new RuntimeException("采精记录只能针对公羊，耳号[" + rawSpermRecord.getManageTags() + "]对应的羊只不是公羊");
            }

            rawSpermRecord.setSheepId(sheepId);
        }

        rawSpermRecord.setUpdateTime(DateUtils.getNowDate());
        return rawSpermRecordMapper.updateRawSpermRecord(rawSpermRecord);
    }

    /**
     * 批量删除采精记录
     *
     * @param ids 需要删除的采精记录主键
     * @return 结果
     */
    @Override
    public int deleteRawSpermRecordByIds(Long[] ids)
    {
        return rawSpermRecordMapper.deleteRawSpermRecordByIds(ids);
    }

    /**
     * 删除采精记录信息
     *
     * @param id 采精记录主键
     * @return 结果
     */
    @Override
    public int deleteRawSpermRecordById(Long id)
    {
        return rawSpermRecordMapper.deleteRawSpermRecordById(id);
    }

    /**
     * 根据耳号查询羊只ID
     *
     * @param manageTags 耳号
     * @return 羊只ID
     */
    @Override
    public Long getSheepIdByManageTags(String manageTags)
    {
        Integer sheepId = rawSpermRecordMapper.selectSheepIdByManageTags(manageTags);
        return sheepId != null ? sheepId.longValue() : null;
    }

    /**
     * 根据耳号查询羊只信息
     *
     * @param manageTags 耳号
     * @return 羊只信息 Map包含id、gender、monthAge、electronicTags等字段
     */
    @Override
    public Map<String, Object> getSheepInfoByManageTags(String manageTags)
    {
        return rawSpermRecordMapper.selectSheepInfoByManageTags(manageTags);
    }

    /**
     * 验证羊只是否为公羊
     *
     * @param manageTags 耳号
     * @return true-是公羊，false-不是公羊
     */
    @Override
    public boolean validateRamGender(String manageTags)
    {
        Map<String, Object> sheepInfo = getSheepInfoByManageTags(manageTags);
        if (sheepInfo != null) {
            Integer gender = convertToInteger(sheepInfo.get("gender"));
            return gender != null && gender == 2; // 公羊gender=2
        }
        return false;
    }

    /**
     * 安全的类型转换：将Object转换为Integer
     *
     * @param obj 要转换的对象
     * @return Integer值，如果转换失败返回null
     */
    private Integer convertToInteger(Object obj) {
        if (obj == null) {
            return null;
        }

        if (obj instanceof Integer) {
            return (Integer) obj;
        } else if (obj instanceof Long) {
            Long longValue = (Long) obj;
            // 检查Long值是否在Integer范围内
            if (longValue >= Integer.MIN_VALUE && longValue <= Integer.MAX_VALUE) {
                return longValue.intValue();
            } else {
                throw new RuntimeException("数值超出Integer范围：" + longValue);
            }
        } else if (obj instanceof String) {
            try {
                return Integer.parseInt((String) obj);
            } catch (NumberFormatException e) {
                throw new RuntimeException("无法将字符串转换为Integer：" + obj);
            }
        } else {
            throw new RuntimeException("无法将 " + obj.getClass().getSimpleName() + " 类型转换为Integer");
        }
    }
}