//package com.zhyc.module.base.service.impl;
//
//import java.math.BigDecimal;
//import java.math.RoundingMode;
//import java.util.Date;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//import java.util.stream.Collectors;
//import com.zhyc.common.utils.DateUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//import com.zhyc.module.base.mapper.BreedRamFileMapper;
//import com.zhyc.module.base.mapper.SheepFileMapper;
//import com.zhyc.module.produce.breed.mapper.RawSpermRecordMapper;
//import com.zhyc.module.produce.breed.mapper.ScBreedRecordMapper;
//import com.zhyc.module.produce.breed.mapper.ScLambingRecordMapper;
//import com.zhyc.module.produce.breed.mapper.ScPregnancyRecordMapper;
//import com.zhyc.module.base.domain.BreedRamFile;
//import com.zhyc.module.base.domain.SheepFile;
//import com.zhyc.module.produce.breed.domain.RawSpermRecord;
//import com.zhyc.module.produce.breed.domain.ScBreedRecord;
//import com.zhyc.module.produce.breed.domain.ScLambingRecord;
//import com.zhyc.module.produce.breed.domain.ScPregnancyRecord;
//import com.zhyc.module.base.service.IBreedRamFileService;
//
///**
// * 种公羊档案Service业务层处理
// *
// * @author zhyc
// * @date 2025-07-29
// */
//@Service
//public class BreedRamFileServiceImpl implements IBreedRamFileService {
//    @Autowired
//    private BreedRamFileMapper breedRamFileMapper;
//
//    @Autowired
//    private SheepFileMapper sheepFileMapper;
//
//    @Autowired
//    private RawSpermRecordMapper rawSpermRecordMapper;
//
//    @Autowired
//    private ScBreedRecordMapper scBreedRecordMapper;
//
//    @Autowired
//    private ScLambingRecordMapper scLambingRecordMapper;
//
//    @Autowired
//    private ScPregnancyRecordMapper scPregnancyRecordMapper;
//
//    /**
//     * 查询种公羊档案
//     *
//     * @param id 种公羊档案主键
//     * @return 种公羊档案
//     */
//    @Override
//    public BreedRamFile selectBreedRamFileById(Long id) {
//        return breedRamFileMapper.selectBreedRamFileById(id);
//    }
//
//    /**
//     * 查询种公羊档案列表
//     *
//     * @param breedRamFile 种公羊档案
//     * @return 种公羊档案
//     */
//    @Override
//    public List<BreedRamFile> selectBreedRamFileList(BreedRamFile breedRamFile) {
//        return breedRamFileMapper.selectBreedRamFileList(breedRamFile);
//    }
//
//    /**
//     * 新增种公羊档案
//     *
//     * @param breedRamFile 种公羊档案
//     * @return 结果
//     */
//    @Override
//    @Transactional
//    public int insertBreedRamFile(BreedRamFile breedRamFile) {
//        breedRamFile.setCreateTime(DateUtils.getNowDate());
//        return breedRamFileMapper.insertBreedRamFile(breedRamFile);
//    }
//
//    /**
//     * 修改种公羊档案
//     *
//     * @param breedRamFile 种公羊档案
//     * @return 结果
//     */
//    @Override
//    @Transactional
//    public int updateBreedRamFile(BreedRamFile breedRamFile) {
//        breedRamFile.setUpdateTime(DateUtils.getNowDate());
//        return breedRamFileMapper.updateBreedRamFile(breedRamFile);
//    }
//
//    /**
//     * 批量删除种公羊档案
//     *
//     * @param ids 需要删除的种公羊档案主键
//     * @return 结果
//     */
//    @Override
//    @Transactional
//    public int deleteBreedRamFileByIds(Long[] ids) {
//        return breedRamFileMapper.deleteBreedRamFileByIds(ids);
//    }
//
//    /**
//     * 删除种公羊档案信息
//     *
//     * @param id 种公羊档案主键
//     * @return 结果
//     */
//    @Override
//    @Transactional
//    public int deleteBreedRamFileById(Long id) {
//        return breedRamFileMapper.deleteBreedRamFileById(id);
//    }
//
//    // ====================== Service实现类中对应的实现 ======================
//
//    @Override
//    public BreedRamFile selectBreedRamFileByEarNumber(String earNumber) {
//        return breedRamFileMapper.selectBreedRamFileByOrdinaryEarNumber(earNumber);
//    }
//
//    @Override
//    public List<BreedRamFile> selectBreedRamFileListByRanchId(Long ranchId) {
//        return breedRamFileMapper.selectBreedRamFileListByRanchId(ranchId);
//    }
//
//    @Override
//    public List<BreedRamFile> selectBreedRamFileListBySheepfoldId(Long sheepfoldId) {
//        return breedRamFileMapper.selectBreedRamFileListBySheepfoldId(sheepfoldId);
//    }
//
//    @Override
//    public List<BreedRamFile> selectCoreFlockBreedRamFileList(BreedRamFile breedRamFile) {
//        return breedRamFileMapper.selectCoreFlockBreedRamFileList(breedRamFile);
//    }
//
//    @Override
//    public List<BreedRamFile> selectBreedingUseBreedRamFileList(BreedRamFile breedRamFile) {
//        return breedRamFileMapper.selectBreedingUseBreedRamFileList(breedRamFile);
//    }
//
//
//    @Override
//    public BreedRamFile selectBreedRamFileByOrdinaryEarNumber(String ordinaryEarNumber) {
//        return breedRamFileMapper.selectBreedRamFileByOrdinaryEarNumber(ordinaryEarNumber);
//    }
//
//    @Override
//    @Transactional
//    public int syncSpecificRams(List<String> earNumbers) {
//        int syncCount = 0;
//        for (String earNumber : earNumbers) {
//            try {
//                // 查询指定耳号的公羊
//                SheepFile sheep = sheepFileMapper.selectSheepFileByManageTags(earNumber);
//                if (sheep != null && sheep.getGender() == 2) {
//                    BreedRamFile existingRam = breedRamFileMapper.selectBreedRamFileByOrdinaryEarNumber(earNumber);
//                    if (existingRam == null) {
//                        BreedRamFile newRam = buildRamFileFromSheep(sheep);
//                        breedRamFileMapper.insertBreedRamFile(newRam);
//                    } else {
//                        updateRamFileFromSheep(existingRam, sheep);
//                        breedRamFileMapper.updateBreedRamFile(existingRam);
//                    }
//                    syncCount++;
//                }
//            } catch (Exception e) {
//                System.err.println("同步公羊档案失败，耳号：" + earNumber + "，错误：" + e.getMessage());
//            }
//        }
//        return syncCount;
//    }
//
//    @Override
//    public Map<String, Object> getBreedRamStatistics() {
//        Map<String, Object> statistics = new HashMap<>();
//
//        // 总公羊数
//        BreedRamFile queryParam = new BreedRamFile();
//        List<BreedRamFile> allRams = breedRamFileMapper.selectBreedRamFileList(queryParam);
//        statistics.put("totalRams", allRams.size());
//
//        // 核心羊群数
//        List<BreedRamFile> coreFlockRams = breedRamFileMapper.selectCoreFlockBreedRamFileList(queryParam);
//        statistics.put("coreFlockRams", coreFlockRams.size());
//
//        // 种用公羊数
//        List<BreedRamFile> breedingUseRams = breedRamFileMapper.selectBreedingUseBreedRamFileList(queryParam);
//        statistics.put("breedingUseRams", breedingUseRams.size());
//
//        // 按品种统计
//        Map<String, Long> varietyCount = allRams.stream()
//                .collect(Collectors.groupingBy(
//                        ram -> ram.getVariety() != null ? ram.getVariety() : "未知",
//                        Collectors.counting()
//                ));
//        statistics.put("varietyDistribution", varietyCount);
//
//        // 按牧场统计
//        Map<String, Long> ranchCount = allRams.stream()
//                .collect(Collectors.groupingBy(
//                        ram -> ram.getRanchName() != null ? ram.getRanchName() : "未知",
//                        Collectors.counting()
//                ));
//        statistics.put("ranchDistribution", ranchCount);
//
//        // 平均月龄
//        Double avgMonthAge = allRams.stream()
//                .filter(ram -> ram.getMonthAge() != null)
//                .mapToLong(BreedRamFile::getMonthAge)
//                .average()
//                .orElse(0.0);
//        statistics.put("avgMonthAge", avgMonthAge);
//
//        // 平均多胎性
//        Double avgProlificacy = allRams.stream()
//                .filter(ram -> ram.getProlificacy() != null)
//                .mapToDouble(ram -> ram.getProlificacy().doubleValue())
//                .average()
//                .orElse(0.0);
//        statistics.put("avgProlificacy", avgProlificacy);
//
//        return statistics;
//    }
//
//    /**
//     * 从sheep_file同步公羊数据到公羊档案
//     * 同步逻辑：
//     * 1. 从sheep_file获取基础信息（gender=2的公羊）
//     * 2. 从raw_sperm_record获取采精相关数据
//     * 3. 从sc_breed_record获取配种统计数据
//     * 4. 从sc_lambing_record获取后代数统计
//     * 5. 从sc_pregnancy_record获取孕检统计数据
//     * 6. 计算多胎性、受孕率等指标
//     *
//     * @return 同步的记录数
//     */
//    /**
//     * 从sheep_file同步公羊数据到公羊档案
//     */
//    @Override
//    @Transactional
//    public int syncFromSheepFile() {
//        // 1. 查询所有gender=2的羊只(公羊)
//        List<SheepFile> rams = sheepFileMapper.selectRamList();
//        int syncCount = 0;
//        int updateCount = 0;
//        int insertCount = 0;
//
//        System.out.println("开始同步公羊数据，共找到 " + rams.size() + " 只公羊");
//
//        for (SheepFile sheep : rams) {
//            try {
//                // 检查该公羊是否已存在于公羊档案
//                BreedRamFile existingRam = breedRamFileMapper
//                        .selectBreedRamFileByOrdinaryEarNumber(sheep.getBsManageTags());
//
//                if (existingRam == null) {
//                    // 新增公羊档案
//                    BreedRamFile newRam = buildRamFileFromSheep(sheep);
//                    int result = breedRamFileMapper.insertBreedRamFile(newRam);
//                    if (result > 0) {
//                        insertCount++;
//                        syncCount++;
//                    }
//                } else {
//                    // 更新公羊档案
//                    updateRamFileFromSheep(existingRam, sheep);
//                    int result = breedRamFileMapper.updateBreedRamFile(existingRam);
//                    if (result > 0) {
//                        updateCount++;
//                        syncCount++;
//                    }
//                }
//            } catch (Exception e) {
//                System.err.println("同步公羊档案失败，耳号：" + sheep.getBsManageTags()
//                        + "，错误：" + e.getMessage());
//                e.printStackTrace();
//            }
//        }
//
//        System.out.println("同步完成！新增: " + insertCount + " 只，更新: " + updateCount + " 只");
//        return syncCount;
//    }
//
//    /**
//     * 从SheepFile构建完整的BreedRamFile对象
//     */
//    private BreedRamFile buildRamFileFromSheep(SheepFile sheep) {
//        BreedRamFile ram = new BreedRamFile();
//
//        // 1. 从sheep_file同步基础信息
//        syncBasicInfoFromSheep(ram, sheep);
//
//        // 2. 从raw_sperm_record同步采精信息
//        syncSpermInfoFromRecords(ram, sheep.getId());
//
//        // 3. 从sc_breed_record、sc_lambing_record、sc_pregnancy_record同步配种和繁殖统计
//        syncBreedingStatistics(ram, sheep.getBsManageTags());
//
//        ram.setCreateTime(DateUtils.getNowDate());
//        ram.setIsDelete(0L);
//
//        return ram;
//    }
//
//    /**
//     * 从SheepFile更新BreedRamFile
//     */
//    private void updateRamFileFromSheep(BreedRamFile ram, SheepFile sheep) {
//        // 1. 更新基础信息
//        syncBasicInfoFromSheep(ram, sheep);
//
//        // 2. 更新采精信息
//        syncSpermInfoFromRecords(ram, sheep.getId());
//
//        // 3. 更新配种和繁殖统计
//        syncBreedingStatistics(ram, sheep.getBsManageTags());
//
//        ram.setUpdateTime(DateUtils.getNowDate());
//    }
//
//    /**
//     * 同步基础信息（从sheep_file）
//     */
//    private void syncBasicInfoFromSheep(BreedRamFile ram, SheepFile sheep) {
//        // 【重要】使用 setManageTags 而不是 setOrdinaryEarNumber
//        ram.setManageTags(sheep.getBsManageTags());              // 普通耳号（manage_tags）
//        ram.setRanchId(sheep.getRanchId());                      // 牧场id
//        ram.setRanchName(sheep.getDrRanch());                    // 牧场名称
//        ram.setSheepfoldId(sheep.getSheepfoldId());              // 羊舍id
//        ram.setSheepfoldName(sheep.getSheepfoldName());          // 羊舍名称
//        ram.setElectronicTags(sheep.getElectronicTags());        // 电子耳号
//        ram.setVarietyId(sheep.getVarietyId());                  // 品种id
//        ram.setVariety(sheep.getVariety());                      // 品种
//        ram.setSheepCategory(sheep.getName());                   // 羊只类别
//        ram.setCurrentStatus(String.valueOf(sheep.getStatusId())); // 当前状态
//        ram.setBirthday(sheep.getBirthday());                    // 出生日期
//
//        // 【关键】从sheep_file获取month_age
//        ram.setMonthAge(sheep.getMonthAge());                    // 月龄
//
//        // 体重相关数据
//        ram.setBirthWeight(sheep.getBirthWeight() != null ?
//                BigDecimal.valueOf(sheep.getBirthWeight()) : null);
//        ram.setWeaningDate(sheep.getWeaningDate());
//        ram.setWeaningDayAge(sheep.getWeaningDayAge() != null ?
//                Long.valueOf(sheep.getWeaningDayAge()) : null);
//        ram.setWeaningWeight(sheep.getWeaningWeight() != null ?
//                BigDecimal.valueOf(sheep.getWeaningWeight()) : null);
//        ram.setWeaningDailyGain(sheep.getWeaningDailyGain() != null ?
//                BigDecimal.valueOf(sheep.getWeaningDailyGain()) : null);
//        ram.setCurrentWeight(sheep.getCurrentWeight() != null ?
//                BigDecimal.valueOf(sheep.getCurrentWeight()) : null);
//
//        // 家系信息
//        ram.setFatherNumber(sheep.getFatherManageTags());
//        ram.setMotherNumber(sheep.getMotherManageTags());
//        ram.setGrandfatherNumber(sheep.getGrandfatherManageTags());
//        ram.setGrandmotherNumber(sheep.getGrandmotherManageTags());
//        ram.setMaternalGrandfatherNumber(sheep.getMaternalGrandfatherManageTags());
//        ram.setMaternalGrandmotherNumber(sheep.getMaternalGrandmotherManageTags());
//    }
//
//    /**
//     * 同步采精信息（从raw_sperm_record）
//     */
//    private void syncSpermInfoFromRecords(BreedRamFile ram, Long sheepId) {
//        if (sheepId == null) {
//            return;
//        }
//
//        try {
//            RawSpermRecord latestSperm = rawSpermRecordMapper.selectLatestByRamId(sheepId);
//
//            if (latestSperm != null) {
//                ram.setSexualStatus(latestSperm.getSexualStatus());
//                ram.setScrotumCircumference(latestSperm.getScrotumCircumference());
//                ram.setSpermCollectionTime(latestSperm.getPickDate());
//                ram.setSpermVolume(latestSperm.getAmount());
//                ram.setSpermVitality(latestSperm.getVitallity());
//                ram.setSpermDensity(latestSperm.getDensity());
//                ram.setSpermQuality(latestSperm.getSemenQuality());
//            }
//        } catch (Exception e) {
//            System.err.println("同步采精信息失败，羊只ID：" + sheepId + "，错误：" + e.getMessage());
//        }
//    }
//
//    /**
//     * 同步配种和繁殖统计数据
//     */
//    private void syncBreedingStatistics(BreedRamFile ram, String ramManageTags) {
//        if (ramManageTags == null || ramManageTags.trim().isEmpty()) {
//            return;
//        }
//
//        try {
//            // 1. 统计该公羊配了多少母羊（去重）
//            Long totalMatedEwes = scBreedRecordMapper.countMatedEwesByRamId(ramManageTags);
//            ram.setTotalMatedEwes(totalMatedEwes != null ? totalMatedEwes : 0L);
//
//            // 2. 统计公羊后代数（从产羔记录）
//            Long offspringCount = scLambingRecordMapper.countOffspringByRamId(ramManageTags);
//            ram.setOffspringCount(offspringCount != null ? offspringCount : 0L);
//
//            // 3. 计算多胎性 = 公羊后代数 / 配种母羊数
//            if (totalMatedEwes != null && totalMatedEwes > 0 && offspringCount != null) {
//                BigDecimal prolificacy = BigDecimal.valueOf(offspringCount)
//                        .divide(BigDecimal.valueOf(totalMatedEwes), 2, RoundingMode.HALF_UP);
//                ram.setProlificacy(prolificacy);
//            } else {
//                ram.setProlificacy(BigDecimal.ZERO);
//            }
//
//            // 4. 统计孕检相关数据
//            syncPregnancyStatistics(ram, ramManageTags, totalMatedEwes);
//
//        } catch (Exception e) {
//            System.err.println("同步配种统计失败，耳号：" + ramManageTags + "，错误：" + e.getMessage());
//        }
//    }
//
//    /**
//     * 同步孕检统计数据
//     */
//    private void syncPregnancyStatistics(BreedRamFile ram, String ramManageTags, Long totalMatedEwes) {
//        try {
//            // 本交孕检母羊数（配种方式为本交=2的孕检有胎记录）
//            Long naturalPregnantEwes = scPregnancyRecordMapper
//                    .countPregnantEwesByRamIdAndBreedType(ramManageTags, 2); // 2=本交
//            ram.setNaturalPregnancyCheckEwes(naturalPregnantEwes != null ? naturalPregnantEwes : 0L);
//
//            // 本交受孕率%
//            if (totalMatedEwes != null && totalMatedEwes > 0 && naturalPregnantEwes != null) {
//                BigDecimal naturalRate = BigDecimal.valueOf(naturalPregnantEwes)
//                        .multiply(BigDecimal.valueOf(100))
//                        .divide(BigDecimal.valueOf(totalMatedEwes), 2, RoundingMode.HALF_UP);
//                ram.setNaturalConceptionRate(naturalRate);
//            } else {
//                ram.setNaturalConceptionRate(BigDecimal.ZERO);
//            }
//
//            // 人工孕检母羊数（配种方式为人工授精=1的孕检有胎记录）
//            Long artificialPregnantEwes = scPregnancyRecordMapper
//                    .countPregnantEwesByRamIdAndBreedType(ramManageTags, 1); // 1=人工授精
//            ram.setArtificialPregnancyCheckEwes(artificialPregnantEwes != null ? artificialPregnantEwes : 0L);
//
//            // 人工受孕率%
//            if (totalMatedEwes != null && totalMatedEwes > 0 && artificialPregnantEwes != null) {
//                BigDecimal artificialRate = BigDecimal.valueOf(artificialPregnantEwes)
//                        .multiply(BigDecimal.valueOf(100))
//                        .divide(BigDecimal.valueOf(totalMatedEwes), 2, RoundingMode.HALF_UP);
//                ram.setArtificialConceptionRate(artificialRate);
//            } else {
//                ram.setArtificialConceptionRate(BigDecimal.ZERO);
//            }
//        } catch (Exception e) {
//            System.err.println("同步孕检统计失败，耳号：" + ramManageTags + "，错误：" + e.getMessage());
//            e.printStackTrace();
//        }
//    }
//}
package com.zhyc.module.base.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.zhyc.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.zhyc.module.base.mapper.BreedRamFileMapper;
import com.zhyc.module.base.mapper.ViewBreedRamFileMapper;
import com.zhyc.module.base.mapper.SheepFileMapper;
import com.zhyc.module.produce.breed.mapper.RawSpermRecordMapper;
import com.zhyc.module.produce.breed.mapper.ScBreedRecordMapper;
import com.zhyc.module.produce.breed.mapper.ScLambingRecordMapper;
import com.zhyc.module.produce.breed.mapper.ScPregnancyRecordMapper;
import com.zhyc.module.base.domain.BreedRamFile;
import com.zhyc.module.base.domain.ViewBreedRamFile;
import com.zhyc.module.base.domain.SheepFile;
import com.zhyc.module.produce.breed.domain.RawSpermRecord;
import com.zhyc.module.produce.breed.domain.ScBreedRecord;
import com.zhyc.module.produce.breed.domain.ScLambingRecord;
import com.zhyc.module.produce.breed.domain.ScPregnancyRecord;
import com.zhyc.module.base.service.IBreedRamFileService;

/**
 * 种公羊档案Service业务层处理
 *
 * @author zhyc
 * @date 2025-07-29
 */
@Service
public class BreedRamFileServiceImpl implements IBreedRamFileService {
    @Autowired
    private BreedRamFileMapper breedRamFileMapper;

    @Autowired
    private ViewBreedRamFileMapper viewBreedRamFileMapper;

    @Autowired
    private SheepFileMapper sheepFileMapper;

    @Autowired
    private RawSpermRecordMapper rawSpermRecordMapper;

    @Autowired
    private ScBreedRecordMapper scBreedRecordMapper;

    @Autowired
    private ScLambingRecordMapper scLambingRecordMapper;

    @Autowired
    private ScPregnancyRecordMapper scPregnancyRecordMapper;

    // ========== 视图查询方法实现 ==========

    @Override
    public ViewBreedRamFile selectViewBreedRamFileById(Long id) {
        return viewBreedRamFileMapper.selectViewBreedRamFileById(id);
    }

    @Override
    public List<ViewBreedRamFile> selectViewBreedRamFileList(ViewBreedRamFile viewBreedRamFile) {
        return viewBreedRamFileMapper.selectViewBreedRamFileList(viewBreedRamFile);
    }

    @Override
    public ViewBreedRamFile selectViewBreedRamFileByEarNumber(String earNumber) {
        return viewBreedRamFileMapper.selectViewBreedRamFileByOrdinaryEarNumber(earNumber);
    }

    @Override
    public List<ViewBreedRamFile> selectViewBreedRamFileListByRanchId(Long ranchId) {
        return viewBreedRamFileMapper.selectViewBreedRamFileListByRanchId(ranchId);
    }

    @Override
    public List<ViewBreedRamFile> selectViewBreedRamFileListBySheepfoldId(Long sheepfoldId) {
        return viewBreedRamFileMapper.selectViewBreedRamFileListBySheepfoldId(sheepfoldId);
    }

    @Override
    public List<ViewBreedRamFile> selectCoreFlockViewBreedRamFileList(ViewBreedRamFile viewBreedRamFile) {
        return viewBreedRamFileMapper.selectCoreFlockViewBreedRamFileList(viewBreedRamFile);
    }

    @Override
    public List<ViewBreedRamFile> selectBreedingUseViewBreedRamFileList(ViewBreedRamFile viewBreedRamFile) {
        return viewBreedRamFileMapper.selectBreedingUseViewBreedRamFileList(viewBreedRamFile);
    }

    // ========== 表操作方法实现 ==========

    @Override
    public BreedRamFile selectBreedRamFileById(Long id) {
        return breedRamFileMapper.selectBreedRamFileById(id);
    }

    @Override
    public List<BreedRamFile> selectBreedRamFileList(BreedRamFile breedRamFile) {
        return breedRamFileMapper.selectBreedRamFileList(breedRamFile);
    }

    @Override
    @Transactional
    public int insertBreedRamFile(BreedRamFile breedRamFile) {
        breedRamFile.setCreateTime(DateUtils.getNowDate());
        return breedRamFileMapper.insertBreedRamFile(breedRamFile);
    }

    @Override
    @Transactional
    public int updateBreedRamFile(BreedRamFile breedRamFile) {
        breedRamFile.setUpdateTime(DateUtils.getNowDate());
        return breedRamFileMapper.updateBreedRamFile(breedRamFile);
    }

    @Override
    @Transactional
    public int deleteBreedRamFileByIds(Long[] ids) {
        return breedRamFileMapper.deleteBreedRamFileByIds(ids);
    }

    @Override
    @Transactional
    public int deleteBreedRamFileById(Long id) {
        return breedRamFileMapper.deleteBreedRamFileById(id);
    }

    @Override
    public BreedRamFile selectBreedRamFileByOrdinaryEarNumber(String ordinaryEarNumber) {
        return breedRamFileMapper.selectBreedRamFileByOrdinaryEarNumber(ordinaryEarNumber);
    }

    @Override
    public List<BreedRamFile> selectBreedRamFileListByRanchId(Long ranchId) {
        return breedRamFileMapper.selectBreedRamFileListByRanchId(ranchId);
    }

    @Override
    public List<BreedRamFile> selectBreedRamFileListBySheepfoldId(Long sheepfoldId) {
        return breedRamFileMapper.selectBreedRamFileListBySheepfoldId(sheepfoldId);
    }

    @Override
    public List<BreedRamFile> selectCoreFlockBreedRamFileList(BreedRamFile breedRamFile) {
        return breedRamFileMapper.selectCoreFlockBreedRamFileList(breedRamFile);
    }

    @Override
    public List<BreedRamFile> selectBreedingUseBreedRamFileList(BreedRamFile breedRamFile) {
        return breedRamFileMapper.selectBreedingUseBreedRamFileList(breedRamFile);
    }

    @Override
    @Transactional
    public int syncSpecificRams(List<String> earNumbers) {
        int syncCount = 0;
        for (String earNumber : earNumbers) {
            try {
                SheepFile sheep = sheepFileMapper.selectSheepFileByManageTags(earNumber);
                if (sheep != null && sheep.getGender() == 2) {
                    BreedRamFile existingRam = breedRamFileMapper.selectBreedRamFileByOrdinaryEarNumber(earNumber);
                    if (existingRam == null) {
                        BreedRamFile newRam = buildRamFileFromSheep(sheep);
                        breedRamFileMapper.insertBreedRamFile(newRam);
                    } else {
                        updateRamFileFromSheep(existingRam, sheep);
                        breedRamFileMapper.updateBreedRamFile(existingRam);
                    }
                    syncCount++;
                }
            } catch (Exception e) {
                System.err.println("同步公羊档案失败,耳号:" + earNumber + ",错误:" + e.getMessage());
            }
        }
        return syncCount;
    }

    @Override
    public Map<String, Object> getBreedRamStatistics() {
        Map<String, Object> statistics = new HashMap<>();

        BreedRamFile queryParam = new BreedRamFile();
        List<BreedRamFile> allRams = breedRamFileMapper.selectBreedRamFileList(queryParam);
        statistics.put("totalRams", allRams.size());

        List<BreedRamFile> coreFlockRams = breedRamFileMapper.selectCoreFlockBreedRamFileList(queryParam);
        statistics.put("coreFlockRams", coreFlockRams.size());

        List<BreedRamFile> breedingUseRams = breedRamFileMapper.selectBreedingUseBreedRamFileList(queryParam);
        statistics.put("breedingUseRams", breedingUseRams.size());

        Map<String, Long> varietyCount = allRams.stream()
                .collect(Collectors.groupingBy(
                        ram -> ram.getVariety() != null ? ram.getVariety() : "未知",
                        Collectors.counting()
                ));
        statistics.put("varietyDistribution", varietyCount);

        Map<String, Long> ranchCount = allRams.stream()
                .collect(Collectors.groupingBy(
                        ram -> ram.getRanchName() != null ? ram.getRanchName() : "未知",
                        Collectors.counting()
                ));
        statistics.put("ranchDistribution", ranchCount);

        Double avgMonthAge = allRams.stream()
                .filter(ram -> ram.getMonthAge() != null)
                .mapToLong(BreedRamFile::getMonthAge)
                .average()
                .orElse(0.0);
        statistics.put("avgMonthAge", avgMonthAge);

        Double avgProlificacy = allRams.stream()
                .filter(ram -> ram.getProlificacy() != null)
                .mapToDouble(ram -> ram.getProlificacy().doubleValue())
                .average()
                .orElse(0.0);
        statistics.put("avgProlificacy", avgProlificacy);

        return statistics;
    }

    /**
     * 从sheep_file同步公羊数据到公羊档案
     */
    @Override
    @Transactional
    public int syncFromSheepFile() {
        List<SheepFile> rams = sheepFileMapper.selectRamList();
        int syncCount = 0;
        int updateCount = 0;
        int insertCount = 0;

        System.out.println("开始同步公羊数据,共找到 " + rams.size() + " 只公羊");

        for (SheepFile sheep : rams) {
            try {
                BreedRamFile existingRam = breedRamFileMapper
                        .selectBreedRamFileByOrdinaryEarNumber(sheep.getBsManageTags());

                if (existingRam == null) {
                    BreedRamFile newRam = buildRamFileFromSheep(sheep);
                    int result = breedRamFileMapper.insertBreedRamFile(newRam);
                    if (result > 0) {
                        insertCount++;
                        syncCount++;
                    }
                } else {
                    updateRamFileFromSheep(existingRam, sheep);
                    int result = breedRamFileMapper.updateBreedRamFile(existingRam);
                    if (result > 0) {
                        updateCount++;
                        syncCount++;
                    }
                }
            } catch (Exception e) {
                System.err.println("同步公羊档案失败,耳号:" + sheep.getBsManageTags()
                        + ",错误:" + e.getMessage());
                e.printStackTrace();
            }
        }

        System.out.println("同步完成:新增: " + insertCount + " 只,更新: " + updateCount + " 只");
        return syncCount;
    }

    /**
     * 从SheepFile构建完整的BreedRamFile对象
     */
    private BreedRamFile buildRamFileFromSheep(SheepFile sheep) {
        BreedRamFile ram = new BreedRamFile();

        // 1. 从sheep_file同步基础信息
        syncBasicInfoFromSheep(ram, sheep);

        // 2. 从raw_sperm_record同步采精信息 - 修复后的版本
        syncSpermInfoFromRecords(ram, sheep.getId());

        // 3. 从sc_breed_record、sc_lambing_record、sc_pregnancy_record同步配种和繁殖统计
        syncBreedingStatistics(ram, sheep.getBsManageTags());

        ram.setCreateTime(DateUtils.getNowDate());
        ram.setIsDelete(0L);

        return ram;
    }

    /**
     * 从SheepFile更新BreedRamFile
     */
    private void updateRamFileFromSheep(BreedRamFile ram, SheepFile sheep) {
        // 1. 更新基础信息
        syncBasicInfoFromSheep(ram, sheep);

        // 2. 更新采精信息 - 修复后的版本
        syncSpermInfoFromRecords(ram, sheep.getId());

        // 3. 更新配种和繁殖统计
        syncBreedingStatistics(ram, sheep.getBsManageTags());

        ram.setUpdateTime(DateUtils.getNowDate());
    }

    /**
     * 同步基础信息(从sheep_file)
     */
    private void syncBasicInfoFromSheep(BreedRamFile ram, SheepFile sheep) {
        ram.setManageTags(sheep.getBsManageTags());
        ram.setRanchId(sheep.getRanchId());
        ram.setRanchName(sheep.getDrRanch());
        ram.setSheepfoldId(sheep.getSheepfoldId());
        ram.setSheepfoldName(sheep.getSheepfoldName());
        ram.setElectronicTags(sheep.getElectronicTags());
        ram.setVarietyId(sheep.getVarietyId());
        ram.setVariety(sheep.getVariety());
        ram.setSheepCategory(sheep.getName());
        ram.setCurrentStatus(String.valueOf(sheep.getStatusId()));
        ram.setBirthday(sheep.getBirthday());
        ram.setMonthAge(sheep.getMonthAge());

        ram.setBirthWeight(sheep.getBirthWeight() != null ?
                BigDecimal.valueOf(sheep.getBirthWeight()) : null);
        ram.setWeaningDate(sheep.getWeaningDate());
        ram.setWeaningDayAge(sheep.getWeaningDayAge() != null ?
                Long.valueOf(sheep.getWeaningDayAge()) : null);
        ram.setWeaningWeight(sheep.getWeaningWeight() != null ?
                BigDecimal.valueOf(sheep.getWeaningWeight()) : null);
        ram.setWeaningDailyGain(sheep.getWeaningDailyGain() != null ?
                BigDecimal.valueOf(sheep.getWeaningDailyGain()) : null);
        ram.setCurrentWeight(sheep.getCurrentWeight() != null ?
                BigDecimal.valueOf(sheep.getCurrentWeight()) : null);

        ram.setFatherNumber(sheep.getFatherManageTags());
        ram.setMotherNumber(sheep.getMotherManageTags());
        ram.setGrandfatherNumber(sheep.getGrandfatherManageTags());
        ram.setGrandmotherNumber(sheep.getGrandmotherManageTags());
        ram.setMaternalGrandfatherNumber(sheep.getMaternalGrandfatherManageTags());
        ram.setMaternalGrandmotherNumber(sheep.getMaternalGrandmotherManageTags());
    }

    /**
     * 同步采精信息(从raw_sperm_record)
     *
     * 修复关键问题:
     * 1. 正确设置所有字段(性欲情况、阴囊周长、采精时间、精液品质)
     * 2. 确保字段名与数据库表字段对应
     */
    private void syncSpermInfoFromRecords(BreedRamFile ram, Long sheepId) {
        if (sheepId == null) {
            return;
        }

        try {
            RawSpermRecord latestSperm = rawSpermRecordMapper.selectLatestByRamId(sheepId);

            if (latestSperm != null) {
                // 【关键修复】确保所有字段都正确同步

                // 1. 性欲情况 - sexual_status
                ram.setSexualStatus(latestSperm.getSexualStatus());

                // 2. 阴囊周长 - scrotum_circumference
                ram.setScrotumCircumference(latestSperm.getScrotumCircumference());

                // 3. 采精时间 - sperm_collection_time (对应 pick_date)
                ram.setSpermCollectionTime(latestSperm.getPickDate());

                // 4. 精液量 - sperm_volume (对应 amount)
                ram.setSpermVolume(latestSperm.getAmount());

                // 5. 精液活力 - sperm_vitality (对应 vitallity)
                ram.setSpermVitality(latestSperm.getVitallity());

                // 6. 精液密度 - sperm_density (对应 density)
                ram.setSpermDensity(latestSperm.getDensity());

                // 7. 精液品质 - sperm_quality (对应 semen_quality)
                ram.setSpermQuality(latestSperm.getSemenQuality());

                System.out.println("成功同步采精信息 - 羊只ID: " + sheepId +
                        ", 性欲情况: " + latestSperm.getSexualStatus() +
                        ", 阴囊周长: " + latestSperm.getScrotumCircumference() +
                        ", 采精时间: " + latestSperm.getPickDate() +
                        ", 精液品质: " + latestSperm.getSemenQuality());
            } else {
                System.out.println("未找到采精记录 - 羊只ID: " + sheepId);
            }
        } catch (Exception e) {
            System.err.println("同步采精信息失败,羊只ID:" + sheepId + ",错误:" + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 同步配种和繁殖统计数据
     */
    private void syncBreedingStatistics(BreedRamFile ram, String ramManageTags) {
        if (ramManageTags == null || ramManageTags.trim().isEmpty()) {
            return;
        }

        try {
            // 1. 统计该公羊配了多少母羊(去重)
            Long totalMatedEwes = scBreedRecordMapper.countMatedEwesByRamId(ramManageTags);
            ram.setTotalMatedEwes(totalMatedEwes != null ? totalMatedEwes : 0L);

            // 2. 统计公羊后代数(从产羔记录)
            Long offspringCount = scLambingRecordMapper.countOffspringByRamId(ramManageTags);
            ram.setOffspringCount(offspringCount != null ? offspringCount : 0L);

            // 3. 计算多胎性 = 公羊后代数 / 配种母羊数
            if (totalMatedEwes != null && totalMatedEwes > 0 && offspringCount != null) {
                BigDecimal prolificacy = BigDecimal.valueOf(offspringCount)
                        .divide(BigDecimal.valueOf(totalMatedEwes), 2, RoundingMode.HALF_UP);
                ram.setProlificacy(prolificacy);
            } else {
                ram.setProlificacy(BigDecimal.ZERO);
            }

            // 4. 统计孕检相关数据
            syncPregnancyStatistics(ram, ramManageTags, totalMatedEwes);

        } catch (Exception e) {
            System.err.println("同步配种统计失败,耳号:" + ramManageTags + ",错误:" + e.getMessage());
        }
    }

    /**
     * 同步孕检统计数据
     */
    private void syncPregnancyStatistics(BreedRamFile ram, String ramManageTags, Long totalMatedEwes) {
        try {
            // 本交孕检母羊数(配种方式为本交=2的孕检有胎记录)
            Long naturalPregnantEwes = scPregnancyRecordMapper
                    .countPregnantEwesByRamIdAndBreedType(ramManageTags, 2);
            ram.setNaturalPregnancyCheckEwes(naturalPregnantEwes != null ? naturalPregnantEwes : 0L);

            // 本交受孕率%
            if (totalMatedEwes != null && totalMatedEwes > 0 && naturalPregnantEwes != null) {
                BigDecimal naturalRate = BigDecimal.valueOf(naturalPregnantEwes)
                        .multiply(BigDecimal.valueOf(100))
                        .divide(BigDecimal.valueOf(totalMatedEwes), 2, RoundingMode.HALF_UP);
                ram.setNaturalConceptionRate(naturalRate);
            } else {
                ram.setNaturalConceptionRate(BigDecimal.ZERO);
            }

            // 人工孕检母羊数(配种方式为人工授精=1的孕检有胎记录)
            Long artificialPregnantEwes = scPregnancyRecordMapper
                    .countPregnantEwesByRamIdAndBreedType(ramManageTags, 1);
            ram.setArtificialPregnancyCheckEwes(artificialPregnantEwes != null ? artificialPregnantEwes : 0L);

            // 人工受孕率%
            if (totalMatedEwes != null && totalMatedEwes > 0 && artificialPregnantEwes != null) {
                BigDecimal artificialRate = BigDecimal.valueOf(artificialPregnantEwes)
                        .multiply(BigDecimal.valueOf(100))
                        .divide(BigDecimal.valueOf(totalMatedEwes), 2, RoundingMode.HALF_UP);
                ram.setArtificialConceptionRate(artificialRate);
            } else {
                ram.setArtificialConceptionRate(BigDecimal.ZERO);
            }
        } catch (Exception e) {
            System.err.println("同步孕检统计失败,耳号:" + ramManageTags + ",错误:" + e.getMessage());
            e.printStackTrace();
        }
    }
}