const fs = require('fs')
// 定义要移动的平台和输出目录路径
const platform = 'android' // 平台名称，如android、ios等
// 构建后的apk文件路径
const apkPath = `./platforms/${platform}/app/build/outputs/apk/debug/app-debug.apk`
// 输出目录路径
const outputPath = './build'
// 修改package.json中的version
const packageJson = require('./package.json')

;(async () => {
  // 解析config.xml文件
  const configXml = await fs.readFileSync('./config.xml', 'utf-8')
  // 获取config.xml中widget节点的version属性
  const version = configXml.match(/<widget[\s\S]*?version="([\s\S]*?)"/)[1]
  // 修改package.json中的version
  packageJson.version = version

  await fs.writeFileSync('./package.json', JSON.stringify(packageJson, null, 2))

  // 复制package.json到输出目录
  await fs.copyFileSync('./package.json', `${outputPath}/package.json`)

  // 删除复制后的package.json中的scripts、devDependencies、dependencies、cordova字段
  const copyPackageJson = require(`${outputPath}/package.json`)
  delete copyPackageJson.scripts
  delete copyPackageJson.devDependencies
  delete copyPackageJson.dependencies
  delete copyPackageJson.cordova
  await fs.writeFileSync(`${outputPath}/package.json`, JSON.stringify(copyPackageJson, null, 2))

  // 移动文件并重命名
  fs.rename(apkPath, `${outputPath}/${packageJson.name}.apk`, () => {})
  console.info('编译成功！')
  // 输出编译后的文件
  console.info(`编译后的文件在${outputPath}目录下`)
})()
