import Vue from "vue";
import VueI18n from "vue-i18n";
import Cookies from "js-cookie";
import elementEnLocale from "element-ui/lib/locale/lang/en"; // element-ui英文语言包
import elementZhLocale from "element-ui/lib/locale/lang/zh-CN"; // element-ui中文语言包
import elementJaLocale from "element-ui/lib/locale/lang/ja"; // element-ui日文语言包
import enLocale from "./lang/en";
import zhLocale from "./lang/zh";
import jaLocale from "./lang/ja";

Vue.use(VueI18n);

const messages = {
  en: {
    ...enLocale,
    ...elementEnLocale,
  },
  zh: {
    ...zhLocale,
    ...elementZhLocale,
  },
  ja: {
    ...jaLocale,
    ...elementJaLocale,
  },
};

/**
 * 获取浏览器语言
 * @returns {string} 语言代码
 */
export function getLanguage() {
  const chooseLanguage = Cookies.get("language");
  if (chooseLanguage) return chooseLanguage;

  // 如果没有Cookie，则判断浏览器语言
  const language = (
    navigator.language || navigator.browserLanguage
  ).toLowerCase();
  const locales = Object.keys(messages);
  for (const locale of locales) {
    if (language.indexOf(locale) > -1) {
      return locale;
    }
  }
  return "zh"; // 默认中文
}

const i18n = new VueI18n({
  // 设置语言环境
  locale: getLanguage(),
  // 设置备用语言环境
  fallbackLocale: "zh",
  // 设置语言环境信息
  messages,
});

export default i18n;
