import React from "react";
import { Alert } from '@ttk/component'
import { config as appLoaderConfig, start } from '@ttk/app-loader'

// 初始化moment
import moment from 'moment'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')

/**
 * json或hook模块初始化
 */
const moduleInit = ({ apps, init }, config) => {
    if (Object.keys(apps).length && init) {
        return init(config)
    }
    return config;
}

/**
 * 加载json/hook模块后初始化
 * @param {*} param0 
 */
const loadModuleFederation = ([jsonModule, hookModule]) => {
    const apps = {}
    Object.assign(apps, jsonModule.apps, hookModule.apps);
    if (process.env.NODE_ENV === 'development') {
        console.log('jsonApps:', jsonModule.apps)
        console.log('hookApps:', hookModule.apps)
    }
   
    // （原来的）公共配置
    apps.config = (options) => {
        Object.keys(options).forEach(key => {
            const reg = new RegExp(`^${key === '*' ? '.*' : key}$`)
            Object.keys(apps).forEach(appName => {
                if (appName !== 'config') {
                    if (reg.test(appName) && apps[appName].config) {
                        apps[appName].config(options[key])
                    }
                }
            })
        })
    }
    apps.config({ '*': { apps } })
    
    let config = { apps };
    // json/hook模块单独配置
    config = moduleInit(jsonModule, config);
    config = moduleInit(hookModule, config);
    // 根据url的hash匹配启动App
    let startAppName;
    if (location && location.hash && (startAppName = /^#\/[^\/]+(?=\/?)/.exec(location.hash))) {
        // 去掉#/
        startAppName = startAppName[0].substring(2)
        config.startAppName = startAppName;
    }
    console.log(`startAppName:${config.startAppName}`)

    // appLoader配置
    appLoaderConfig(config);
    return {
        default: start
    }
}

/**
 * 显示错误信息，返回组件
 * @param {*} error 
 */
const showError = error => {
    console.error(error)
    return {
        // 函数组件
        default: () => (
            <Alert
                style={{margin: '20px'}}
                message={error.message}
                description={error.stack}
                type="error"
                showIcon
            />
        )
    }
}

let host;

/**
 * 返回Promise，能使用topLevelAwait功能时，注释掉
 */
host = Promise.all([import('ttk_json_apps'), import('ttk_hook_apps')])
.then(loadModuleFederation)
.catch(showError)

// 能使用topLevelAwait功能时，取消注释
// try {
//     host = await Promise.all([import('ttk_json_apps'), import('ttk_hook_apps')]);
// } catch(error) {
//     host = showError(error);
// }

export default host;
