import { ref } from 'vue';
import { createI18n } from 'vue-i18n';
import dayjs from 'dayjs';
import zhCN from './lang/zh-CN';

export const locales: string[] = ['zhs', 'zh-TW', 'en', 'pt-BR'];

export const defaultLang = 'zhs';

export const langMap = {
  zhs: 'zh-CN',
  'zh-CN': 'zh-CN',
  en: 'en-US',
  'en-US': 'en-US',
};

const loadedLanguages = ref<string[]>([defaultLang]);

const i18n = createI18n({
  legacy: false,
  missingWarn: false,
  fallbackWarn: false,
  // 如果不需要国际化，可以打开如下两个配置，取消控制台的警告
  silentTranslationWarn: true,
  silentFallbackWarn: true,
  locale: langMap[defaultLang],
  messages: {
    ['zh-CN']: zhCN as any,
  },
});

function setI18nLanguage(lang: string) {
  i18n.global.locale = lang;
  // request.headers['Accept-Language'] = lang
  const HTML = document.querySelector('html');
  HTML && HTML.setAttribute('lang', lang);
  return lang;
}

export function loadLanguageAsync(lang: string = defaultLang): Promise<string> {
  const _lang = langMap[lang];
  return new Promise<string>(resolve => {
    const currentLocale = i18n.global;

    if (currentLocale.locale !== _lang) {
      if (!loadedLanguages.value.includes(_lang)) {
        return import(
          /* webpackChunkName: "lang-[request]" */
          /* 根据所用文件后缀(ts、js、vue)，自行添加后缀 */
          // eslint-disable-next-line comma-dangle
          /* @vite-ignore */ `./lang/${_lang}.ts`
        ).then(result => {
          const loadedLang = result.default;
          // set vue-i18n lang
          currentLocale.setLocaleMessage(_lang, loadedLang);
          // set dayjs lang
          // TODO: 有问题先注释掉
          // dayjs.updateLocale(loadedLang.dayjsLocaleName, loadedLang.dayjs);
          // save loaded
          loadedLanguages.value.push(_lang);
          return resolve(setI18nLanguage(_lang));
        });
      }
      return resolve(setI18nLanguage(_lang));
    }
    resolve(_lang);
  });
}

export default i18n;
