/**
 * Author by zhangle, Email Olvier_web@163.com, Date on 2019/5/16.
 *  自动生成接口API
 */
const fs = require('fs')
const path = require('path')
const axios = require('axios')
let url = 'http://10.100.172.150:9108/v2/api-docs'
let filePath = path.join(__dirname, '../src')

function fetch () {
    return axios({
        url: url,
        method: 'get'
    }).then((res) => {
        return res
    }).catch((error) => {
        console.log(error.message)
        return Promise.reject(error)
    })
}

let getAPI = async () => {
    let res = await fetch()
    let resultAPI = {}
    let ObjectAPI = res.data.paths
    Object.keys(ObjectAPI).map((v, k) => {
        // v 当前请求URL
        let content = ObjectAPI[v]
        let url = v// 请求url
        let methods = Object.keys(content) // 获取请求方法 这里有可能是数组
        methods.map((item,index) => {
            let method = methods[index]
            let tags = content[method].tags// 获取tags
            let lastName = v.match(/{?\w+}?$/)[0].replace(/[{}]/g, '')
            // let methodName = `${lastName}Using${method.replace(/^(\w)/, ($1) => $1.toUpperCase())}`
            let methodName = `${lastName}-${method}`
            if (resultAPI[tags]) {
                Object.assign(resultAPI[tags], {
                    [methodName]: {
                        url,
                        method
                    }
                })
            } else {
                resultAPI[tags] = {
                    [methodName]: {
                        url,
                        method
                    }
                }
            }
        })
    })
    // let str = `export default ${JSON.stringify(resultAPI, null, '\t').replace(/"/g, '\'')}`
    let str = `/* eslint-disable */\r\n export default ${JSON.stringify(resultAPI, null, '\t')}`
    writeApiFile(str)
}
let writeApiFile = (resultAPI) => {
    try {
        let inputFileState = fs.existsSync(`${filePath}`)
        if (!inputFileState) {
            console.log('============================>>>>>>>>> 你已经入坑!')
        } else {
            let fileState = fs.existsSync(`${filePath}\\interface`)
            if (!fileState) fs.mkdirSync(`${filePath}\\interface`)
            fs.writeFileSync(`${filePath}\\interface\\apis.js`, resultAPI, {flag: 'w'})
            console.log('文件生成成功了')
        }
    } catch (error) {
        console.log('============================>>>>>>>>>' + error.message)
    }
}
getAPI()
