/**
 * @file 该文件用于按需引入 ECharts 的图表与组件（优化版）
 * @author xxx
 * @recentUpdate 增加灵活的按需加载配置机制
 */

import * as echarts from 'echarts';

// 定义所有可用的图表和组件映射表
const CHART_COMPONENTS = {
    // 图表类型
    PieChart: () => import('echarts/charts').then(m => m.PieChart),
    LineChart: () => import('echarts/charts').then(m => m.LineChart),
    BarChart: () => import('echarts/charts').then(m => m.BarChart),
    ScatterChart: () => import('echarts/charts').then(m => m.ScatterChart),
    RadarChart: () => import('echarts/charts').then(m => m.RadarChart),
    MapChart: () => import('echarts/charts').then(m => m.MapChart),
    FunnelChart: () => import('echarts/charts').then(m => m.FunnelChart),
    SunburstChart: () => import('echarts/charts').then(m => m.SunburstChart),
    CustomChart: () => import('echarts/charts').then(m => m.CustomChart),
    HeatmapChart: () => import('echarts/charts').then(m => m.HeatmapChart),
    // 功能组件
    TitleComponent: () => import('echarts/components').then(m => m.TitleComponent),
    TooltipComponent: () => import('echarts/components').then(m => m.TooltipComponent),
    LegendComponent: () => import('echarts/components').then(m => m.LegendComponent),
    GridComponent: () => import('echarts/components').then(m => m.GridComponent),
    ToolboxComponent: () => import('echarts/components').then(m => m.ToolboxComponent),
    DataZoomComponent: () => import('echarts/components').then(m => m.DataZoomComponent),
    DataZoomInsideComponent: () => import('echarts/components').then(m => m.DataZoomInsideComponent),
    DataZoomSliderComponent: () => import('echarts/components').then(m => m.DataZoomSliderComponent),
    VisualMapComponent: () => import('echarts/components').then(m => m.VisualMapComponent),
    PolarComponent: () => import('echarts/components').then(m => m.PolarComponent),
    MarkLineComponent: () => import('echarts/components').then(m => m.MarkLineComponent),
    GeoComponent: () => import('echarts/components').then(m => m.GeoComponent),
    // 渲染器
    CanvasRenderer: () => import('echarts/renderers').then(m => m.CanvasRenderer)
};

// 地图数据懒加载
const MAP_DATA = {
    world: () => import('./json/world.json'),
    beijing: () => import('./json/beijing.json'),
    china: () => import('./json/china.json')
};

// 默认需要加载的组件
const DEFAULT_COMPONENTS = [
    // 核心组件
    'CanvasRenderer',
    'TooltipComponent',
    'GridComponent',
    // 地图相关组件
    'GeoComponent',
    'TitleComponent',
    'VisualMapComponent',
    'MapChart'
];

/**
 * 按需加载并注册指定的ECharts组件
 * @param {Array} components - 需要加载的组件名称数组
 * @returns {Promise<Array>} 已加载的组件数组
 */
async function loadComponents(components = []) {
    // 合并默认组件和自定义组件，并去重
    const allComponents = [...new Set([...DEFAULT_COMPONENTS, ...components])];

    try {
        const loadedComponents = await Promise.all(
            allComponents.map(async (componentName) => {
                if (CHART_COMPONENTS[componentName]) {
                    return await CHART_COMPONENTS[componentName]();
                }
                console.warn(`Component ${componentName} not found`);
                return null;
            })
        );

        // 过滤掉null值
        const validComponents = loadedComponents.filter(comp => comp !== null);

        // 注册组件
        echarts.use(validComponents);

        return validComponents;
    } catch (error) {
        console.error('Failed to load components:', error);
        throw error;
    }
}

/**
 * 按需加载并注册指定的地图数据
 * @param {Array} mapNames - 需要加载的地图名称数组
 * @returns {Promise<Object>} 加载的地图数据对象
 */
async function loadMaps(mapNames = []) {
    const loadedMaps = {};

    try {
        for (const mapName of mapNames) {
            if (MAP_DATA[mapName]) {
                const mapData = await MAP_DATA[mapName]();
                echarts.registerMap(mapName, mapData.default || mapData);
                loadedMaps[mapName] = true;
            }
        }

        return loadedMaps;
    } catch (error) {
        console.error('Failed to load map data:', error);
        throw error;
    }
}

/**
 * ECharts安装器函数
 * @param {HTMLElement} dom - DOM元素，用于初始化图表
 * @param {Object} options - 配置选项
 * @param {Array} options.components - 需要加载的组件列表
 * @param {Array} options.maps - 需要加载的地图数据列表
 * @param {Object} options.initOptions - ECharts初始化选项
 * @returns {Promise<Object>} ECharts实例或核心对象
 */
export default async function installer(dom, options = {}) {
    // 参数验证
    if (dom && !(dom instanceof HTMLElement)) {
        throw new Error('dom parameter must be an HTMLElement');
    }

    const {
        components = [],
        maps = [],
        initOptions = {}
    } = options;

    try {
        // 加载组件和地图数据
        await Promise.all([
            loadComponents(components),
            loadMaps(maps)
        ]);

        // 初始化ECharts实例
        return dom ? echarts.init(dom, null, initOptions) : echarts;
    } catch (error) {
        console.error('ECharts initialization failed:', error);
        throw error;
    }
}

// 导出辅助函数供直接使用
export { loadComponents, loadMaps, CHART_COMPONENTS, MAP_DATA };