import { createI18n } from 'vue-i18n'

export const defaultLang = 'zh'

const currentLang = localStorage.getItem('locale') || defaultLang

import zh from './zh'
import en from './en'
import vi from './vi'

export const messages = {
    zh,
    en,
    vi
}

export const getLocale = () => {
    const localLang = localStorage.getItem('locale') || defaultLang
    if (localLang && Object.keys(messages).includes(localLang)) {
        return localLang
    }
    return defaultLang
}

const i18n = createI18n({
    legacy: false,
    locale: getLocale(),
    fallbackLocale: defaultLang,
    messages
})

export const changeLanguage = (lang) => {
    if (!Object.keys(messages).includes(lang)) {
        console.warn(`语言标识 ${lang} 不存在，默认使用中文 ${defaultLang}`)
        lang = defaultLang
    }

    i18n.global.locale.value = lang
    localStorage.setItem('locale', lang)
    let timer = setTimeout(() => {
        clearTimeout(timer)
        location.reload();
    }, 100)
}

export default i18n
