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

// yapi的cookie，过期了需要替换
let Cookie = 'experimentation_subject_id=IjczYmVhOGNhLWFjOWUtNDIwNS1hNGJhLWMyMzQ2Y2YwMDU1NyI%3D--d82f806b863b427a00fadf4108b2bea5ff00dfcd; _yapi_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjQ2LCJpYXQiOjE2NDk5MTU4MDksImV4cCI6MTY1MDUyMDYwOX0.EYlOgqtOoiiB3zJJNIUBG8Q_8f2GQ_YVyaJqfVm58A4; _yapi_uid=46'
/**
 * 接口请求方法
 * @param params 请求入参
 */
 function useRequest(params = {}) {
  return new Promise((resolve, reject) => {
    request({
      method: 'get',
      json: true,
      ...params,
      headers: {
        "content-type": "application/json",
        ...(params.headers || {})
      }
    }, function(error, response, body) {
      // 如果当前接口请求错误
      if (error) {
        reject(error)
        return
      }
      // 如果当前返回码错误
      if (response.statusCode != 200) {
        reject(response)
        return
      }
      resolve(body)
    })
  })
}

/**
 * 从yapi上拉取生成yapi文件
 */
async function updateApiConfig() {
  // 如果cookie不存在
  if (!Cookie) {
    // 询问用户输入
    const answer = await inquirer.prompt([
      {
        type: 'input',
        name: 'cookie',
        message: '请输入yapi网站的cookie：',
        validate(answer) {
          return !!answer ? true : 'cookie是必填项'
        }
      }
    ])
    // 赋值给全局的cookie
    Cookie = answer.cookie
  }
  // 获取接口返回报文
  const { errcode, data } = await useRequest({
    url: 'http://yapi.cusc.com:3000/api/project/list?group_id=92&page=1&limit=50',
    headers: { Cookie }
  })

  // 询问用户输入
  const { project } = await inquirer.prompt([
    {
      type: 'list',
      name: 'project',
      message: '请选择项目：',
      choices: data.list
    }
  ])
  // 获取当前选择的项目
  const projectInstance = data.list.find(item => item.name === project)
  // 获取接口返回报文
  const categoryResp = await useRequest({
    url: `http://yapi.cusc.com:3000/api/interface/list_menu?project_id=${projectInstance['_id']}`,
    headers: { Cookie }
  })
  // 询问需要生成哪个分类的api文档
  const categoryAnswer = await inquirer.prompt([
    {
      type: 'list',
      name: 'category',
      message: '请选择分类',
      choices: categoryResp.data
    }
  ])
  // 获取接口列表
  const interfaceList = categoryResp.data.find(category => category.name === categoryAnswer.category).list
  // 如果定义了接口
  if (interfaceList && interfaceList.length > 0) {
    // 文件名称
    let fileName = ''
    // 生成api
    const api = interfaceList.map(i => {
      // 路径
      const path = i.path.slice(1).split('/')
      //记录文件名
      fileName = path[0]
      return `/**\n * ${i.title}\n * @yapi http://yapi.cusc.com:3000/project/${projectInstance['_id']}/interface/api/${i['_id']}\n */\nexport function ${'fetch' + path.map(i => (i.slice(0, 1).toUpperCase() + i.slice(1))).join('')}(data) {\n  return request({\n    url: API_PREFIX + '${i.path.slice(1)}',\n    method: '${i.method}',\n    data\n  })\n}\n`
    }).join('\n')
    // 文件路径
    const API_PATH = path.join(__dirname, '../', 'src', 'api', `${fileName}.js`)
    // 判断文件是否存在
    try {
      fs.accessSync(fs.readFileSync(API_PATH), fs.constants.F_OK)
      // 开始写文件
      fs.writeFileSync(
        fs.readFileSync(API_PATH),
        `import request from '@/utils/request'\n\nconst API_PREFIX = process.env.VUE_APP_BASIC_DATA_API\n\n${api}`
      )
    } catch (error) {
      fs.writeFileSync(API_PATH, `import request from '@/utils/request'\n\nconst API_PREFIX = process.env.VUE_APP_BASIC_DATA_API\n\n${api}`)
    }
  }
}

updateApiConfig()