import { Icon } from 'ant-design-vue'

export default {
  name: 'MenuTree',
  props: {
    dataSource: {
      type: Array,
      required: true
    },
    openKeys: {
      type: Array,
      default: () => []
    },
    search: {
      type: Boolean,
      default: false
    }
  },
  created () {
    this.localOpenKeys = this.openKeys.slice(0)
  },
  data () {
    return {
      localOpenKeys: [],
      selected: ''
    }
  },
  methods: {
    onSelect (selectedKeys, info) {
      this.selected = 'ant-menu-item-selected'
      console.log('selected', selectedKeys)
      this.$emit('click', selectedKeys)
    },
    renderIcon (icon) {
      return icon && (<Icon type={icon} />) || null
    },
    renderMenuItem (item) {
      return (
        <a-tree-node title={item.title} key={item.key} icon={this.renderIcon(item.icon)}/>
      )
    },
    renderItem (item) {
      return item.children ? this.renderSubItem(item, item.key) : this.renderMenuItem(item)
    },
    renderSubItem (item) {
      const childrenItems = item.children && item.children.map(o => {
        return this.renderItem(o, o.key)
      })
      return (
        <a-tree-node title={item.title} key={item.key} icon={this.renderIcon(item.icon)}>
          { childrenItems }
        </a-tree-node>
      )
    }
  },
  render () {
    const { dataSource } = this.$props

    // this.localOpenKeys = openKeys.slice(0)
    const list = dataSource.map(item => {
      return this.renderItem(item)
    })

    return (
      <div class="tree-wrapper">
        <a-tree showLine defaultExpandAll {...{ on: { select: (selectedKeys, info) => this.onSelect(selectedKeys, info) } }}>
          <a-tree-node key="">
            <span slot="title">根目录</span>
            {list}
          </a-tree-node>
        </a-tree>
      </div>
    )
  }
}
