import path from 'path'
import pxtorem from 'postcss-pxtorem'
import { defineConfig, loadEnv } from 'vite'
import createVitePlugins from './vite/plugins'

export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd())
  const { VITE_APP_PUBLIC_PATH } = env
  return {
    base: VITE_APP_PUBLIC_PATH,
    plugins: createVitePlugins(env, command === 'build'),
    resolve: {
      alias: {
        '~': path.resolve(__dirname, './'),
        '@': path.resolve(__dirname, './src')
      },
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
    },
    // vite 相关配置
    server: {
      port: 8085,
      host: true,
      open: true,
      proxy: {
        '/dev-api': {
          // target: 'http://192.168.100.55:8080',
          target: 'https://sfa-qa.wxl66.cn/api',
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/dev-api/, '')
        },
        '/dev-promotion-api': {
          target: 'https://sfa-qa.wxl66.cn/promotion-api',
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/dev-promotion-api/, '')
        },
        '/ql_local': {
          target: 'http://192.168.131.48',
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/ql_local/, '')
        },
        '/bc_local': {
          target: 'http://192.168.131.5:8180',
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/bc_local/, '')
        }
      }
    },
    css: {
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove();
                }
              }
            },
          },
          pxtorem({
            rootValue({ file }) {
              return 37.5;
            },
            propList: ['*'],
            exclude: file => {
              if (file.indexOf('login')) return true
              if (file.indexOf('vant') !== -1) {
                return false
              } else if (file.indexOf('mobile_views') !== -1) {
                return false
              } else {
                return true
              }
            }
          })
        ]
      }
    }
  }
})
