const path = require('path')
const fs = require('fs')
const recursive = require('recursive-readdir')

const args = process.argv.slice(2)
// 要处理的目录
let dir = args[0]
if (dir === '$PWD') dir = args[1]
// const workspace = process.cwd()

// eslint-disable-next-line no-console
console.log('处理index.js')
const indexFile = path.join(dir, 'index.js')
let indexContent = fs.readFileSync(indexFile).toString()
indexContent = indexContent
  .replace(/\.child\('sd-/g, ".child('oa-")
  .replace(/ \*\/ '\.\/sd-/g, " */ './oa-")
fs.writeFileSync(indexFile, indexContent)

// eslint-disable-next-line no-console
console.log('处理vue文件')
recursive(
  dir,
  [
    (file, stats) => {
      return (
        stats.isFile() && (path.extname(file) !== '.vue' || !path.basename(file).startsWith('sd-'))
      )
    },
  ],
  function(_err, files) {
    files.forEach((file) => {
      renamePrefix(file)
    })
    require('../_auto-import/batch-process')
  }
)

function renamePrefix(file) {
  let content = fs.readFileSync(file).toString()
  content = content
    .replace('_import-components/sd-', '_import-components/oa-')
    .replace("name: 'Sd", "name: 'Oa")
  // console.log(file)
  fs.writeFileSync(file, content)
  fs.renameSync(file, file.replace(path.basename(file), path.basename(file).replace(/^sd-/, 'oa-')))
}
