import React from 'react'
import { get } from 'lodash'

// 从对象获取 a.b.c 的路径值
const getObjPathVal = (obj, path) => {
  return get(obj, path)
}

// 判断是否叶子节点
const isLeaf = (data, prop) => {
  const { node } = prop
  const childrenList = getObjPathVal(data, node.children)
  return !(Array.isArray(childrenList) && childrenList.length)
}

// 创建 children 子节点
export const renderChildrenNode = (list, prop) => {
  if (Array.isArray(list) && list.length) {
    const { node } = prop
    const childrenNodeKey = list.map(item => getObjPathVal(item, node.id)).join('-')
    return (
      <div
        key={`${childrenNodeKey}--childrenNode`}
        className='org-tree-node-children'>
        { list.map(item => renderNode(item, prop))}
      </div>
    )
  }
  return null
}

// 创建 展开/折叠 按钮
export const renderExpandBtn = (data, prop) => {
  const { node, onExpand } = prop

  // 展开/折叠 按钮样式
  const cls = ['org-tree-node-btn']
  getObjPathVal(data, node.expand) && cls.push('expanded')

  return (
    <span
      key={`${getObjPathVal(data, node.id)}--expandBtn`}
      onClick={e => {
        e.stopPropagation()
        typeof onExpand === 'function' && onExpand(e, data)
      }}
      className={cls.join(' ')} />
  )
}

// 创建 content 节点，包括 展开/折叠 按钮
export const renderContentNode = (data, prop) => {
  const labelInnerClassname = 'org-tree-node-label-inner'

  const { node, collapsable, renderContent, onClick, labelClassName } = prop
  const childNodes = []

  // 添加自定义渲染的节点组件
  if (typeof renderContent === 'function') {
    const vnode = renderContent(data)
    vnode && childNodes.push(vnode)
  } else {
    childNodes.push(getObjPathVal(data, node.label))
  }

  // 非叶子节点渲染 展开/折叠 按钮
  if (collapsable && !isLeaf(data, prop)) {
    childNodes.push(renderExpandBtn(data, prop))
  }

  // content 节点样式
  const cls = [labelInnerClassname]
  labelClassName && cls.push(labelClassName)

  return (
    <div
      key={`${getObjPathVal(data, node.id)}--contentNode`}
      className='org-tree-node-label'
      onClick={e => {
        typeof onClick === 'function' && onClick(e, data)
      }}>
      <div className={cls.join(' ')}>
        {childNodes}
      </div>
    </div>
  )
}

// 创建 node 节点，包括content节点和children节点
export const renderNode = (data, prop) => {
  const { node, collapsable } = prop
  const collapsed = collapsable && !getObjPathVal(data, node.expand)

  // 创建根、子节点
  const childNodes = []
  childNodes.push(renderContentNode(data, prop))
  !collapsed && childNodes.push(renderChildrenNode(data.children, prop))

  // node 节点样式
  const cls = ['org-tree-node']
  if (isLeaf(data, prop)) {
    cls.push('is-leaf')
  } else if (collapsed) {
    cls.push('collapsed')
  }

  return (
    <div
      key={`${getObjPathVal(data, node.id)}--node`}
      className={cls.join(' ')}>
      { childNodes}
    </div>
  )
}

export const render = (props) => {
  return renderNode(props.data, props)
}

export default render
