import reduce from "lodash/reduce";
import ApiConstant from "@/api/ApiConstant";
import Settings from "@/config/settings";

export default (nuxtContext) => {
  const {
    $axios,
    store,
    app: { i18n: $i18n },
  } = nuxtContext;
  return new Promise((resolve, reject) => {
    const p = [
      $axios({
        url: `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:CORE:I18N_LANGUAGE`,
        method: "GET",
        params: { enableFlag: "Y" },
      }),
      $axios({
        url: `${ApiConstant.PREFIX_CORE}/api/sys/i18n/list-modify`,
        headers: {
          Authorization: "",
        },
        method: "GET",
      }),
      $axios({ url: `${ApiConstant.PREFIX_CORE}/api/sys/config/list` }),
    ];

    // 保留axios中header信息 国际化处理
    Promise.all(p)
      .then((res) => {
        // 设置languages
        store.commit(
          "app/SET_LANGUAGES",
          res[0].data.data?.map((item) => ({
            label: item.label,
            value: item.value,
          }))
        );

        // 国际化信息获取成功
        store.commit("app/SET_I18N_READY", true);
        store.state.app.languages
          .map((item) => item.value)
          .forEach((lang) => {
            const reg = new RegExp(`_${lang}$`);
            $i18n.setLocaleMessage(lang, {
              // 本地国际化
              ...$i18n.messages[lang],
              // 接口国际化
              ...reduce(
                res[1].data.data,
                function (result, value, key) {
                  if (reg.test(key)) {
                    // eslint-disable-next-line
                  result[key.replace(reg, "")] = value;
                  }
                  return result;
                },
                {}
              ),
            });
          });
        // 系统配置
        store.commit("app/SET_SYSTEM_CONFIG", {
          ...res[2].data.data,
          SYSTEM_TITLE: res[2].data.data.SYSTEM_TITLE || Settings.title,
          // DOMAIN_LOGIN_FLAG: 1,
        });

        resolve();
      })
      .catch((_err) => {
        reject(_err);
      });
  });
};
