import axios from 'axios'
import { createI18n } from 'vue-i18n'
import { Language } from '@/constants/language'
import { defineStore } from '../store'
import { localData } from '../storage'

export const i18n = createI18n({})

export const useLanguageStore = defineStore(() => {
    const appLanguage = localData.getRef('appLanguage')

    // 设置语言
    const setLanguage = async (lang: Language) => {
        const locale = i18n.global.getLocaleMessage(lang)

        if (!Object.keys(locale).length) {
            await axios(`./language/${lang}.json`).then((res) => {
                i18n.global.setLocaleMessage(lang, res.data)
            }).catch(() => {
                // 默认语言
            })
        }

        i18n.global.locale = lang
        appLanguage.value = lang
    }

    setLanguage(appLanguage.value)

    return {
        appLanguage,
        setLanguage,
    }
})