const path = require('path')

module.exports = {
  // 基础路径
  publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
  
  // 输出目录
  outputDir: 'dist',
  
  // 静态资源目录
  assetsDir: 'static',
  
  // 生产环境是否生成 sourceMap 文件
  productionSourceMap: false,
  
  // 开发服务器配置
  devServer: {
    port: 8080,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    proxy: {
      '/api': {
        target: process.env.VUE_APP_API_BASE_URL || 'http://localhost:3000',
        changeOrigin: true,
        pathRewrite: {
          '^/api': '/api'
        }
      }
    }
  },
  
  // 配置别名
  configureWebpack: {
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
        '@common': path.resolve(__dirname, 'common'),
        '@components': path.resolve(__dirname, 'common/components'),
        '@utils': path.resolve(__dirname, 'common/utils'),
        '@config': path.resolve(__dirname, 'common/config'),
        '@static': path.resolve(__dirname, 'static')
      }
    },
    // 性能优化
    optimization: {
      splitChunks: {
        chunks: 'all',
        cacheGroups: {
          vendor: {
            name: 'vendor',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial'
          },
          common: {
            name: 'common',
            minChunks: 2,
            priority: 5,
            chunks: 'initial',
            reuseExistingChunk: true
          }
        }
      }
    }
  },
  
  // CSS 相关配置
  css: {
    loaderOptions: {
      sass: {
        // 全局样式变量
        additionalData: `
          @import "@/common/styles/variables.scss";
          @import "@/common/styles/mixins.scss";
        `
      }
    }
  },
  
  // 链式操作配置
  chainWebpack: config => {
    // 移除 prefetch 插件
    config.plugins.delete('prefetch')
    
    // 移除 preload 插件
    config.plugins.delete('preload')
    
    // 图片压缩
    config.module
      .rule('images')
      .test(/\.(gif|png|jpe?g|svg)$/i)
      .use('image-webpack-loader')
      .loader('image-webpack-loader')
      .options({
        mozjpeg: {
          progressive: true,
          quality: 80
        },
        optipng: {
          enabled: false
        },
        pngquant: {
          quality: [0.65, 0.90],
          speed: 4
        },
        gifsicle: {
          interlaced: false
        }
      })
      .end()
  },
  
  // 第三方插件配置
  pluginOptions: {
    // uni-app 插件配置
    'uni-app': {
      // 自定义配置
    }
  },
  
  // 环境变量配置
  runtimeCompiler: true,
  
  // 并行处理
  parallel: require('os').cpus().length > 1,
  
  // PWA 配置
  pwa: {
    name: '智慧畜牧管理系统',
    themeColor: '#2E8B57',
    msTileColor: '#2E8B57',
    appleMobileWebAppCapable: 'yes',
    appleMobileWebAppStatusBarStyle: 'black',
    workboxPluginMode: 'InjectManifest',
    workboxOptions: {
      swSrc: 'src/sw.js'
    }
  }
}