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

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zhyc.module.produce.breed.mapper.ScEmbryoFlushMapper;
import com.zhyc.module.produce.breed.domain.ScEmbryoFlush;
import com.zhyc.module.produce.breed.service.IScEmbryoFlushService;

/**
 * 冲胚记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-11-28
 */
@Service
public class ScEmbryoFlushServiceImpl implements IScEmbryoFlushService
{
    @Autowired
    private ScEmbryoFlushMapper scEmbryoFlushMapper;

    /**
     * 品种ID常量
     * 1-湖羊, 2-东佛里生, 3-回交, 4-级杂一代, 5-级杂二代, 6-级杂三代, 7-1世代, 8-2世代, 9-3世代, 10-4世代
     */
    private static final int VARIETY_HUYANG = 1;        // 湖羊
    private static final int VARIETY_DONGFULISHENG = 2; // 东佛里生
    private static final int VARIETY_HUIJIAO = 3;       // 回交
    private static final int VARIETY_JIZA_1 = 4;        // 级杂一代
    private static final int VARIETY_JIZA_2 = 5;        // 级杂二代
    private static final int VARIETY_JIZA_3 = 6;        // 级杂三代
    private static final int VARIETY_SHIDAI_1 = 7;      // 1世代
    private static final int VARIETY_SHIDAI_2 = 8;      // 2世代
    private static final int VARIETY_SHIDAI_3 = 9;      // 3世代
    private static final int VARIETY_SHIDAI_4 = 10;     // 4世代

    /** 品种ID到名称的映射 */
    private static final Map<Integer, String> VARIETY_NAME_MAP = new HashMap<>();
    static {
        VARIETY_NAME_MAP.put(1, "湖羊");
        VARIETY_NAME_MAP.put(2, "东佛里生");
        VARIETY_NAME_MAP.put(3, "回交");
        VARIETY_NAME_MAP.put(4, "级杂一代");
        VARIETY_NAME_MAP.put(5, "级杂二代");
        VARIETY_NAME_MAP.put(6, "级杂三代");
        VARIETY_NAME_MAP.put(7, "一世代");
        VARIETY_NAME_MAP.put(8, "二世代");
        VARIETY_NAME_MAP.put(9, "三世代");
        VARIETY_NAME_MAP.put(10, "四世代");
    }

    @Override
    public ScEmbryoFlush selectScEmbryoFlushById(Long id)
    {
        return scEmbryoFlushMapper.selectScEmbryoFlushById(id);
    }

    @Override
    public List<ScEmbryoFlush> selectScEmbryoFlushList(ScEmbryoFlush scEmbryoFlush)
    {
        return scEmbryoFlushMapper.selectScEmbryoFlushList(scEmbryoFlush);
    }

    @Override
    public int insertScEmbryoFlush(ScEmbryoFlush scEmbryoFlush)
    {
        calculateEmbryoCount(scEmbryoFlush);
        return scEmbryoFlushMapper.insertScEmbryoFlush(scEmbryoFlush);
    }

    @Override
    public int updateScEmbryoFlush(ScEmbryoFlush scEmbryoFlush)
    {
        calculateEmbryoCount(scEmbryoFlush);
        return scEmbryoFlushMapper.updateScEmbryoFlush(scEmbryoFlush);
    }

    @Override
    public int deleteScEmbryoFlushByIds(Long[] ids)
    {
        return scEmbryoFlushMapper.deleteScEmbryoFlushByIds(ids);
    }

    @Override
    public int deleteScEmbryoFlushById(Long id)
    {
        return scEmbryoFlushMapper.deleteScEmbryoFlushById(id);
    }

    /**
     * 计算冲胚数和有效胚数量
     */
    private void calculateEmbryoCount(ScEmbryoFlush flush)
    {
        int gradeAPlus = flush.getGradeAPlus() != null ? flush.getGradeAPlus() : 0;
        int gradeA = flush.getGradeA() != null ? flush.getGradeA() : 0;
        int gradeB = flush.getGradeB() != null ? flush.getGradeB() : 0;
        int gradeC = flush.getGradeC() != null ? flush.getGradeC() : 0;
        int gradeD = flush.getGradeD() != null ? flush.getGradeD() : 0;
        int cell24 = flush.getCell24() != null ? flush.getCell24() : 0;
        int cell8 = flush.getCell8() != null ? flush.getCell8() : 0;
        int cell16 = flush.getCell16() != null ? flush.getCell16() : 0;
        int unfertilized = flush.getUnfertilized() != null ? flush.getUnfertilized() : 0;
        int degenerated = flush.getDegenerated() != null ? flush.getDegenerated() : 0;

        // 有效胚 = A+ + A + B + C + D
        flush.setValidEmbryo(gradeAPlus + gradeA + gradeB + gradeC + gradeD);

        // 冲胚数 = 所有数量求和
        flush.setTotalEmbryo(gradeAPlus + gradeA + gradeB + gradeC + gradeD
                + cell24 + cell8 + cell16 + unfertilized + degenerated);
    }

    /**
     * 根据供体母羊耳号获取关联信息
     */
    @Override
    public Map<String, Object> getDonorRelatedInfo(String donorFemaleNo)
    {
        Map<String, Object> result = new HashMap<>();

        if (donorFemaleNo == null || donorFemaleNo.trim().isEmpty()) {
            return result;
        }

        // 1. 查询母羊信息
        Map<String, Object> femaleInfo = scEmbryoFlushMapper.selectSheepInfoByManageTag(donorFemaleNo);
        if (femaleInfo == null || femaleInfo.isEmpty()) {
            return result;
        }

        String femaleVariety = (String) femaleInfo.get("variety");
        Integer femaleVarietyId = getIntValue(femaleInfo.get("varietyId"));

        result.put("donorFemaleVariety", femaleVariety);
        result.put("donorFemaleVarietyId", femaleVarietyId);
        result.put("ranchId", femaleInfo.get("ranchId"));
        result.put("ranchName", femaleInfo.get("ranchName"));

        // 2. 查询配种记录获取公羊信息
        Map<String, Object> breedRecord = scEmbryoFlushMapper.selectBreedRecordByEwe(donorFemaleNo);
        if (breedRecord != null && !breedRecord.isEmpty()) {
            String maleNo = (String) breedRecord.get("donorMaleNo"); // 这里的 Key 必须对应 SQL 里的别名
            result.put("donorMaleNo", maleNo);
            result.put("matingDate", breedRecord.get("matingDate"));

            // 3. 查询公羊品种
            if (maleNo != null && !maleNo.trim().isEmpty()) {
                Map<String, Object> maleInfo = scEmbryoFlushMapper.selectSheepInfoByManageTag(maleNo);
                if (maleInfo != null && !maleInfo.isEmpty()) {
                    String maleVariety = (String) maleInfo.get("variety");
                    result.put("donorMaleVariety", maleVariety);

                    // 4. 【关键修复】使用品种名称计算胚胎品种
                    // 这样可以确保无论数据库ID是多少，只要名字是对的就能算出结果
                    Integer mId = getVarietyIdByName(maleVariety);
                    Integer fId = getVarietyIdByName(femaleVariety);

                    if (mId != null && fId != null) {
                        String embryoVariety = calculateEmbryoVarietyById(mId, fId);
                        result.put("embryoVariety", embryoVariety);
                    }
                }
            }
        }

        return result;
    }


    /**
     * 安全获取Integer值
     */
    private Integer getIntValue(Object obj) {
        if (obj == null) {
            return null;
        }
        if (obj instanceof Integer) {
            return (Integer) obj;
        }
        if (obj instanceof Long) {
            return ((Long) obj).intValue();
        }
        if (obj instanceof Number) {
            return ((Number) obj).intValue();
        }
        try {
            return Integer.parseInt(obj.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    /**
     * 根据品种名称获取ID
     */
    private Integer getVarietyIdByName(String name) {
        if (name == null) return null;
        for (Map.Entry<Integer, String> entry : VARIETY_NAME_MAP.entrySet()) {
            if (entry.getValue().equals(name)) {
                return entry.getKey();
            }
        }
        return null;
    }

    /**
     * 根据父母品种名称计算胚胎品种（接口方法）
     */
    @Override
    public String calculateEmbryoVariety(String maleVariety, String femaleVariety)
    {
        Integer maleId = getVarietyIdByName(maleVariety);
        Integer femaleId = getVarietyIdByName(femaleVariety);
        if (maleId == null || femaleId == null) {
            return null;
        }
        return calculateEmbryoVarietyById(maleId, femaleId);
    }

    /**
     * 根据父母品种ID计算胚胎品种（核心计算方法）
     *
     * 品种规则:
     * 1-湖羊, 2-东佛里生, 3-回交, 4-级杂一代, 5-级杂二代, 6-级杂三代, 7-1世代, 8-2世代, 9-3世代, 10-4世代
     *
     * 计算规则(根据图片):
     * - 湖羊(公) × 湖羊(母) → 湖羊
     * - 东佛里生(公) × 东佛里生(母) → 东佛里生
     * - 东佛里生(公) × 湖羊(母) → 级杂一代
     * - 东佛里生(公) × 级杂一代(母) → 级杂二代
     * - 东佛里生(公) × 级杂二代(母) → 级杂三代
     * - 东佛里生(公) × 级杂三代(母) → 东佛里生
     * - 湖羊(公) × 级杂三代(母) → 回交
     * - 湖羊(公) × 回交(母) → 回交
     * - 世代计算...
     *
     * @param maleVarietyId 公羊品种ID
     * @param femaleVarietyId 母羊品种ID
     * @return 胚胎品种名称
     */
    public String calculateEmbryoVarietyById(Integer maleVarietyId, Integer femaleVarietyId)
    {
        if (maleVarietyId == null || femaleVarietyId == null) {
            return null;
        }

        int male = maleVarietyId;
        int female = femaleVarietyId;

        // 湖羊(公) × 湖羊(母) → 湖羊
        if (male == VARIETY_HUYANG && female == VARIETY_HUYANG) {
            return VARIETY_NAME_MAP.get(VARIETY_HUYANG);
        }

        // 东佛里生(公) × 东佛里生(母) → 东佛里生
        if (male == VARIETY_DONGFULISHENG && female == VARIETY_DONGFULISHENG) {
            return VARIETY_NAME_MAP.get(VARIETY_DONGFULISHENG);
        }

        // 东佛里生(公) × 湖羊(母) → 级杂一代
        if (male == VARIETY_DONGFULISHENG && female == VARIETY_HUYANG) {
            return VARIETY_NAME_MAP.get(VARIETY_JIZA_1);
        }

        // 东佛里生(公) × 级杂一代(母) → 级杂二代
        if (male == VARIETY_DONGFULISHENG && female == VARIETY_JIZA_1) {
            return VARIETY_NAME_MAP.get(VARIETY_JIZA_2);
        }

        // 东佛里生(公) × 级杂二代(母) → 级杂三代
        if (male == VARIETY_DONGFULISHENG && female == VARIETY_JIZA_2) {
            return VARIETY_NAME_MAP.get(VARIETY_JIZA_3);
        }

        // 东佛里生(公) × 级杂三代(母) → 东佛里生
        if (male == VARIETY_DONGFULISHENG && female == VARIETY_JIZA_3) {
            return VARIETY_NAME_MAP.get(VARIETY_DONGFULISHENG);
        }

        // 湖羊(公) × 级杂三代(母) → 回交
        if (male == VARIETY_HUYANG && female == VARIETY_JIZA_3) {
            return VARIETY_NAME_MAP.get(VARIETY_HUIJIAO);
        }

        // 湖羊(公) × 回交(母) → 回交
        if (male == VARIETY_HUYANG && female == VARIETY_HUIJIAO) {
            return VARIETY_NAME_MAP.get(VARIETY_HUIJIAO);
        }

        // ========== 世代计算规则 ==========
        // 级杂二代(BM)或n世代(SM) × 级杂一代/级杂二代/级杂三代/回交(公) → 世代

        // 判断公羊是否为可产生世代的品种(级杂一代/二代/三代/回交)
        boolean isMaleCapableOfGeneration = (male >= 3 && male <= 10);

        if (isMaleCapableOfGeneration) {
            // 级杂二代(母) x 任意合格公羊 -> 一世代
            if (female == VARIETY_JIZA_2) {
                return VARIETY_NAME_MAP.get(VARIETY_SHIDAI_1);
            }
            // 一世代(母) x 任意合格公羊 -> 二世代
            if (female == VARIETY_SHIDAI_1) {
                return VARIETY_NAME_MAP.get(VARIETY_SHIDAI_2);
            }
            // 二世代(母) x 任意合格公羊 -> 三世代
            if (female == VARIETY_SHIDAI_2) {
                return VARIETY_NAME_MAP.get(VARIETY_SHIDAI_3);
            }
            // 三世代(母) x 任意合格公羊 -> 四世代
            if (female == VARIETY_SHIDAI_3) {
                return VARIETY_NAME_MAP.get(VARIETY_SHIDAI_4);
            }
        }

        // 默认返回null，表示无法计算或规则未覆盖
        return null;
    }

    @Override
    public List<Map<String, Object>> selectDonorFemaleList()
    {
        return scEmbryoFlushMapper.selectDonorFemaleList();
    }
}