import axios from "axios";
import fs from 'fs';

const swagger = 'http://127.0.0.1:9087/api/v2/api-docs';
const outDir = './src/service/';
const requestStr = "import request from '@/utils/request';";
const commentTpl = (summary) => [
  '/*',
  ` * ${summary}`,
  ' */',
]

const apiTpl = (name, method, path) => {
  const apiName = `${method}${name}`;
  const hasPathParams = path.indexOf('{') > -1;

  const apiDetail = `const ${apiName}ById = (id) => request(\`${path.replace('{', '${')}\`);`;
  const apiList = `const ${apiName} = (params) => request('${path}', { params });`;
  const apiSave = `const ${apiName} = (data) => request('${path}', { data, method: 'post' });`;
  const apiUpdate = `const ${apiName} = (id, data) => request(\`${path.replace('{', '${')}\`, { data, method: 'put' });`;
  const apiDelete = `const ${apiName} = (id) => request(\`${path.replace('{', '${')}\`, { method: 'delete' });`;

  switch(method) {
    case 'get':
      return hasPathParams ? apiDetail : apiList;
    case 'post':
      return apiSave;
    case 'put':
      return apiUpdate;
    case 'delete':
      return apiDelete;
    default:
      return '';
  }
}

axios.get(swagger).then((res) => {
  const { paths, tags } = res.data;
  const files = Object.keys(paths).reduce((acc, path) => {
    const allAPI = paths[path];
    const apiName = getApiName(path);

    Object.keys(allAPI).forEach((method) => {
      const api = allAPI[method];
      const fname = getFileName(api, tags);

      const f = acc[fname] || [requestStr, ''];
      const content = [
        ...commentTpl(api.summary),
        `export ${apiTpl(apiName, method, path)}`,
        '',
      ]

      acc[fname] = f.concat(content)
    }, []);

    return acc;
  }, {});

  // 写入文件
  Object.keys(files).forEach(f => {
    const fname = `${outDir}${f}.js`
    const content = files[f].join('\n');
    fs.writeFile(fname, content, err => {
      console.error(err);
    });
  });

})

function getFileName(api, tags) {
  const tagName = api.tags[0];
  const tag = tags.filter(x => x.name == tagName)[0];
  const descriptions = tag.description.split(' ');

  const fname = descriptions.filter(x => x != 'Controller');

  // 转为小写
  return fname.join('').toLowerCase();
};

function getApiName(path) {
  const parts = path.split('/').reverse();
  const part = parts[0].indexOf('{') > -1 ? parts[1] : parts[0];

  // 首字母大写, - 转驼峰
  return part.replace(/^./, m => m.toUpperCase())
            .replace(/\-./, m => (m.length > 1 ? m[1].toUpperCase() : m));
}