<template>
  <el-config-provider :locale="locale">
    <router-view />
    <message-box ref="msgbox" :options="msgOptions"/>
    <message-box ref="tipbox" :options="tipOptions" />
  </el-config-provider>
</template>

<script setup>
import { ref, provide, watch } from 'vue'
import { ElConfigProvider } from 'element-plus';
// import { handleThemeStyle } from '@/utils/theme'
import Locales from '@/locales/index'
// import useSettingsStore from '@/store/modules/settings'
import useAppStore from '@/store/modules/app'
import MessageBox from '@/components/MessageBox'
import { dotSpinner } from 'ldrs'
import { ring2 } from 'ldrs'
import { clientLang } from '@/utils/i18n'

ring2.register()
dotSpinner.register()

const { proxy } = getCurrentInstance();
const route = useRoute();

watch(route, (newRoute) => {
  if (newRoute.query && newRoute.query.language && ( newRoute.path == '/login' || newRoute.path.startsWith('/signUp') ) ) {
    changeLanguage(clientLang(newRoute.query.language))
  }
}, {
  immediate: true, deep: true
})

onMounted(() => {
  window.openMsg = openMsg
  window.showTip = showTip
})

const locale = ref(Locales[useAppStore().lang]);

const changeLanguage = (lang = 'en') => {
    if (lang) {
      if (lang == 'zh-cn') {
        locale.value = Locales['zh-cn']
      } else if (lang.startsWith('zh')) {
        locale.value = Locales['zh-tw']
      } else if (lang.startsWith('es')) {
        locale.value = Locales['es']
      } else if (lang.startsWith('ko')) {
        locale.value = Locales['ko']
      } else if (lang.startsWith('hi')) {
        locale.value = Locales['hi']
      } else if (lang.startsWith('vi')) {
        locale.value = Locales['vi']
      } else if (lang.startsWith('th')) {
        locale.value = Locales['th']
      } else if (lang.startsWith('id')) {
        locale.value = Locales['id']
      } else if (lang.startsWith('ar')) {
        locale.value = Locales['ar']
      } else if (lang.startsWith('en')) {
        locale.value = Locales['en']
      }
    }
    useAppStore().changeLanguage(lang)
}

const msgOptions = ref({})
const tipOptions = ref({})

function openMsg(options) {
  msgOptions.value = options
  return proxy.$refs.msgbox.openMsg()
}

function showTip(options) {
  options.type = "tip"
  options.closeIcon = true
  if (!options.width) {
    options.width = '410'
  }
  tipOptions.value = options
  return proxy.$refs.tipbox.showTip()
}

provide('changeLanguage', changeLanguage);
provide('openMsg', openMsg);
provide('showTip', showTip);

</script>
