const TransformPages = require('uni-read-pages')
const {webpack} = new TransformPages()

// 读取 manifest.json ，修改后重新写入
const fs = require('fs')
const path = require('path');

// 获取绝对路径
function resolve(dir) {
    return path.join(__dirname, dir)
}

const manifestPath = './src/manifest.json'
let Manifest = fs.readFileSync(manifestPath, { encoding: 'utf-8' })
function replaceManifest(path, value) {
    const arr = path.split('.')
    const len = arr.length
    const lastItem = arr[len - 1]

    let i = 0
    let ManifestArr = Manifest.split(/\n/)

    for (let index = 0; index < ManifestArr.length; index++) {
        const item = ManifestArr[index]
        if (new RegExp(`"${arr[i]}"`).test(item)) ++i;
        if (i === len) {
            const hasComma = /,/.test(item)
            if(typeof(value) === "boolean") {
              ManifestArr[index] = item.replace(new RegExp(`"${lastItem}"[\\s\\S]*:[\\s\\S]*`), `"${lastItem}": ${value}${hasComma ? ',' : ''}`)
            }else {
              ManifestArr[index] = item.replace(new RegExp(`"${lastItem}"[\\s\\S]*:[\\s\\S]*`), `"${lastItem}": "${value}"${hasComma ? ',' : ''}`)
            }

            break;
        }
    }

    Manifest = ManifestArr.join('\n')
}
// 使用
replaceManifest('app-plus.usingComponents', false)
replaceManifest('app-plus.splashscreen.alwaysShowBeforeRender', false)
replaceManifest('mp-baidu.usingComponents', false)
replaceManifest('h5.publicPath', process.env.VUE_APP_BASE_PATH)
replaceManifest('h5.router.base', process.env.VUE_APP_BASE_PATH)
fs.writeFileSync(manifestPath, Manifest, {
    "flag": "w"
})


module.exports = {
    publicPath: process.env.VUE_APP_BASE_PATH,
    transpileDependencies: ['uview-ui','uni-simple-router','wx-open-launch-weapp'],
    configureWebpack: {
      module: {
        rules: [{
          test: /\.vue$/,
          use: {
            loader: path.resolve(__dirname, "./node_modules/vue-inset-loader")
          },
        }]
      },
      plugins: [
        new webpack.DefinePlugin({
          ROUTES: webpack.DefinePlugin.runtimeValue(() => {
            const tfPages = new TransformPages({
              includes: ['path', 'name', 'meta', 'aliasPath']
            });
            return JSON.stringify(tfPages.routes)
          }, true )
        })
      ],
      resolve: {
        // 文件别名
        alias: {
          "@":resolve('src'),
          "store":resolve('src/store'),
          "common": resolve('src/common'),
          "router":resolve('src/router'),
          "styles":resolve('src/styles'),
          "mixins":resolve('src/mixins'),
          "static":resolve('src/static'),
        }
      }
    },
    chainWebpack: (config) => {
        // 发行或运行时启用了压缩时会生效
        config.optimization.minimizer('terser').tap((args) => {
            const compress = args[0].terserOptions.compress
            // 非 App 平台移除 console 代码(包含所有 console 方法，如 log,debug,info...)
            // compress.drop_console = true
            compress.pure_funcs = [
                '__f__', // App 平台 vue 移除日志代码
                // 'console.debug' // 可移除指定的 console 方法
            ]
            return args
        })
        config
            .plugin('define')
            .tap(args => {
                args[0]['process.env'].VUE_APP_TEST = '"test"'
                return args
            })
    }

}
