import type { Locale } from 'antdv-next/dist/locale/index';

import type { App } from 'vue';

import { ref } from 'vue';

import {
  $t,
  setupLocale as coreSetup,
  mergeLocaleMessages,
} from '@vben/locales';

import antdDefaultLocale from 'antdv-next/dist/locale/zh_CN';
import dayjs from 'dayjs';

const antdLocale = ref<Locale>(antdDefaultLocale);

const modules = import.meta.glob('./langs/zh-CN/*.json', { eager: true });

function normalizeModule(module: unknown) {
  return module && typeof module === 'object' && 'default' in module
    ? (module as { default: Record<string, any> }).default
    : module;
}

function loadAppMessages() {
  const messages: Record<string, any> = {};
  for (const [path, module] of Object.entries(modules)) {
    const fileName = path.match(/\.\/langs\/zh-CN\/(.*)\.json$/)?.[1];
    if (!fileName) {
      continue;
    }
    const value = normalizeModule(module);
    if (fileName === 'runtime') {
      Object.assign(messages, value);
    } else {
      messages[fileName] = value;
    }
  }
  return messages;
}

mergeLocaleMessages(loadAppMessages());

/**
 * 加载第三方组件库的语言包
 */
async function loadThirdPartyMessage() {
  await Promise.all([loadAntdLocale(), loadDayjsLocale()]);
}

/**
 * 加载dayjs的语言包
 */
async function loadDayjsLocale() {
  await import('dayjs/locale/zh-cn');
  dayjs.locale('zh-cn');
}

/**
 * 加载antd的语言包
 */
async function loadAntdLocale() {
  antdLocale.value = antdDefaultLocale;
}

async function setupLocale(app: App) {
  await coreSetup(app);
  await loadThirdPartyMessage();
}

export { $t, antdLocale, setupLocale };
