import { defineStore } from 'pinia'
import i18n from '@/locales/index.js'
import { useI18n } from 'vue-i18n'

const storeKey = 'LANGUAGE_STORE_KEY'

export const useLangStore = defineStore({
	id: 'lang',
	state: () => ({
		lang: !process.env.APP_LOCALE ? 'en' : process.env.APP_LOCALE,
		systemLang: '',
		languageList: [
			{
				name: 'English',
				key: 'en',
				requestKey: 'en'
			},
			{
				name: 'Indonesia',
				key: 'ind',
				requestKey: 'id'
			}
		]
	}),
	getters: {
		requestLocale: (state) => {
			if (!state.lang) { return 'en' }
			const map = [
				{
					locale: 'en',
					requestLocale: 'en'
				},
				{
					locale: 'ja',
					requestLocale: 'jp'
				},
				{
					locale: 'ind',
					requestLocale: 'id'
				},
			]
			const obj = map.find(el => {
				return state.lang.includes(el.locale) || el.locale.includes(state.lang)
			})
			if (obj) {
				return obj.requestLocale
			}
			return 'en'
		}
	},
	actions: {
		changeLanguage (lang) {
			if (!lang || lang === this.lang) {
				return
			}
			i18n.global.locale.value = lang
			
			this.lang = lang
			uni.setLocale(lang)

			uni.$emit('AppLangChange', lang)
			
			console.log('Change language success!', lang)
			this.saveToLocal()

			uni.reLaunch({
				url: '/pages/index/index'
			})
		},
		changeLang (item) {
			const lang = item.key
			if (!lang || lang === this.lang) {
				return
			}
			i18n.global.locale.value = lang
			
			this.lang = lang
			uni.setLocale(lang)

			uni.$emit('AppLangChange', lang)
			
			console.log('Change language success!', lang)
			this.saveToLocal()
			
			// #ifdef H5
			window.location.href = '/'
			// #endif

			// #ifdef APP-PLUS
			plus.runtime.restart()
			// #endif
		},
		asyncFromLocal () {
			const lang = uni.getStorageSync(storeKey)
			this.lang = lang || process.env.APP_LOCALE
			this.changeLanguage(lang)
		},
		saveToLocal () {
			uni.setStorageSync(storeKey, this.lang)
		},
	}
})
 