const path = require("path");
const webpack = require("webpack");
const GitRevisionPlugin = require("git-revision-webpack-plugin");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const GitRevision = new GitRevisionPlugin();
const buildDate = JSON.stringify(new Date().toLocaleString());
const createThemeColorReplacerPlugin = require("./config/plugin.config");
const theme = require("./src/config/theme.config");
const MonacoWebpackPlugin = require("monaco-editor-webpack-plugin");
// const serverCongfig = require('./src/config/serviceSettings')
const webpackPlatformSetting = require("plg-platform-setting/webpack-plugin");

function resolve(dir) {
  return path.join(__dirname, dir);
}

// check Git
function getGitHash() {
  try {
    return GitRevision.version();
  } catch (e) {}
  return "unknown";
}

const isProd = process.env.NODE_ENV === "production";

const assetsCDN = {
  // webpack build externals
  externals: {
    vue: "Vue",
    "vue-router": "VueRouter",
    vuex: "Vuex",
    axios: "axios",
  },
  css: [],
  js: [
    "//cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.min.js",
    "//cdn.jsdelivr.net/npm/vue-router@3.5.2/dist/vue-router.min.js",
    "//cdn.jsdelivr.net/npm/vuex@3.6.2/dist/vuex.min.js",
    "//cdn.jsdelivr.net/npm/axios@0.19.0/dist/axios.min.js",
    //at.alicdn.com/t/font_1780424_92kpfp3gue7.js
  ],
};

const defaultPlugins = [
  // Ignore all locale files of moment.js
  new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  new webpack.DefinePlugin({
    APP_VERSION: `"${require("./package.json").version}"`,
    GIT_HASH: JSON.stringify(getGitHash()),
    BUILD_DATE: buildDate,
  }),
  new MonacoWebpackPlugin({
    languages: ["javascript", "css", "html", "json", "sql"],
    features: ["coreCommands", "find"],
  }),
  //   createThemeColorReplacerPlugin(),
  new webpackPlatformSetting(),
];

/**依赖大小分析工具 npm run build:preview */
process.env.MODE == "preview" ? defaultPlugins.push(new BundleAnalyzerPlugin()) : null;

// vue.config.js
const vueConfig = {
  configureWebpack: {
    // webpack plugins
    plugins: defaultPlugins,
    // if prod, add externals
    // externals: isProd ? assetsCDN.externals : {}
  },
  filenameHashing: false, //去掉文件名后的hash

  chainWebpack: (config) => {
    config.resolve.alias.set("@$", resolve("src")).set("jq", resolve("public/jq"));
    console.log("NODE_ENV", process.env.NODE_ENV);
    if (process.env.NODE_ENV == "plglib") {
      /**用于联调测试组件库的开发模式 */
      const plglibPath = process.env.PLGLIB_PATH;
      console.log("PLGLIB_PATH", process.env.PLGLIB_PATH);
      config.resolve.alias.set("plglib", resolve("_plglib")).set("@plglib", plglibPath + "/packages");
    }

    const svgRule = config.module.rule("svg");
    svgRule.uses.clear();
    svgRule
      .oneOf("inline")
      .resourceQuery(/inline/)
      .use("vue-svg-icon-loader")
      .loader("vue-svg-icon-loader")
      .end()
      .end()
      .oneOf("external")
      .use("file-loader")
      .loader("file-loader")
      .options({
        name: "assets/[name].[hash:8].[ext]",
      });

    // if prod is on
    // assets require on cdn
    if (isProd) {
      config.plugin("html").tap((args) => {
        // args[0].cdn = assetsCDN
        return args;
      });
    }
    config.plugins.delete("prefetch");

    // /js/views-enterprise-img-enterprise-112-png.js

    // 去除生产环境下的 console
    if (isProd) {
      config.optimization.minimizer("terser").tap((options) => {
        options[0].terserOptions.compress.drop_console = true;
        return options;
      });
    }
  },

  css: {
    loaderOptions: {
      less: {
        modifyVars: {
          // less vars，customize ant design theme

          // 'primary-color': '#F5222D',
          // 'link-color': '#F5222D',
          "border-radius-base": "2px",
          ...theme,
        },
        // DO NOT REMOVE THIS LINE
        javascriptEnabled: true,
      },
    },
  },

  devServer: {
    // development server port 8000
    port: 8000,
    // If you want to turn on the proxy, please remove the mockjs /src/main.jsL11
    // proxy: {
    //   '/api': {
    //     target: 'https://mock.ihx.me/mock/5baf3052f7da7e07e04a5116/antd-pro',
    //     ws: false,
    //     changeOrigin: true
    //   }
    // }
    proxy: {
      "^/api": {
        // 通过配置来启动,有配置的使用配置，没有配置默认公司网关
        // target: 'http://192.168.1.212:7002', // 公司测试 conba
        // target: 'http://116.54.19.104:7002', // 昆中药 conba
        // target: 'http://192.168.1.88:30127', // 康恩贝 conba
        // target: "http://10.30.67.19:7002", // 思源
        // target: 'http://192.168.1.88:30262', // 思源医疗测试环境
        // target: "http://192.168.1.200:7002", // 鹰江开发环境
        target: "http://wms-qingniu.upcloud.plg.com", //青牛开发环境
        // target: "http://192.168.1.88:31533", //青牛测试环境
        // 192.168.1.37:27200/home
        pathRewrite: {
          "^/api": "/api",
        },
      },
        "^/qneis_": {
          target: "http://192.168.41.208:10019",
          pathRewrite: {
            "^/qneis_": "",
          },
        },
      "/localw": {
        target: "http://127.0.0.1:6060",
        changeOrigin: true,
        ws: false,
        pathRewrite: {
          "^/localw": "",
        },
      },
    },
  },
  // disable source map in production
  productionSourceMap: false,
  lintOnSave: false,
  // babel-loader no-ignore node_modules/*
  transpileDependencies: [],
  /* 设计器运行时编译需要 */
  runtimeCompiler: true,
};

// preview.pro.loacg.com only do not use in your production;
if (process.env.VUE_APP_PREVIEW === "true") {
  console.log("VUE_APP_PREVIEW", true);
  // add `ThemeColorReplacer` plugin to webpack plugins
  // vueConfig.configureWebpack.plugins.push(createThemeColorReplacerPlugin())
}

//vueConfig.configureWebpack.plugins.push(createThemeColorReplacerPlugin())

module.exports = vueConfig;
