const fs = require('fs')
const path = require('path')
const xml2js = require('xml2js')

const parser = new xml2js.Parser()
// 读取svg并处理每个symbol
fs.readFile(path.join(__dirname, '/source.svg'), function(_err, data) {
  parser.parseString(data, function(_err, result) {
    result.svg.symbol.forEach(saveIcon)
  })
})

function saveIcon(symbol) {
  let name = symbol.$.id
  // path中写了fill的是双色图标
  let theme = 'outline'
  if (name.endsWith('-twotone')) {
    theme = 'twotone'
    name = name.replace('-twotone', '')
  } else if (name.endsWith('-filled')) {
    theme = 'fill'
    name = name.replace('-filled', '')
  }
  // 单色图标的模板
  const template = `export default{
  name: 'sd-${name}',
  theme: '${theme}',
  icon: {
    tag: 'svg',
    attrs: { viewBox: '${symbol.$.viewBox}', focusable: false },
    children: [
      ${symbol.path.map(processPath).join(',')}
    ]
  }
}`
  // 双色图标的模板
  const templateTwoTone = `export default{
  name: 'sd-${name}',
  theme: '${theme}',
  icon: function (primaryColor, secondaryColor) {
    return {
      tag: 'svg',
      attrs: { viewBox: '${symbol.$.viewBox}', focusable: false },
      children: [
        ${symbol.path.map(processPathTwoTone).join(',')}
      ]
    }
  }
}`
  // 将每个图标写入文件
  fs.writeFile(
    path.join(__dirname, 'icons', theme, `${name}.js`),
    theme === 'twotone' ? templateTwoTone : template,
    (error) => {
      if (error) {
        // eslint-disable-next-line no-console
        console.error(`Error while creating ${name}.js`)
        throw error
      }
    }
  )
}
function processPath(path) {
  return `{
        tag: 'path',
        attrs: {
          d: '${path.$.d}'
        }
      }`
}
// 处理双色图标的path，颜色1890FF为可变部分
function processPathTwoTone(path) {
  return `{
        tag: 'path',
        attrs: {
          fill: ${path.$.fill !== '#1890FF' ? "'currentColor'" : 'primaryColor'},
          d: '${path.$.d}'
        }
      }`
}
