const fs = require('fs')
const path = require('path')

function writeFile(jsFile, jsContent) {
  // 生成最终的js文件
  fs.writeFile(jsFile, jsContent, (error) => {
    if (error) {
      // eslint-disable-next-line no-console
      console.error('Error while creating ' + jsFile)
      throw error
    }
  })
}

function getPrefix(chunkName) {
  const paths = chunkName.split('-')
  switch (paths[0]) {
    case 'src':
      return 'sd'
    case 'product':
      return paths[1]
    case 'custom':
      return 'xm'
  }
}

function replaceRoute(file, workspace) {
  const relativePath = path.relative(workspace, path.dirname(file))
  // 生成块名称
  const chunkName = relativePath.replace('src_', '').replace(/(\\|\/)/g, '-')
  const prefix = getPrefix(chunkName)
  const content = fs.readFileSync(file).toString()

  // 检查路由的命名与所在的目录是否匹配
  const errors = []
  if (prefix) {
    var regexpRouteNames = /\.(?:route|child|routeInFrame)\('\/?([a-z-]*?)', {/g
    var routeNames = regexpRouteNames.exec(content)

    while (routeNames != null) {
      const routeNamePrefix = routeNames[1].split('-')[0]
      if (routeNamePrefix && routeNamePrefix !== prefix) {
        errors.push(`console.warn('路由 ${routeNames[1]} 不符合命名规则，应该以 ${prefix} 开头')`)
      }
      routeNames = regexpRouteNames.exec(content)
    }
  }

  // 替换：component: './xm-tabbed-table-example.vue',
  let result = content.replace(/component: '(.*?)',/g, (_, path) => {
    return `component:asyncComponent(
    () => import(/* webpackChunkName: "${chunkName}" */ '${path}')
  ),`
  })

  // 替换：flowService.addFlowForm('pageId','./xm-tabbed-table-example.vue')
  result = result.replace(
    /flowService\.addFlowForm\([\s]*?'(.*?)',[\s]*?'(.*?)'[\s]*?\)/g,
    (_, name, path) => {
      return `flowService.addFlowForm(
  '${name}',
  asyncComponent(
    () => import(/* webpackChunkName: "${chunkName}-form" */ '${path}')
  )
)`
    }
  )

  // 替换：formService.addForm('pageId','./xm-tabbed-table-example.vue')
  result = result.replace(
    /formService\.addForm\([\s]*?'(.*?)',[\s]*?'(.*?)'[\s]*?\)/g,
    (_, name, path) => {
      return `formService.addForm(
  '${name}',
  asyncComponent(
    () => import(/* webpackChunkName: "${chunkName}-form" */ '${path}')
  )
)`
    }
  )

  let header = `// 自动生成的文件，请勿修改
`
  if (result.includes('asyncComponent(') && !content.includes('import asyncComponent from')) {
    header += `import asyncComponent from '@/common/services/async-component'
`
  }

  writeFile(
    file.replace('index.js', 'index-normalize-route.js'),
    header + result + errors.join('\n')
  )
}
module.exports = replaceRoute
