/**
 * 行业领域相关处理工具方法
 */

import * as industryConfig from "../config/enum/industryEnum";

/**
 * 创建行业映射的函数
 * 构建一个从行业大类数字编码（1-97）到行业门类字母编码（A-T）的映射关系
 * keyof typeof industryConfig 获取该类型的所有键名
 * typeof industryConfig 获取 industryConfig 的类型
 * 结果是：'INDUSTRY' | 'A' | 'B' | 'C' | ... | 'T'
 * @returns {number:string} 返回映射对象，格式如 {1: "A", 2: "A", ..., 90: "R", ...}
 */
function createIndustryMap() {
    let map = {};
    
    // 获取所有以单个字母命名的子枚举（A-T）
    let subEnumKeys = Object.keys(industryConfig)
        .filter(key => key.length === 1 && /^[A-T]$/.test(key));
    
    subEnumKeys.forEach((categoryKey) => {
        let subEnum = industryConfig[categoryKey as keyof typeof industryConfig];
        if (subEnum && typeof subEnum === 'object') {
            Object.values(subEnum).forEach((value) => {
                if (typeof value === 'number') {
                    map[value] = categoryKey;
                }
            });
        }
    });
    
    return map;
}


/**
 * 调用函数初始化映射
 */
export const IndustryMap = createIndustryMap();


/**
 * 根据数字代码获取门类字母
 * getIndustryCategoryByCode(90);
 * @param code 
 * @returns "R"
 */
export function getIndustryCategoryByCode(code: number) {
    return IndustryMap[code] || null;
}


/**
 * 根据门类字母获取所有数字代码
 * getIndustryCodesByCategory('R')
 * @param category 
 * @returns [86, 87, 88, 89, 90]
 */
export function getIndustryCodesByCategory(category: string) {
    let subEnum = industryConfig[category as keyof typeof industryConfig];
    if (!subEnum || typeof subEnum !== 'object') return [];
    
    return Object.values(subEnum)
        .filter(v => typeof v === 'number') as number[];
}


/**
 * 获取完整的行业信息（包括门类和大类）
 * getIndustryFullInfo(90);
 * @param code 
 * @returns {category: "R", categoryName: "文化、体育和娱乐业", subCategoryName: "娱乐业"}
 */
export function getIndustryFullInfo(code: number) {
    let categoryKey = IndustryMap[code];
    if (!categoryKey) return null;
    
    // 获取门类名称
    let categoryName = industryConfig.INDUSTRY[categoryKey as keyof typeof industryConfig.INDUSTRY];
    
    // 获取大类名称
    let subEnum = industryConfig[categoryKey as keyof typeof industryConfig];
    let subCategoryName = '';
    
    if (subEnum && typeof subEnum === 'object') {
        // 反转枚举以通过值获取键
        let reversedSubEnum = Object.entries(subEnum).reduce((acc, [key, value]) => {
            if (typeof value === 'number') {
                acc[value] = key;
            }
            return acc;
        }, {} as Record<number, string>);
        
        subCategoryName = reversedSubEnum[code] || '';
    }
    
    return {
        category: categoryKey,
        categoryName: String(categoryName),
        subCategoryName
    };
}


