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 remoteOrigin = isDev ? "http://localhost:9000" : process.env.REMOTE_URL;

if (!remoteOrigin) {
  throw new Error(
    "打包失败：土星云远程模块地址不存在, 请在环境变量中设置 REMOTE_URL 为远程模块地址"
  );
}
// 模块联邦
module.exports = function (config, env) {
  if (process.env.REACT_APP_SATURN_ENV === "private") {
    return config;
  }
  // config.output.crossOriginLoading = "use-credentials";
  config.output.crossOriginLoading = "anonymous";
  console.log(`土星云业务远程地址为：${remoteOrigin}`);
  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;
};
