import type { App } from 'vue';
import type { I18n, I18nOptions } from 'vue-i18n';

import { createI18n } from 'vue-i18n';
import { setHtmlPageLang, setLoadLocalePool } from './helper';
import { localeSetting } from '/@/settings/localeSetting';
import { useLocaleStoreWithOut } from '/@/store/modules/locale';
import { useGlobSetting } from '../hooks/setting';

const { fallback, availableLocales } = localeSetting;

const globSetting = useGlobSetting();

export let i18n: ReturnType<typeof createI18n>;

async function createI18nOptions(): Promise<I18nOptions> {
  const localeStore = useLocaleStoreWithOut();
  const locale = localeStore.getLocale;

  // const defaultLocal = await import(`./lang/${locale}.ts`);

  // const message = defaultLocal.default?.message ?? {};

  let message = {};
  try {
    const responseStream = await fetch(globSetting.apiUrl + '/language/main-language-json');
    const { data } = await responseStream.json();
    localeStore.setLanguageJson(data);
    message = data[locale];
  } catch {
    console.error('从服务器获取翻译数据出错，请联系管理员！');
    // throw new Error('从服务器获取翻译数据出错，请联系管理员！');
  }

  setHtmlPageLang(locale);
  setLoadLocalePool((loadLocalePool) => {
    loadLocalePool.push(locale);
  });

  return {
    legacy: false,
    locale,
    fallbackLocale: fallback,
    messages: {
      [locale]: message,
    },
    availableLocales: availableLocales,
    sync: true, //If you don’t want to inherit locale from global scope, you need to set sync of i18n component option to false.
    silentTranslationWarn: true, // true - warning off
    missingWarn: false, //missign flag  waring
    silentFallbackWarn: true,
  };
}

// setup i18n instance with glob
export async function setupI18n(app: App) {
  const options = await createI18nOptions();
  i18n = createI18n(options) as I18n;
  app.use(i18n);
}
