const { ModuleFederationPlugin } = require("webpack").container;
const { dependencies } = require("./package.json");

function createShared(names) {
  return names.map((item) => ({
    singleton: true,
    strictVersion: true,
    eager: true,
    requiredVersion: dependencies[item],
  }));
}

function filterShared(keys) {
  let newDeps = {};
  for (let i in dependencies) {
    if (!keys.includes(i)) {
      newDeps[i] = dependencies[i];
    }
  }
  return newDeps;
}

const isDev = process.env.NODE_ENV !== "production";
// 远程模块域名
const REMOTE_ORIGIN = isDev ? "http://localhost:9000" : process.env.REMOTE_URL;
// 远程模块部署版本
const REMOTE_VERSION = "v1_0";
// 拼接部署地址与模块对应版本号
const remoteOrigin = `${REMOTE_ORIGIN}/${REMOTE_VERSION}/`;

// 模块联邦
module.exports = function (config, env) {
  if (process.env.REACT_APP_SATURN_ENV === "private") {
    return config;
  }
  if (!REMOTE_ORIGIN) {
    throw new Error(
      "打包失败：土星云远程模块地址不存在, 请在环境变量中设置 REMOTE_URL 为远程模块地址"
    );
  }
  // config.output.crossOriginLoading = "use-credentials";
  config.output.crossOriginLoading = "anonymous";
  console.log(`租户端远程地址：${remoteOrigin}`);
  console.log(`租户端版本：${REMOTE_VERSION}`);
  config.plugins.unshift(
    new ModuleFederationPlugin({
      name: "minio_console",
      remotes: {
        saturn_tenant: `saturn_tenant@${remoteOrigin}remoteEntry.js`,
      },
      // filename: "remoteEntry.js",
      // exposes: {
      //   "./PageLayout": "./src/screens/Console/Common/Layout/PageLayout.tsx",
      //   "./PageHeader":
      //     "./src/screens/Console/Common/PageHeader/PageHeader.tsx",
      //   "./history": "./src/history.ts",
      // },
      shared: {
        ...filterShared([
          // '@codemirror/lang-json',
          // '@codemirror/legacy-modes',
          // '@date-io/moment',
          // '@emotion/react',
          // '@emotion/styled',
          // '@mui/icons-material',
          "@mui/lab",
          "@mui/material",
          // '@mui/styled-engine-sc',
          // '@mui/styles',
          // '@uiw/react-codemirror',
          // 'history',
          "js-cookie",
          // 'kbar',
          // 'local-storage-fallback',
          // 'lodash',
          // 'minio',
          "moment",
          "react-chartjs-2",
          // 'react-copy-to-clipboard',
          // 'react-dropzone',
          // 'react-grid-layout',
          // 'react-hot-loader',
          // 'react-moment',
          // 'react-virtualized',
          // 'react-window',
          // 'react-window-infinite-loader',
          // 'recharts',
          "superagent",
          // 'use-debounce',
          // 'websocket',
          "chart.js",
        ]),
        ...createShared([
          "react",
          "react-dom",
          "react-router-dom",
          "react-redux",
          "redux",
          "redux-thunk",
        ]),
      },
    })
  );
  return config;
};
