// 修改所有后台接口路径为ui开头
// 这个方法非常不靠谱，会把路由中的替换，慎用

const argv = require('yargs').argv._
const fs = require('fs')
const path = require('path')


let fileDir = argv[0] || '../src/' || '../src/views/comment'

if (fileDir.charAt(1) !== ':') {
  fileDir = path.join(__dirname, fileDir)
}
const needReplace = JSON.parse(fs.readFileSync(path.join(__dirname, '125411.json'), 'utf-8'))

let fileRegx = /^.(js|vue)$/

traveller(fileDir)


function traveller(fileDir) {
  if (fs.existsSync(fileDir)) {
    let files = fs.readdirSync(fileDir)
    files.forEach(fileName => {
      let filePath = path.join(fileDir, fileName)
      let file = fs.statSync(filePath)
      let ext = path.extname(fileName)
      if (file.isDirectory()) {
        traveller(filePath)
      } else if (ext.match(fileRegx)) {
        let fileContent = fs.readFileSync(filePath, 'utf-8')
        let jsContent = fileContent
        if (ext === '.vue') {
          fileContent = fileContent.split(/<\/?script[^>]*>/)
          jsContent = (fileContent[1]||'')
        }
        if(jsContent.trim().length){
          let hasReplaced = false
          for(var oldPath in needReplace){
            if(jsContent.includes(oldPath) || jsContent.includes(oldPath.slice(1)) ){
              hasReplaced = true
              jsContent=jsContent.replace(new RegExp('([\'"`])\/'+oldPath.slice(1),'g'), '$1'+needReplace[oldPath])
            }
          }
          if(hasReplaced){
            console.log('=> ',filePath)
            let transFileContent = jsContent
            if(ext === '.vue'){
              transFileContent = fileContent[0]+'<script>'+jsContent+'</script>'+fileContent[2]
            }
            // console.log(transFileContent)
            fs.writeFileSync(filePath, transFileContent);
          }
        }
      }
    })

  }
}
