import { createI18n } from 'vue-i18n' // import from runtime only
import {ref} from 'vue'
import elementEnLocale from 'element-plus/lib/locale/lang/en'
import elementZhLocale from 'element-plus/lib/locale/lang/zh-cn'
import elementJaLocale from 'element-plus/lib/locale/lang/ja'
import { getLanguage } from '../api/workflowManagement/index';
import key from '../constant/key'
import Cookies from 'js-cookie';

// User defined lang
import enLocale from './en'
import zhLocale from './zh-cn'
import jpLocale from './ja'

if (localStorage.getItem(key.languageKey) !== 'en' && localStorage.getItem(key.languageKey) !== 'jp') {
	localStorage.setItem(key.languageKey, 'ch')
	Cookies.set(key.language, 'ch')
}

const messages:any = ref({
	'en': {
		...enLocale,
		...elementEnLocale.el,
		No: 'No',
	},
	'ch': {
		...zhLocale,
		...elementZhLocale.el,
		No: 'No',
	},
	'jp': {
		...jpLocale,
		...elementJaLocale.el,
		No: 'No',
		'select.placeholder': '選択',
	},
})
getLanguage({ i_func_id: 'ALL',i_language: Cookies.get('i_language')}).then(res => {
	const data: any = {}
	for(const key of Object.keys(res.data)){
		data[String(key)] = res.data[key]
	}
	messages.value['en'] = { ...messages.value['en'], ...data }
	messages.value['ch'] = { ...messages.value['ch'], ...data }
	messages.value['jp'] = { ...messages.value['jp'], ...data }
})

export const getLocale = () => {
	// Default language is english
	return localStorage.getItem(key.languageKey) || 'ch'
}

const i18n = createI18n({
	legacy: false,
	locale: getLocale(),
	messages: messages.value,
})

export default i18n
