const fs = require('fs')
const path = require('path')
const axios = require('axios')
const token =
  'eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxIiwic3ViIjoiYWRtaW4iLCJpc3MiOiJwY2FwaSIsImlhdCI6MTY5MjIzNDQxNiwidXNlcm5hbWUiOiJhZG1pbiIsImV4cCI6MTY5MjMwNjQxNn0.R45O1KaWqZHbL_XYy4a6eKP4EvtMHOQAAnmgOBRmqVQ'

// 解析获取函数
const teshu = {
  hashStr(code) {
    code = code.replace(/(\/\*[\s\S]*?\*\/)|((?<!:)\/\/.*)/g, '')
    code = code.replace(/import.*;/g, '')
    code = code.replace(/pragma.*;/g, '')
    return code.trim()
  },
  getFunctions(text) {
    text = this.hashStr(text)
    const reg =
      /(^|\s)((function|event)\s|constructor\s*\(.*\))[^{};]*({(?:[^}{]+|{(?:[^}{]+|{(?:[^}{]+|{(?:[^}{]+|{(?:[^}{]+|{(?:[^}{]+|{(?:[^}{]+|{(?:[^}{]+|{[^}{]*})*})*})*})*})*})*})*})*}|;)/g
    const res = text.match(reg) || []
    for (const i in res) res[i] = this.hashStr(res[i].trim(), false)
    return res
  }
}

// 递归目录文件
function fileDisplay(filePath, course) {
  //根据文件路径读取文件，返回文件列表
  var files = fs.readdirSync(filePath)
  //遍历读取到的文件列表
  files.forEach(function (filename) {
    //获取当前文件的绝对路径
    var filedir = path.join(filePath, filename)
    //根据文件路径获取文件信息，返回一个fs.Stats对象
    var stats = fs.statSync(filedir)
    var isFile = stats.isFile() //是文件
    var isDir = stats.isDirectory() //是文件夹
    if (isFile) {
      try {
        const data = fs.readFileSync(filedir, 'utf8')
        course && course(filedir, data)
      } catch (err) {
        console.error(err)
      }
    }
    if (isDir) {
      fileDisplay(filedir, course) //递归，如果是文件夹，就继续遍历该文件夹下面的文件
    }
  })
}

// 获取函数对应接口
var obj = {}
fileDisplay('./api', function (filedir, data) {
  var objname = filedir.replace(/\\/g, '/')
  obj[objname] = {}
  teshu.getFunctions(data).map(item => {
    const reg = /(?<=function)([^(]*)(?=\()/g
    const res = item.match(reg) || []
    const reg2 = /(?<=url.*:.*["|'|`])([^"|'|\?|`]*)/g
    var reg3 = /\s+/g
    var functionName = (item.match(res)?.[0] || '').replace(reg3, '')
    var url = (item.match(reg2)?.[0] || '').replace(reg3, '')
    if (!url) {
      const reg4 = /(?<=handleImport.*\(.*["|'|`])([^"|'|\?|`]*)/g
      url = (item.match(reg4)?.[0] || '').replace(reg3, '')
    }
    obj[objname][functionName] = url
  })
})

// 获取页面文件和组件中使用的接口函数
var objfnm = {}
fileDisplay('./views', function (filedir, data) {
  // var data_ = data.replace(/[ ]|[\r\n]/g, '')
  var objname = filedir.replace(/\\/g, '/')
  const reg = /import\s*\{?\s*([a-zA-Z0-9_,\s]+)\s*\}?\s*from\s*['"]@\/api\/[a-zA-Z0-9_\-/]+\s*[\.'"]/g
  const res = data.match(reg) || []
  var regex3 = /(?<=\{)(.+?)(?=\})/g
  res.map(function (item) {
    if (!objfnm[objname]) {
      objfnm[objname] = {}
    }
    var apiadd = item.match(/(@\/api\/[a-zA-Z0-9_\-/]+)/)[0]
    var funlist = item
      .replace(/[ ]|[\r\n]/g, '')
      .match(regex3)[0]
      .split(',')
    objfnm[objname][apiadd.replace('@/', '') + '.js'] = funlist
  })
})

// 数组去重
function removeDuplicate(arr) {
  let len = arr.length
  for (let i = 0; i < len; i++) {
    for (let j = i + 1; j < len; j++) {
      if (arr[i] === arr[j]) {
        arr.splice(j, 1)
        len--
        j--
      }
    }
  }
  return arr
}

// 获取远程菜单目录
function getmenu(list, cb) {
  for (var item of list) {
    if (item.type === 2) {
      cb && cb(item)
    } else if (item.children && item.children.length) {
      getmenu(item.children, cb)
    }
  }
}
const service = axios.create({
  timeout: 300000
})
service.interceptors.request.use(
  config => {
    config.headers['x-token'] = token
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)
service
  .get('https://jiasm.zfire.top/pcapi/admin/user/module/list?adminUserId=1')
  .then(res => {
    const { data } = res.data
    var listmenu = []
    getmenu(data, function (item) {
      listmenu.push(item)
    })
    var menuobj = {}
    listmenu.map(item => {
      menuobj[item.fullUrl] = {}
    })
    Object.keys(menuobj).map(function (key1) {
      Object.keys(objfnm).map(function (key2) {
        if (key2.indexOf('views' + key1) == 0) {
          Object.keys(objfnm[key2]).map(function (key3) {
            if (!menuobj[key1][key3]) {
              menuobj[key1][key3] = []
            }
            menuobj[key1][key3] = removeDuplicate([...menuobj[key1][key3], ...objfnm[key2][key3]])
          })
        }
      })
    })

    var listss = []
    Object.keys(menuobj).map(function (key1) {
      Object.keys(menuobj[key1]).map(function (key2) {
        var obj_ = {}
        menuobj[key1][key2].map(function (funName) {
          obj_[funName] = obj[key2][funName]
          listss.push(obj[key2][funName])
        })
        menuobj[key1][key2] = obj_
      })
    })

    listss = removeDuplicate(listss)
    console.log('页面中使用到的接口去重：', listss, listss.length)
    // console.log('页面中使用到的接口对应关系：', menuobj)

    // 导出页面中使用到的接口对应关系
    let str = JSON.stringify(menuobj)
    fs.writeFile('./data.json', str, function (err) {
      if (err) {
        res.status(500).send('Server is error...')
      }
    })
  })
  .catch(err => {
    console.log('Error: ', err.message)
  })
