import { set as _set } from "lodash";
import megaEnLocale from "@mega-design/ui-vue/es/locale/language/en_US"; // @mega-design/ui-vue lang
import megaZhLocale from "@mega-design/ui-vue/es/locale/language/zh_CN"; // @mega-design/ui-vue lang
import megaZhTWLocale from "@mega-design/ui-vue/es/locale/language/zh_TW"; // @mega-design/ui-vue lang
import Vue from "vue";
import VueI18n from "vue-i18n";

Vue.use(VueI18n);

const localeMessage = {
  // 本地国际化语言处理
  zh_CN: {},
  zh_TW: {},
  en: {},
};

// 处理数据
const handleLocaleI18n = (data, str = "") => {
  // eslint-disable-next-line
  for (const dataKey in data) {
    const path = str ? `${str}.${dataKey}` : str + dataKey;
    const keys = Object.keys(data[dataKey]);
    if (keys.length === 3 && keys.includes("en")) {
      _set(localeMessage.zh_CN, path.split("."), data[dataKey].zh_CN);
      _set(localeMessage.zh_TW, path.split("."), data[dataKey].zh_TW);
      _set(localeMessage.en, path.split("."), data[dataKey].en);
    } else {
      handleLocaleI18n(data[dataKey], path);
    }
  }
};

// https://webpack.js.org/guides/dependency-management/#requirecontext
const localeFiles = require.context("@/locales", true, /\.js$/);
// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
localeFiles.keys().forEach((modulePath) => {
  const value = localeFiles(modulePath);
  handleLocaleI18n(value.default);
});

export default ({ app, store, $axios }) => {
  // 获取浏览器语言
  const curLanguage = (
    navigator.language || navigator.browserLanguage
  ).toLowerCase();
  let localLanguage;
  if (curLanguage.includes("zh-cn") || curLanguage === "zh") {
    localLanguage = "zh_CN";
    // 假如浏览器语言是中文简体
  } else if (curLanguage.includes("zh-tw") || curLanguage.includes("zh-hk")) {
    localLanguage = "zh_TW";
    // 假如浏览器语言是中文繁体
  } else if (curLanguage.includes("en")) {
    localLanguage = "en";
    // 假如浏览器语言是英文
  } else {
    localLanguage = "en";
    // 假如浏览器语言是其它语言
  }
  store.commit("app/SET_LOCALE", localLanguage);
  // Set i18n instance on app
  // This way we can use it in middleware and pages asyncData/fetch
  // eslint-disable-next-line
  app.i18n = new VueI18n({
    locale: store.state.app.locale,
    fallbackLocale: "zh_CN",
    messages: {
      en: {
        ...megaEnLocale,
        ...localeMessage.en,
      },
      zh_TW: {
        ...megaZhTWLocale,
        ...localeMessage.zh_TW,
      },
      zh_CN: {
        ...megaZhLocale,
        ...localeMessage.zh_CN,
      },
    },
  });
};
