import { App, WritableComputedRef, ref, computed } from 'vue'
import { createI18n, I18n as BaseI18n } from 'vue-i18n'
import { deflangName, langNameEum, langNames, langNameDescs } from './constant'
import { localGetFactory, localSetFactory } from '@/util/store'
import { paramsToStr, strToParams } from "@/util";

// import zh from './zh'
// import en from './en'
// import ja from './ja'
// import jp from './ja'
// import kr from './kr'
// 接入weblate
import zhProgram from './weblate/zh.json'
import enProgram from './weblate/en.json'
import jaProgram from './weblate/ja.json'
import krProgram from './weblate/kr.json'
// zh.program = zhProgram.program
// en.program = enProgram.program
// ja.program = jaProgram.program

const langList = ref([]);

const localKey = 'lang'
const local = {
  get: localGetFactory(str => {
    if (str) {
      return str
    } else {
      const langs = Object.keys(langNameDescs)
      const defLang = window?.navigator?.language || 'zh'
      const navLang = langs.find(lang =>
        new RegExp(`-?${lang}-?`).test(defLang)
      )
      return navLang || langNameEum.en
    }
  }),
  set: localSetFactory((lang) => lang)
}
const getAllParams = () => {
  let href = window.location.href;
  let query = href.substring(href.indexOf("?") + 1);
  let vars = query.split("&");
  let obj = {};
  for (let i = 0; i < vars.length; i++) {
    let pair = vars[i].split("=");
    // 将参数名和参数值分别作为对象的属性名和属性值
    obj[pair[0]] = pair[1];
  }
  return obj;
};
const params = getAllParams()
export const lang = (params.lang || window.lang || local.get(localKey))
console.log('strToParams',params, lang, local.get(localKey))

if (lang !== local.get(localKey)) {
  local.set(localKey, lang)
}

const i18n = createI18n({
  legacy: false,
  fallbackLocale: deflangName,
  availableLocales: langNames,
  locale: lang,
  sync: true,
  silentTranslationWarn: true,
  missingWarn: false,
  silentFallbackWarn: true
})

i18n.global.setLocaleMessage('zh', zhProgram)
i18n.global.setLocaleMessage('en', enProgram)
i18n.global.setLocaleMessage('ja', jaProgram)
i18n.global.setLocaleMessage('kr', krProgram)
i18n.global.changeLang = (lang, reload = true) => {
  i18n.global.locale.value = lang
  local.set(localKey, lang)
  params.lang = lang
  if (reload) {
    location.search = paramsToStr(params)
  }
  // location.reload()
}

export const setupI18n = (app) => {
  app.config.globalProperties.$t = i18n.global.t
  app.use(i18n)
}
export const changeLang = i18n.global.changeLang
export const ui18n = i18n.global
export const useI18n = () => ui18n


export const getLangList = computed(() => langList.value)
export const setLangList = (list) => {
  langList.value = list
}