/**
 *@author       孙冬冬
 *@date         2020/1/16 11:04
 *@Copyright    天源迪科信息技术股份有限公司
 *@Description
 */
const fs = require('fs')
const chalk = require('chalk')
const path = require('path')
const fileSave = require('file-save')
const execa = require('execa')
const render = require('json-templater/string')
// 转换为小写驼峰
const camelCase = require('camelcase')
// 转换为短横线
const kebabCase = require('kebab-case')
// 转换为大写驼峰
const uppercamelcase = require('uppercamelcase')
// 引入样式
const getIndexWxss = require('./theme').getIndexWxss
// 集成路由
const createRouteToApp = require('./createRoute').createRouteToApp


// 判断参数
if (!process.argv[2]) {
  console.log(chalk.red('[组件名]第一个参数必填 '))
  process.exit(1)
}
// 获取组件名称
const folderName = `${process.argv[2]}`
const componentshortname = kebabCase(folderName)
  .replace('-', '')
const htName = 'ht-' + componentshortname
const demoName = htName + '-demo'
const ComponentShortName = uppercamelcase(folderName)
const componentPath = path.resolve(__dirname, '../src/components', htName)
const demoPath = path.resolve(__dirname, '../tools/demo/pages', demoName)

// 读取组件api和events
let jsonFile = fs.readFileSync(path.resolve(__dirname, './json/vantData.json'), 'utf8')
jsonFile = JSON.parse(jsonFile)
const compon = jsonFile[folderName]
if (!compon) {
  console.log(chalk.red(`没有找到${folderName}组件，请检查组件名称！`))
  process.exit(1)
}
// 获取props数组
let props = []
if (compon.props) {
  props = Object.keys(compon.props)
}
// 获取events数组
let values = []
if (compon.events) {
  values = Object.keys(compon.events)
}
// 获取externalClasses数组
let externalClasses = compon.externalClasses || []

// 获取index.wxml中的props
externalClasses = externalClasses.map(function (item) {
  return camelCase(item)
})
props = props.concat(externalClasses)
let wxmlProps = props.map(function (item) {
  return `${item} = "{{${item}}}"`
})
const wxmlMethods = values.map(function (item) {
  if (!item.includes('bind:')) {
    item = 'bind:' + item
  }
  return `${item} = "handle${uppercamelcase(item.replace('bind:', ''))}"`
})
wxmlProps = wxmlProps.concat(wxmlMethods)
  .join('\n    ') // 加四个空格方便格式化
// 获取index.js中的props
const externalClassesObject = {}
externalClasses.forEach(function (item) {
  externalClassesObject[item] = {type: 'String'}
})

const comProps = JSON.stringify({...compon.props, ...externalClassesObject}, null, 4)
const jsProps = comProps
  .substr(1, comProps.length - 2)
  .replace(/\"/g, '')

// 获取index.js中的events
let jsMethods = []
for (let i = 0; i < values.length; i++) {
  const name = values[i].replace('bind:', '')
  jsMethods[i] = `handle${uppercamelcase(name)}({detail}) {
      this.triggerEvent('${name}', detail)
  },`
}
jsMethods = jsMethods.join('\n  ') // 加四个空格方便格式化
// 定义组件模板文件常量
const jsonTpl = fs.readFileSync(path.resolve(__dirname, './tpl/component.json.tpl'), 'utf8')
const wxssTpl = fs.readFileSync(path.resolve(__dirname, './tpl/component.wxss.tpl'), 'utf8')
const jsTpl = fs.readFileSync(path.resolve(__dirname, './tpl/component.js.tpl'), 'utf8')
const wxmlTpl = fs.readFileSync(path.resolve(__dirname, './tpl/component.wxml.tpl'), 'utf8')
const files = [
  {
    filename: 'index.json',
    content: render(jsonTpl, {
      componentName: componentshortname,
      htName,
    }),
  },
  {
    filename: 'index.wxss',
    content: render(wxssTpl, {
      htName,
    }),
  },
  {
    filename: 'index.js',
    content: render(jsTpl, {
      props: jsProps,
      methods: jsMethods,
    }),
  },
  {
    filename: 'index.wxml',
    content: render(wxmlTpl, {
      props: wxmlProps,
      htName,
    }),
  },
]

// 生成组件
files.forEach(file => {
  const filePath = path.join(componentPath, file.filename)
  fileSave(filePath)
    .write(file.content, 'utf8')
    .end('\n')
  console.log(chalk.green(`创建文件:${filePath}`))
})
// 定义demo模板文件常量
const demoJsonTpl = fs.readFileSync(path.resolve(__dirname, './tpl/demo.json.tpl'), 'utf8')
const demoWxssTpl = fs.readFileSync(path.resolve(__dirname, './tpl/demo.wxss.tpl'), 'utf8')
const demoJsTpl = fs.readFileSync(path.resolve(__dirname, './tpl/demo.js.tpl'), 'utf8')
const demoWxmlTpl = fs.readFileSync(path.resolve(__dirname, './tpl/demo.wxml.tpl'), 'utf8')

const demoFiles = [
  {
    filename: 'index.json',
    content: render(demoJsonTpl, {
      htName,
    }),
  },
  {
    filename: 'index.wxss',
    content: render(demoWxssTpl, {
      demoName,
    }),
  },
  {
    filename: 'index.js',
    content: render(demoJsTpl, {}),
  },
  {
    filename: 'index.wxml',
    content: render(demoWxmlTpl, {
      demoName,
      htName,
    }),
  },
]

// 生成组件demo
demoFiles.forEach(file => {
  const filePath = path.join(demoPath, file.filename)
  fileSave(filePath)
    .write(file.content, 'utf8')
    .end('\n')
  console.log(chalk.green(`创建demo文件:${filePath}`))
})
// 生成default/index.wxss
getIndexWxss()
// 将新建组件的路由集成到app.json
createRouteToApp()
