import { useState, useEffect, useRef, useCallback } 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 BindKnowledgeGraph from './components/BindKnowledgeGraph'
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 [sidebarWidth, setSidebarWidth] = useState(280)
  const isResizing = useRef(false)
  const sidebarRef = useRef(null)
  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 [bindKnowledgeGraphIsOpen, setBindKnowledgeGraphIsOpen] = useState(false)

  // 拖拽改变侧边栏宽度
  const handleMouseDown = useCallback(
    (e) => {
      e.preventDefault()
      isResizing.current = true
      document.body.style.cursor = 'col-resize'
      document.body.style.userSelect = 'none'

      const startX = e.clientX
      const startWidth = sidebarWidth

      const handleMouseMove = (e) => {
        if (!isResizing.current) return
        const delta = e.clientX - startX
        const newWidth = Math.min(Math.max(startWidth + delta, 200), 600)
        setSidebarWidth(newWidth)
      }

      const handleMouseUp = () => {
        isResizing.current = false
        document.body.style.cursor = ''
        document.body.style.userSelect = ''
        document.removeEventListener('mousemove', handleMouseMove)
        document.removeEventListener('mouseup', handleMouseUp)
      }

      document.addEventListener('mousemove', handleMouseMove)
      document.addEventListener('mouseup', handleMouseUp)
    },
    [sidebarWidth],
  )

  // 编辑器内容
  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, ...data }))

    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 (selectedKeys, info) => {
    if (!info.node) return
    const { key, title } = info.node

    // 保持选中状态，防止重复点击导致选中状态消失
    setCheckedKeys([key])

    // 如果点击的是当前已经选中的章节，且没有发生章节切换，则直接返回
    if (key === chapterId) {
      return
    }

    setLoading(true)
    // 切换章节前清理保存定时器并执行一次保存
    clearInterval(saveInterRef.current)
    await saveContent()

    // 清理旧内容
    if (editorRef.current && editorRef.current.editor) {
      editorRef.current.editor.clear()
    }

    // 设置新章节 ID，触发 useEffect 加载数据
    setChapterId(key)
    setNowTitle(title)
    setLoading(false)
  }

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

  useEffect(() => {
    if (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: '7', label: '关联知识图谱' },
    { key: '5', label: '设置编者' },
    {
      key: '6',
      label: '一键AI',
      children: [
        { key: '61', label: '一键AI创作课件', disabled: true },
        { key: '62', label: '一键AI创作教案', disabled: true },
      ],
    },
    { 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)
    } else if (e.key == 7) {
      setBindKnowledgeGraphIsOpen(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">
        <div className="book-content-row">
          <div
            ref={sidebarRef}
            className="book-content-tree"
            style={{ width: isCollapse ? 50 : sidebarWidth, minWidth: isCollapse ? 50 : 200, flexShrink: 0 }}>
            <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>
          </div>
          {!isCollapse && <div className="resize-handle" onMouseDown={handleMouseDown} />}
          <div className="book-content-editor" style={{ flex: 1, minWidth: 0 }}>
            <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>
          </div>
        </div>
      </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>
      )}
      {/* 关联知识图谱 */}
      {currentChapter && bindKnowledgeGraphIsOpen && (
        <BindKnowledgeGraph
          open={bindKnowledgeGraphIsOpen}
          chapter={currentChapter}
          onCancel={() => setBindKnowledgeGraphIsOpen(false)}
          onOk={() => setBindKnowledgeGraphIsOpen(false)}></BindKnowledgeGraph>
      )}
    </div>
  )
}

export default Examine
