const { notEmpty } = require('./utils.js')
const fs = require('fs')
const path = require('path')

function getFolder(path) {
  let components = []
  const files = fs.readdirSync(path)
  files.forEach(function (item) {
    let stat = fs.lstatSync(path + '/' + item)
    if (stat.isDirectory() === true && item != 'components') {
      components.push(path + '/' + item)
      components.push.apply(components, getFolder(path + '/' + item))
    }
  })
  return components
}

module.exports = {
  description: '创建前端模块',
  prompts: [
    {
      type: 'list',
      name: 'path',
      message: '请选择页面创建目录',
      choices: getFolder('src/views'),
    },
    {
      type: 'input',
      name: 'name',
      message: '请输入view名称',
      validate: notEmpty('name'),
    },
    {
      type: 'input',
      name: 'table',
      message: '请输入Table名称',
      validate: notEmpty('table'),
    },
  ],
  actions: (data) => {
    let moduleName = path.relative('src/views', data.path)
    const pathCaseName = '{{ pathCase name }}'
    const properCaseName = '{{ properCase name }}'
    const camelCaseName = '{{ camelCase name }}'
    return [
      {
        type: 'queryTableColumns',
        speed: 'slow',
      },
      {
        type: 'add',
        path: `src/views/${moduleName}/${pathCaseName}/index.vue`,
        templateFile: './template/index.hbs',
        force: true,
        data: {
          moduleName: moduleName,
        },
      },
      {
        type: 'add',
        path: `src/views/${moduleName}/${pathCaseName}/components/${properCaseName}Edit.vue`,
        templateFile: './template/edit.hbs',
        force: true,
        data: {
          moduleName: moduleName,
        },
      },
      {
        type: 'add',
        path: `src/api/${moduleName}/${camelCaseName}.js`,
        templateFile: './template/api.hbs',
        force: true,
        data: {
          moduleName: moduleName,
        },
      },
    ]
  },
}
