const path = require('path')
const fs = require('fs')
const vueDocs = require('vue-docgen-api')
const kebabcase = require('lodash.kebabcase')

function saveTags(specs) {
  const tags = {}
  specs.forEach((spec) => {
    tags[spec.name] = {
      // ...spec,
      description:
        spec.description +
        (spec.tags && spec.tags.since ? '\n\r* ' + spec.tags.since[0].description + '新增' : '') +
        `\n\r[查看文档](http://xcoamobile.smartdot.com:18080/#${spec.name.replace(/-/g, '')})`,
      attributes: [
        ...spec.props.map((prop) => prop.name),
        ...(spec.events || []).map((event) => event.name),
        ...(spec.events || []).map((event) => '@' + event.name),
      ],
    }
  })
  writeFile('./src/common/components/_specs/tags.json', JSON.stringify(tags, null, '  '))
}

function saveProps(specs) {
  const props = {}
  specs.forEach((spec) => {
    spec.props.forEach((prop) => {
      props[spec.name + '/' + prop.name] = {
        description: `${prop.description}\n\r* 类型：${prop.type.name}${
          prop.defaultValue && !prop.defaultValue.func && prop.defaultValue.value !== 'undefined'
            ? '&emsp;默认值：' + prop.defaultValue.value
            : ''
        }${prop.required ? '&emsp;必填' : ''}${
          prop.tags && prop.tags.since ? '\n\r* ' + prop.tags.since[0].description + '新增' : ''
        }`,
      }
    })
    ;(spec.events || []).forEach((event) => {
      const data = {
        description: `${formatText(event.description)}${
          event.properties
            ? '\n\r参数\n\r' +
              event.properties
                .map((prop) => {
                  return (
                    '* ' +
                    prop.name +
                    '：' +
                    prop.type.names[0] +
                    ' - ' +
                    formatText(prop.description)
                  )
                })
                .join('\n\r')
            : ''
        }`,
      }
      props[spec.name + '/' + event.name] = {
        ...data,
        type: 'event',
      }
      props[spec.name + '/@' + event.name] = data
    })
  })

  writeFile('./src/common/components/_specs/attributes.json', JSON.stringify(props, null, '  '))
}

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 formatText(text) {
  // 去除html标签，替换换行符
  return (text || '').replace(/\n/g, '\n\r').replace(/<\/?[a-z1-9]+>/g, '')
}

// 获取所有组件文件的列表
const files = fs
  .readdirSync('./src/common/components')
  .filter((file) => file.endsWith('.vue'))
  .map((file) => path.join('./src/common/components', file))
files.push('./src/webflow/sd-webflow.vue')

Promise.all(
  files.map((file) => {
    return vueDocs.parse(file).then((spec) => {
      spec.name = path.basename(file, '.vue')
      return spec
    })
  })
).then((datas) => {
  const specs = datas.map((spec) => {
    return {
      ...spec,
      description: formatText(spec.description),
      props: spec.props
        ? spec.props
            .filter((prop) => !(prop.tags && prop.tags.ignore))
            .map((prop) => ({
              ...prop,
              name: kebabcase(prop.name),
              description: formatText(prop.description),
            }))
        : [],
    }
  })
  saveTags(specs)
  saveProps(specs)
})
