import { nextTick } from 'vue'
import { useI18n, createI18n } from 'vue-i18n'
import browser from '@/utils/browser'

export { useI18n }
export const SUPPORT_LOCALES = ['zh_CN', 'en', 'zh_HK']


export function getLocale() {
    let lang = browser.getURLParam('lang')
    if (!lang) {
        lang = window.navigator.language || window.navigator.userLanguage || null
        if (lang && /^en/.test(lang)) {
            console.log('自动获取浏览器语言:' + lang)
            lang = 'en'
        }
        else if (lang && /^zh_CN/.test(lang)) {
            lang = 'zh_CN'
        }
        else {
            lang = 'zh_HK'
        }
    }
    return lang 
    // 先不更新多语言
    // return 'zh_HK'
}

export function setupI18n(options = { locale: 'zh_HK' }) {
    console.log(options.locale);
    const i18n = createI18n(options)
    // 先不更新多语言
    // setI18nLanguage(i18n, 'zh_HK')

    setI18nLanguage(i18n, options.locale)

    return i18n
}

export function setI18nLanguage(i18n, locale) {
    //先不更新多语言
    // locale = 'zh_HK'
    if (i18n.mode === 'legacy') {
        i18n.global.locale = locale
    } else {
        i18n.global.locale.value = locale
    }
    /**
     * NOTE:
     * If you need to specify the language setting for headers, such as the `fetch` API, set it here.
     * The following is an example for axios.
     *
     * axios.defaults.headers.common['Accept-Language'] = locale
     */

    document.querySelector('html').setAttribute('lang', locale)
}

export async function loadLocaleMessages(i18n, locale) {
    // load locale messages with dynamic import
    // set locale and locale message

    const messages = await import(/* webpackChunkName: "locale-[request]" */ `../locales/${locale}.json`)
    i18n.global.setLocaleMessage(locale, messages.default)

    return nextTick()
}

export default setupI18n({
    globalInjection: true,
    legacy: false,
    locale: '',
    fallbackLocale: 'zh_HK',
})
