package org.dromara.web.service;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 营养代谢基础值查询工具类
 * 支持通过营养素名称、性别和年龄查询推荐值
 */
public class NutritionDataUtil {

    // 营养素数据映射表
    private static final Map<String, Map<String, String>> NUTRIENT_MAP = new HashMap<>();

    // 年龄范围映射表
    private static final Map<String, AgeRange> AGE_RANGE_MAP = new HashMap<>();

    // 年龄范围类
    private static class AgeRange {
        final int min;
        final int max;
        final String groupName;

        AgeRange(int min, int max, String groupName) {
            this.min = min;
            this.max = max;
            this.groupName = groupName;
        }

        boolean contains(int age) {
            return age >= min && age <= max;
        }
    }

    static {
        // 初始化年龄范围映射
        initializeAgeRanges();
        // 初始化营养素数据
        initializeNutrientData();
    }

    // 初始化年龄范围
    private static void initializeAgeRanges() {
        AGE_RANGE_MAP.put("0-6月", new AgeRange(0, 0, "0-6月"));
        AGE_RANGE_MAP.put("7-12月", new AgeRange(0, 1, "7-12月"));
        AGE_RANGE_MAP.put("1-3岁", new AgeRange(1, 3, "1-3岁"));
        AGE_RANGE_MAP.put("4-6岁", new AgeRange(4, 6, "4-6岁"));
        AGE_RANGE_MAP.put("7-10岁", new AgeRange(7, 10, "7-10岁"));
        AGE_RANGE_MAP.put("11-13岁", new AgeRange(11, 13, "11-13岁"));
        AGE_RANGE_MAP.put("14-17岁", new AgeRange(14, 17, "14-17岁"));
        AGE_RANGE_MAP.put("18-49岁", new AgeRange(18, 49, "18-49岁"));
        AGE_RANGE_MAP.put("50-64岁", new AgeRange(50, 64, "50-64岁"));
        AGE_RANGE_MAP.put("≥65岁", new AgeRange(65, Integer.MAX_VALUE, "≥65岁"));
        AGE_RANGE_MAP.put("孕妇", new AgeRange(-1, -1, "孕妇（中期/晚期）"));
        AGE_RANGE_MAP.put("乳母", new AgeRange(-1, -1, "乳母"));
    }

    // 初始化营养素数据
    private static void initializeNutrientData() {
        // 常量元素
        addNutrientData("钙", "mg", "300 (AI)", "350 (AI)", "600", "800", "1000", "1200", "1000", "800", "1000", "1000", "1000/1200", "1000");
        addNutrientData("磷", "mg", "160 (AI)", "280 (AI)", "400", "500", "600", "800", "700", "700", "700", "700", "700", "700");
        addNutrientData("钾", "mg", "350 (AI)", "450 (AI)", "700", "900", "1300", "1800", "2000", "2000", "2000", "2000", "2000", "2000");
        addNutrientData("钠", "mg", "170 (AI)", "350 (AI)", "700", "900", "1200", "1500", "1500", "1500", "1500", "1500", "1500", "1500");
        addNutrientData("镁", "mg", "25 (AI)", "40 (AI)", "100", "120", "150", "200", "250", "330", "330", "330", "350", "350");
        addNutrientData("氯", "mg", "270 (AI)", "540 (AI)", "1000", "1200", "1700", "2300", "2300", "2300", "2300", "2300", "2300", "2300");

        // 微量元素
        addNutrientData("铁", "mg", "0.3 (AI)", "10", "9", "10", "12", "男16/女20", "男15/女20", "男12/女20", "12", "12", "24", "13");
        addNutrientData("锌", "mg", "1.5 (AI)", "3 (AI)", "4", "5", "7", "男10/女9", "男12.5/女7.5", "男12.5/女7.5", "男12.5/女7.5", "男12.5/女7.5", "10/12.5", "16.5");
        addNutrientData("硒", "μg", "15 (AI)", "20 (AI)", "20", "25", "30", "40", "50", "60", "60", "60", "65", "75");
        addNutrientData("铜", "mg", "0.2 (AI)", "0.3 (AI)", "0.8", "0.9", "1", "1.1", "1.1", "0.8", "0.8", "0.8", "1.3", "1.3");
        addNutrientData("锰", "mg", "0.05 (AI)", "0.08 (AI)", "1.5", "2.5", "3.5", "4.5", "4.5", "4.5", "4.5", "4.5", "4.5", "4.5");
        addNutrientData("碘", "μg", "85 (AI)", "115 (AI)", "90", "90", "120", "120", "120", "120", "120", "120", "230", "240");
        addNutrientData("氟", "mg", "0.01 (AI)", "0.05 (AI)", "0.7", "1", "1.5", "2", "2.5", "3", "3", "3", "3", "3");
        addNutrientData("铬", "μg", "5 (AI)", "10 (AI)", "15", "20", "25", "30", "30", "50", "50", "50", "50", "50");
        addNutrientData("钼", "μg", "2 (AI)", "4 (AI)", "6", "8", "10", "12", "15", "30", "30", "30", "30", "30");

        // 脂溶性维生素
        addNutrientData("维生素A", "μg RE", "400 (AI)", "400 (AI)", "400", "500", "600", "700", "700", "800", "700", "700", "800/900", "1200");
        addNutrientData("维生素D", "μg", "10 (AI)", "10 (AI)", "10", "10", "10", "10", "10", "10", "10", "10", "10", "10");
        addNutrientData("维生素E", "mg α-TE", "3 (AI)", "4 (AI)", "6", "7", "9", "11", "14", "14", "14", "14", "14", "14");
        addNutrientData("维生素K", "μg", "2 (AI)", "2.5 (AI)", "25", "30", "40", "50", "60", "80", "80", "80", "80", "80");

        // 水溶性维生素
        addNutrientData("维生素B1", "mg", "0.2 (AI)", "0.3 (AI)", "0.6", "0.8", "1", "男1.2/女1.0", "男1.3/女1.1", "男1.4/女1.2", "男1.4/女1.2", "男1.4/女1.2", "1.5/1.6", "1.6");
        addNutrientData("维生素B2", "mg", "0.2 (AI)", "0.3 (AI)", "0.6", "0.8", "1", "男1.2/女1.0", "男1.3/女1.1", "男1.4/女1.2", "男1.4/女1.2", "男1.4/女1.2", "1.5/1.6", "1.7");
        addNutrientData("维生素B6", "mg", "0.1 (AI)", "0.2 (AI)", "0.6", "0.8", "1", "男1.2/女1.0", "男1.4/女1.2", "男1.4/女1.2", "男1.4/女1.2", "男1.4/女1.2", "1.8", "2");
        addNutrientData("维生素B12", "μg", "0.3 (AI)", "0.4 (AI)", "0.7", "1", "1.3", "1.6", "2", "2.4", "2.4", "2.4", "2.6", "2.8");
        addNutrientData("烟酸", "mg NE", "2 (AI)", "3 (AI)", "6", "8", "11", "男14/女12", "男16/女14", "男18/女14", "男18/女14", "男18/女14", "18", "18");
        addNutrientData("维生素C", "mg", "40 (AI)", "50 (AI)", "60", "70", "80", "90", "100", "100", "100", "100", "115/130", "150");
        addNutrientData("叶酸", "μg DFE", "65 (AI)", "80 (AI)", "150", "200", "250", "300", "350", "400", "400", "400", "600", "500");
        addNutrientData("胆碱", "mg", "125 (AI)", "150 (AI)", "175", "200", "250", "300", "350", "400", "400", "400", "450", "550");
        addNutrientData("生物素", "μg", "5 (AI)", "6 (AI)", "8", "12", "15", "20", "25", "30", "30", "30", "30", "35");
        addNutrientData("泛酸", "mg", "1.7 (AI)", "2.0 (AI)", "3", "4", "4", "5", "5", "5", "5", "5", "6", "7");

        // 其他
        addNutrientData("膳食纤维", "g", "-", "-", "13", "14", "15", "18", "20", "25", "25", "25", "25", "25");
    }

    // 添加营养素数据
    private static void addNutrientData(String nutrient,  String... values) {
        Map<String, String> dataMap = new HashMap<>();
        String[] ageGroups = {
            "0-6月", "7-12月", "1-3岁", "4-6岁", "7-10岁",
            "11-13岁", "14-17岁", "18-49岁", "50-64岁", "≥65岁",
            "孕妇（中期/晚期）", "乳母"
        };

        for (int i = 0; i < values.length && i < ageGroups.length; i++) {
            dataMap.put(ageGroups[i], values[i] + (values[i].equals("-") ? "" : " " ));
        }
        NUTRIENT_MAP.put(nutrient, dataMap);
    }

    /**
     * 根据整数年龄获取营养推荐值
     *
     * @param nutrient 营养素名称
     * @param gender 性别 (男/女，当不需要区分性别时可传null)
     * @param age 实际年龄 (整数)
     * @return 对应的营养值 (带单位)，未找到返回null
     */
    public static String getValueByAge(String nutrient, String gender, int age) {
        String ageGroup = findAgeGroup(age);
        return getValue(nutrient, gender, ageGroup);
    }

    /**
     * 根据年龄组名称获取营养推荐值
     *
     * @param nutrient 营养素名称
     * @param gender 性别 (男/女，当不需要区分性别时可传null)
     * @param ageGroup 年龄组名称
     * @return 对应的营养值 (带单位)，未找到返回null
     */
    public static String getValue(String nutrient, String gender, String ageGroup) {
        // 获取标准化的年龄组
        String normalizedAgeGroup = normalizeAgeGroup(ageGroup);

        // 获取营养素数据
        Map<String, String> nutrientData = NUTRIENT_MAP.get(nutrient);
        if (nutrientData == null) return null;

        // 获取原始值
        String rawValue = nutrientData.get(normalizedAgeGroup);
        if (rawValue == null) return null;

        // 处理带斜杠的值
        if (rawValue.contains("/")) {
            // 处理孕妇中期/晚期
            if ("孕妇（中期/晚期）".equals(normalizedAgeGroup)) {
                String[] parts = rawValue.split(" ")[0].split("/");
                return parts.length > 1 ? parts[0] + " (中期)" + "/" + parts[1] + " (晚期)" : rawValue;
            }

            // 处理性别区分值
            if (gender != null && rawValue.contains("男") && rawValue.contains("女")) {
                return extractGenderSpecificValue(rawValue, gender);
            }
        }

        return rawValue;
    }

    // 根据年龄查找对应的年龄组
    private static String findAgeGroup(int age) {
        // 特殊处理婴儿(0岁)
        if (age == 0) return "0-6月";

        for (Map.Entry<String, AgeRange> entry : AGE_RANGE_MAP.entrySet()) {
            AgeRange range = entry.getValue();
            if (range.contains(age)) {
                return entry.getKey();
            }
        }
        return "18-49岁"; // 默认值
    }

    // 标准化年龄组
    private static String normalizeAgeGroup(String ageGroup) {
        if (AGE_RANGE_MAP.containsKey(ageGroup)) {
            return AGE_RANGE_MAP.get(ageGroup).groupName;
        }
        return ageGroup;
    }

    // 提取性别特定值
    private static String extractGenderSpecificValue(String rawValue, String gender) {
        // 分离值和单位
        String[] parts = rawValue.split(" ");
        String valuePart = parts[0];
        String unit = parts.length > 1 ? " " + parts[1] : "";

        Pattern pattern = Pattern.compile("男([^/]+)/女([^/]+)");
        Matcher matcher = pattern.matcher(valuePart);

        if (matcher.find()) {
            String maleValue = matcher.group(1).trim();
            String femaleValue = matcher.group(2).trim();
            return ("男".equals(gender) ? maleValue : femaleValue) + unit;
        }
        return rawValue;
    }

    // 获取所有支持查询的营养素列表
    public static String[] getAvailableNutrients() {
        return NUTRIENT_MAP.keySet().toArray(new String[0]);
    }

}
