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 CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = ['js', 'css']
const webpackPlatformSetting = require('plg-platform-setting/webpack-plugin')
const tmsScript = require('./script.js')

const baseTarget = 'http://tms-jxqn.upcloud.plg.com/api'//标准版环境
const textBaseTarget = 'http://192.168.1.88:30875' // 逸飞
//target: 'http://192.168.1.206:7002', // 正方体
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 isProd = true

const assetsCDN = {
  // webpack build externals

  externals: {
    vue: 'Vue',
    'vue-router': 'VueRouter',
    vuex: 'Vuex',
    axios: 'axios',
    echarts: 'echarts',
    'ant-design-vue': 'antd',
    plglib: 'plglib',
    moment: 'moment',
  },
  css: [],
  // https://unpkg.com/browse/vue@2.6.10/
  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',
    '//cdn.jsdelivr.net/npm/moment@2.29.1/moment.min.js',
    '//cdn.jsdelivr.net/npm/moment@2.29.1/locale/zh-cn.js',
    '//cdn.jsdelivr.net/npm/ant-design-vue@1.7.8/dist/antd.min.js',
    '//prolog0212.vicp.cc:36872/plglib.umd.min.0.0.69.js',
    '//cdn.jsdelivr.net/npm/echarts@5.1.1/dist/echarts.min.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'],
  }),
  // 下面是下载的插件的配置
  new CompressionWebpackPlugin({
    algorithm: 'gzip',
    test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
    threshold: 10240,
    minRatio: 0.6,
  }),
  new webpackPlatformSetting(),
]

if (process.env.NODE_ENV === 'production') {
  defaultPlugins.push(createThemeColorReplacerPlugin())
  // defaultPlugins.push(
  //   new webpack.optimize.LimitChunkCountPlugin({
  //     maxChunks: 5,
  //     minChunkSize: 100,
  //   })
  // )
}
/**依赖大小分析工具 npm run build:preview */
process.env.MODE == 'preview' ? defaultPlugins.push(new BundleAnalyzerPlugin()) : null
// defaultPlugins.push( new MonacoWebpackPlugin({
//   languages: ['sql'],
//   features: [],
//   publicPath: '/'}
// ));
// vue.config.js
const vueConfig = {
  configureWebpack: {
    optimization: {
      splitChunks: {
        cacheGroups: {
          JQPage: {
            name: 'JQPage',
            priority: -100,
            chunks:'initial',
            test: /(.*([\\/]JQ_Page[\\/]js)+?.*).js$/,
            enforce: true,
            reuseExistingChunk:true
          }
        }
      }
    },

    // webpack plugins
    devtool:!isProd&&'source-map',
    plugins: defaultPlugins,
    // if prod, add externals
    externals: process.env.MODE == 'cdn' ? assetsCDN.externals : {},
  },
  filenameHashing: true, //去掉文件名后的hash

  chainWebpack: (config) => {
    config.resolve.alias.set('@$', resolve('src')).set('jq', resolve('public/jq')).set('@plglib',  resolve('__plglib/packages'))
    // console.log('NODE_ENV', process.env)

    if (process.env.NODE_ENV == 'plglib') {
      /**用于联调测试组件库的开发模式 */

      //console.log('PLGLIB_PATH', process.env.PLGLIB_PATH)
      config.resolve.alias.set('plglib', resolve('_plglib'))
    }
    // config.plugin('monaco').use(new MonacoWebpackPlugin())
    // /\.(html)(\?.*)?$/


    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 (process.env.MODE == 'cdn') {
      config.plugin('html').tap((args) => {
        args[0].cdn = assetsCDN
        return args
      })
    }
    config.plugin('html').tap((args) => {
      args[0].scripts = tmsScript.scripts
      args[0].links = tmsScript.links
      return args
    })

    config.plugins.delete('prefetch')

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

    config.module
    .rule('jqhtml')
    .test(/(.*([\\/]JQ_Page[\\/]pages)+?.*).html$/)
    .use('html-loader')
    .loader('html-loader')
    .end();
    //config.optimization.splitChunks




  },

  css: {
    sourceMap: !isProd,

    loaderOptions: {
      less: {
        sourceMap: !isProd,

        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: 8001,

    proxy: {
      '/api': {
        target: baseTarget, // 云仓
        pathRewrite: {
          '^/api': '',
        },
      },
      '/images-host': {
        target: 'http://fe-file.upcloud.plg.com/files/', //图片host
        pathRewrite: {
          '^/images-host': '',
        },
      },
      '/textApi': {
        target: textBaseTarget, //测试代理
        pathRewrite: {
          '^/textApi': '',
        },
      },
      // UPCLOUD_RDC_TMS_MAINDATA_SERVICE:'/api/upcloud-rdc-tms-maindata-service',
      //  UPCLOUD_RDC_TMS_BUSINESS_SERVICE:'/api/upcloud-rdc-tms-business-service'
      '/business': {
        target: baseTarget + '/upcloud-rdc-tms-business-service',
        pathRewrite: {
          '^/business': '',
        },
      },
      '/maindata': {
        target: baseTarget + '/upcloud-rdc-tms-maindata-service',
        pathRewrite: {
          '^/maindata': '',
        },
      }

    },
  },

  // disable source map in production
  productionSourceMap: !isProd,
  lintOnSave: false,
  // babel-loader no-ignore node_modules/*
  transpileDependencies: [],
  /* 设计器运行时编译需要 */
  runtimeCompiler: true,
}



module.exports = vueConfig

