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

export const i18n = createI18n({})

export const languageStore = createStore({
    state() {
        return {
            lang: localData.getRef('appLanguage'),
        }
    },
    actions: {
        // 设置语言
        async setLanguage(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
            this.state.lang = lang
        }
    }
})

const { actions, state } = languageStore
actions.setLanguage(state.lang)