import { useState, useEffect, useRef } from 'react'
import { Button, Row, Col, Descriptions, Tree, Dropdown, Modal, Spin, App } from 'antd'
import { EllipsisOutlined, DiffOutlined, MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons'
import WangEditorCustomer from '@/common/wangeditor-customer'
import { useLocation, useNavigate } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { setAutosaveTime } from '@/store/modules/editor'
import { setTreeChapter } from '@/store/modules/user'
import EditChapterTitle from './components/form-chapter-title'
import EditChapterEditors from './components/EditChapterEditors'
import { get } from 'lodash-es'
import md5 from 'js-md5'

import { convertToAntdTreeData, findTreeElementByKey, findFirstNotHasChildren, findParentLevelOne, findTreeToIndex, findNodeById } from '@/utils/common'
import { getAllList, getInfoByChapterId, sectionEdit, chapterDel, dragOrder } from './request'
import './index.less'

const Examine = () => {
  const { modal } = App.useApp()

  const location = useLocation()
  const id = get(location, 'state.id', '')
  const isAdminOrCreator = get(location, 'state.isAdminOrCreator', false)

  const { treeChapter, userInfo } = useSelector(state => state.user)
  const navigate = useNavigate()
  const dispatch = useDispatch()

  const [gData, setGData] = useState([])
  const [chapterId, setChapterId] = useState(0)
  const [bookId, setBookId] = useState(0)

  // 树节点设置
  const [expandedKeys, setExpandedKeys] = useState([])
  const [checkedKeys, setCheckedKeys] = useState([])
  const [nowTitle, setNowTitle] = useState('')
  // 编辑操作
  const [isCollapse, setisCollapse] = useState(false)
  const [editKey, setEditKey] = useState(null)
  const [parentId, setParentId] = useState(null)
  const [editValue, setEditValue] = useState('')
  const [loading, setLoading] = useState(false)
  const [contentMd5, setContentMd5] = useState('')

  // 设置编者
  const [currentChapter, setCurrentChapter] = useState(null)
  const [editChapterEditorsIsOpen, setEditChapterEditorsIsOpen] = useState(false)
  const onChapterEditorsChange = () => {
    setEditChapterEditorsIsOpen(false)
  }
  // 编辑器内容
  const editorRef = useRef()
  const saveInterRef = useRef()
  const [html, setHtml] = useState('')
  const [contentId, setContentId] = useState(false)

  // 获取目录结构
  const getChapterTreeList = async () => {
    setLoading(true)
    const { data = [], code } = await getAllList({ book_id: id })
    if (code !== 200) {
      setLoading(false)
      navigate('/books/management/list', { replace: true })
      return
    }

    if (data.length === 0) {
      setLoading(false)
      return
    }

    const uniqueBookList = [...new Set(data.map(item => item.book_id))][0]
    setBookId(uniqueBookList)
    const arr = convertToAntdTreeData(data, 'name')
    setGData(arr)
    const allKeys = getAllNodeKeys(arr)
    setExpandedKeys(allKeys)

    const first = findFirstNotHasChildren(arr)
    setNowTitle(first.title)

    if (treeChapter && Object.entries(treeChapter).length > 0) {
      if (parseInt(treeChapter.saveBookId) === parseInt(id)) {
        const childInKey = findTreeElementByKey(arr, 'key', treeChapter.saveChapterId)
        if (childInKey) {
          setChapterId(childInKey.key)
          setCheckedKeys([childInKey.key])
          setNowTitle(childInKey.title)
        } else {
          setChapterId(first.key)
          setCheckedKeys([first.key])
          setNowTitle(first.title)
        }
      } else {
        setChapterId(first.key)
        setCheckedKeys([first.key])
        setNowTitle(first.title)
        await dispatch(setTreeChapter({ saveBookId: id, saveChapterId: first.key }))
      }
    } else {
      setChapterId(first.key)
      setCheckedKeys([first.key])
      setNowTitle(first.title)
    }
    setLoading(false)
  }

  const newChapterChange = (id, title) => {
    setChapterId(parseInt(id))
    setCheckedKeys([parseInt(id)])
    setNowTitle(title)
  }
  // 递归函数，获取所有节点的key
  const getAllNodeKeys = nodes => {
    let keys = []
    nodes.forEach(node => {
      keys.push(node.key)
      if (node.children && node.children.length > 0) {
        keys = keys.concat(getAllNodeKeys(node.children))
      }
    })
    return keys
  }
  const [disabled, setDisabled] = useState(false)
  // 获取内容
  const getChapterVal = async () => {
    setLoading(true)
    const data = await getInfoByChapterId({ chapter_id: chapterId })
    setDisabled(!data.selected_editor_ids.includes(userInfo.id) && !isAdminOrCreator)
    dispatch(setTreeChapter({ saveBookId: id, saveChapterId: chapterId }))

    const { content, id: cId } = data
    if (content) {
      setContentMd5(md5(content))
    }
    setHtml(content)
    setContentId(cId)
    if (editorRef.current && editorRef.current.editor) {
      editorRef.current.editor.setHtml(content)
    }
    setLoading(false)
  }

  const onExpand = expandedKeys => {
    setExpandedKeys(expandedKeys)
  }
  const handleSelect = async (checkedKeys, info) => {
    const { key } = info.node
    const childInKey = findTreeElementByKey(gData, 'key', key)

    if (childInKey.children && childInKey.children.length > 0) {
      clearInterval(saveInterRef.current)
      // 进行展开操作
      const tempExpandeds = JSON.parse(JSON.stringify(expandedKeys))
      let newExpand = ''
      if (expandedKeys.includes(key)) {
        newExpand = tempExpandeds.filter(item => parseInt(item) !== parseInt(key))
      } else {
        newExpand = [...tempExpandeds, key]
      }
      setExpandedKeys(newExpand)
      setCheckedKeys([key])
      return
    } else {
      const { key, title } = info.node
      if (info.selected === false) {
        setLoading(true)
        setChapterId(key)
        setCheckedKeys([key])
        setNowTitle(title)
        setLoading(false)
      } else {
        setLoading(true)
        clearInterval(saveInterRef.current)
        await saveContent()

        if (key !== chapterId) {
          editorRef.current.editor.clear()
        }
        setLoading(true)
        setChapterId(checkedKeys[0])
        setCheckedKeys([checkedKeys[0]])
        setNowTitle(info.node.title)
        setLoading(false)
      }
    }
  }

  useEffect(() => {
    getChapterTreeList()
  }, [])
  useEffect(() => {
    if (chapterId) {
      setCheckedKeys([chapterId])
      getChapterVal()
    }
  }, [chapterId])

  // 保存方法
  const saveContent = async () => {
    if ((contentId, editorRef.current, editorRef.current.editor, !loading)) {
      const contentHtml = editorRef.current.editor.getHtml()
      const newMd5 = md5(contentHtml)
      clearInterval(saveInterRef.current)
      const word_count = editorRef.current.editor.getText().length
      // 保存
      const data = await sectionEdit({
        id: contentId,
        content: contentHtml,
        word_count
      })
      if (data) {
        if ((data.code && data.code === 3000) || data.code === '3000') {
          navigate('/books/management/list')
          return
        } else {
          setContentMd5(newMd5)
          dispatch(setAutosaveTime(Date.now()))
        }
      }
    }
  }

  useEffect(() => {
    if (!loading && contentId) {
      clearInterval(saveInterRef.current)
    } else {
      clearInterval(saveInterRef.current)
    }
  }, [contentId, loading, contentMd5, html])

  const addChapterParent = () => {
    setEditKey(-1)
    setEditValue('')
    setParentId(-1)
  }

  const delChapter = async node => {
    const childInKey = findParentLevelOne(gData, 'key', node.key)
    let current = null
    if (childInKey && childInKey.children && childInKey.children.length > 0) {
      const index = findTreeToIndex(childInKey.children, 'key', node.key)

      if (childInKey.children.length === 1) {
        current = childInKey
      } else {
        // 前面还有
        if (index <= childInKey.children.length) {
          if (index === 0) {
            current = childInKey.children[index + 1]
          } else {
            current = childInKey.children[index - 1]
          }
        }
      }
    } else {
      const index = findTreeToIndex(gData, 'key', node.key)
      let child = null
      if (index === 0) {
        child = gData[index + 1]
      } else {
        child = gData[index - 1]
      }
      if (child && child.children && child.children.length > 0) {
        current = child.children[0]
      } else {
        current = child
      }
    }

    const data = await chapterDel({ id: node.key })
    if (data) {
      await dispatch(setTreeChapter({ saveBookId: id, saveChapterId: current ? current.key : null }))
      await getChapterTreeList()
    }
  }

  useEffect(() => {
    if (gData && gData.length > 0 && treeChapter && Object.entries(treeChapter).length > 0) {
      if (parseInt(treeChapter.saveBookId) === parseInt(id)) {
        const childInKey = findTreeElementByKey(gData, 'key', treeChapter.saveChapterId)
        if (childInKey && Object.entries(childInKey).length > 0) {
          setChapterId(parseInt(treeChapter.saveChapterId))
          setCheckedKeys([parseInt(treeChapter.saveChapterId)])
          setNowTitle(childInKey.title)
        }
      }
    }
  }, [gData, treeChapter])

  let chapterMenuItems = [
    { key: '1', label: '展开全部' },
    { key: '2', label: '添加子节' },
    { key: '5', label: '设置编者' },
    { key: '3', label: '编辑' },
    { key: '4', label: '删除' }
  ]
  if (!isAdminOrCreator) {
    chapterMenuItems = [{ key: '1', label: '展开全部' }]
  }

  const handleMenuClick = async (e, node) => {
    e.domEvent.stopPropagation()
    setCurrentChapter(node)
    if (parseInt(e.key) === 1) {
      // 展开全部
      const ids = findNodeById([node], 'key', node.key)
      const expandedKeysTemp = [...expandedKeys, node.key, ...ids]
      setExpandedKeys(expandedKeysTemp)
    } else if (parseInt(e.key) === 2) {
      // 添加子节
      setEditKey(-1)
      setEditValue('')
      setParentId(node.key)
    } else if (parseInt(e.key) === 3) {
      // 编辑
      setEditKey(node.key)
      setEditValue(node.title)
      setParentId(false)
    } else if (parseInt(e.key) === 4) {
      await modal.confirm({
        title: '删除确认',
        content: `确认删除子节【${node.title}】？`,
        onOk() {
          delChapter(node)
        }
      })
    } else if (e.key == 5) {
      setEditChapterEditorsIsOpen(true)
    }
  }

  // 章节名称
  const chapterTitleRender = node => {
    return (
      <div className="chapter-tree-item">
        <p className="title">{node.title}</p>
        <Dropdown trigger={['click']} menu={{ items: chapterMenuItems, onClick: e => handleMenuClick(e, node) }}>
          <EllipsisOutlined onClick={e => e.stopPropagation()} />
        </Dropdown>
      </div>
    )
  }

  const onDrop = async info => {
    const dropToGap = info.dropToGap // true 为同级或最大级 false 为子级
    const nowDropNode = info.dragNode.key
    const sideDropNode = info.node.key

    let data = null
    if (dropToGap) {
      // 同级
      const dragOverGapBottom = info.node.dragOverGapBottom
      const dragOver = info.node.dragOver
      const dragOverGapTop = info.node.dragOverGapTop
      if (!dragOverGapTop && !dragOver && !dragOverGapBottom) {
        // 拖到最底部
        // 拖拽到最顶层
        data = await dragOrder({
          book_id: id,
          drag_node: nowDropNode,
          position_node: sideDropNode,
          drop_type: 'after'
        })
      } else {
        if (dragOverGapTop) {
          // 拖拽到最顶层
          data = await dragOrder({
            book_id: id,
            drag_node: nowDropNode,
            position_node: sideDropNode,
            drop_type: 'before'
          })
        } else if (dragOverGapBottom) {
          data = await dragOrder({
            book_id: id,
            drag_node: nowDropNode,
            position_node: sideDropNode,
            drop_type: 'after'
          })
        }
      }
    } else {
      // 子级
      data = await dragOrder({
        book_id: id,
        drag_node: nowDropNode,
        position_node: sideDropNode,
        drop_type: 'inner'
      })
    }
    if (data) {
      await getChapterTreeList()
    }
  }

  return (
    <div className="examine">
      <div className="content-box">
        <Row gutter={10} style={{ height: '100%' }} className="book-content-row">
          <Col span={isCollapse ? 1 : 4} className="book-content-tree">
            <div className="border">
              {!isCollapse ? (
                <>
                  <Descriptions
                    layout="vertical"
                    rootClassName="section-left-top"
                    bordered
                    items={[
                      {
                        key: '1',
                        label: (
                          <Row gutter={5} justify={'space-between'} style={{ alignItems: 'center' }}>
                            <Col>章节目录</Col>
                            <Col>
                              {isAdminOrCreator && <Button type="text" icon={<DiffOutlined />} onClick={addChapterParent}></Button>}
                              <Button type="text" icon={<MenuFoldOutlined />} onClick={() => setisCollapse(true)}></Button>
                            </Col>
                          </Row>
                        )
                      }
                    ]}
                  />
                  {gData && gData.length > 0 && (
                    <Tree
                      className="draggable-tree"
                      onSelect={handleSelect}
                      defaultExpandAll
                      defaultExpandedKeys={expandedKeys}
                      expandedKeys={expandedKeys}
                      defaultSelectedKeys={checkedKeys}
                      selectedKeys={checkedKeys}
                      onDrop={onDrop}
                      draggable
                      blockNode
                      disabled={loading}
                      treeData={gData}
                      onExpand={onExpand}
                      titleRender={nodeData => chapterTitleRender(nodeData)}
                    />
                  )}
                </>
              ) : (
                <Descriptions
                  layout="vertical"
                  bordered
                  items={[
                    {
                      key: '1',
                      label: (
                        <Row gutter={5} justify={'space-between'} style={{ alignItems: 'center' }}>
                          <Col>
                            <Button type="text" icon={<MenuUnfoldOutlined />} onClick={() => setisCollapse(false)}></Button>
                          </Col>
                        </Row>
                      )
                    }
                  ]}
                />
              )}
            </div>
          </Col>
          <Col span={isCollapse ? 23 : 20} className="book-content-tree">
            <div className="editor-right">
              <Spin spinning={loading}>
                <WangEditorCustomer
                  ref={editorRef}
                  chapterId={chapterId}
                  bookId={id}
                  contentId={contentId}
                  setHtml={setHtml}
                  html={html}
                  saveContent={saveContent}
                  gData={gData}
                  nowTitle={nowTitle}
                  disabled={disabled}
                />
              </Spin>
            </div>
          </Col>
        </Row>
      </div>

      <Modal
        open={editKey}
        footer={null}
        centered
        destroyOnClose
        title={editKey > 0 ? '修改章节' : '新增章节'}
        maskClosable={false}
        mask={false}
        closeIcon={false} // 添加这一行以隐藏关闭按钮
        onCancel={() => setEditKey(false)}
        classNames={{
          wrapper: 'chapter-title-modal'
        }}>
        <EditChapterTitle
          setEditKey={setEditKey}
          editValue={editValue}
          editKey={editKey}
          getChapterTreeList={getChapterTreeList}
          setEditValue={setEditValue}
          parentId={parentId}
          bookId={id}
          expandedKeys={expandedKeys}
          setExpandedKeys={setExpandedKeys}
          editorLoading={loading}
          newChapterChange={newChapterChange}
        />
      </Modal>

      {/* 设置章节编写者 */}
      {currentChapter && editChapterEditorsIsOpen && (
        <EditChapterEditors
          open={editChapterEditorsIsOpen}
          chapter={currentChapter}
          onCancel={() => setEditChapterEditorsIsOpen(false)}
          onChange={onChapterEditorsChange}></EditChapterEditors>
      )}
    </div>
  )
}

export default Examine
