import { useState, useEffect, useCallback } from 'react'
import { Modal, Tree, App, Button, Flex } from 'antd'
import { getTagList, bindTag } from '../api'

function getIds(nodes) {
  let ids = []
  nodes.forEach(node => {
    ids.push(node.id)
    if (node.children && node.children.length > 0) {
      ids = ids.concat(getIds(node.children))
    }
  })

  return ids
}

const BindKnowledgeGraph = ({ chapter = {}, ...props }) => {
  const { message } = App.useApp()

  const [treeData, setTreeData] = useState([])
  const [expandedKeys, setExpandedKeys] = useState([])

  const fetchList = useCallback(() => {
    getTagList({ type: 2, parent_id: chapter.book_id, chapter_id: chapter.id }).then(res => {
      setTreeData(res.data)
      setExpandedKeys(getIds(res.data))
    })
  }, [chapter])

  useEffect(() => {
    fetchList()
  }, [fetchList])

  const toggleBind = async node => {
    await bindTag({
      tag_id: node.id,
      book_id: chapter.book_id,
      chapter_id: chapter.id,
      option_type: node.is_checked ? 'delete' : 'add'
    })
    message.success('操作成功')
    fetchList()
  }

  const titleRender = node => {
    return (
      <Flex justify="space-between">
        <span>{node.name}</span>
        <Button color="primary" variant="link" size="small" onClick={() => toggleBind(node)}>
          {node.is_checked ? '取消关联' : '关联'}
        </Button>
      </Flex>
    )
  }
  return (
    <Modal title="关联知识图谱" centered {...props} footer={null}>
      <Tree
        blockNode
        selectable={false}
        treeData={treeData}
        fieldNames={{ title: 'name', key: 'id' }}
        expandedKeys={expandedKeys}
        titleRender={titleRender}
        onExpand={setExpandedKeys}
      />
      {/* <TreeSelect
        multiple
        showSearch
        treeDefaultExpandAll
        value={value}
        treeData={treeData}
        fieldNames={{ label: 'name', value: 'id' }}
        onChange={setValue}
        style={{ width: '100%' }}></TreeSelect> */}
    </Modal>
  )
}

export default BindKnowledgeGraph
