import { toRefs, shallowReadonly, ShallowRef } from 'vue'
import axios from 'axios'
import { createI18n } from 'vue-i18n'
import { Language } from '@/constants/language'
import { VueStore } from '../base'
import WebStorage from '@/utils/storage/base'

interface StoreState {
    lang: ShallowRef<Language>;
}

const store = new (class extends VueStore<StoreState>{
    constructor() {
        const storage = new WebStorage<Language>(localStorage, 'language', Language.ZhCN)
        const state: StoreState = {
            lang: storage.getRef()
        }

        super(state)
        const lang = this.state.lang
        this.actions.setLanguage(lang)
    }

    i18n = createI18n({})

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

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

            this.i18n.global.locale = lang
            this.state.lang = lang
        }
    }
})

export function useLanguageStore() {
    return shallowReadonly({
        i18n: store.i18n,
        ...toRefs(store.state),
        ...store.actions,
        ...store.methods,
    })
}