import React, { useState, useEffect, useRef } from 'react';
import {
  Divider,
  Button,
  Row,
  Col,
  Descriptions,
  Tree,
  Tooltip,
  Dropdown,
  Space,
  Input,
  Popconfirm,
  Modal,
  Spin,
} from 'antd';
import {
  DiffOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  EyeOutlined,
  DashOutlined,
  CloseOutlined,
  CheckOutlined,
  EllipsisOutlined,
} 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 { 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,
  getRecordList,
  getUserInfo,
  getPowerByRoleId,
} from './request';
import './index.less';

const Examine = () => {
  const location = useLocation();
  const id = get(location, 'state.id', '');

  const { treeChapter } = 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 [nameList, setNameList] = useState([]);
  const [openDel, setOpenDel] = useState(false);
  const [delNode, setDelNode] = useState({});
  const [recordList, setRecordList] = useState([]);

  // 树节点设置
  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 [delLoading, setDelLoading] = useState(false);
  const [contentMd5, setContentMd5] = useState('');
  const [quanXian, setQuanXian] = useState(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 getQuanXian = async () => {
    const data = await getUserInfo();
    const data1 = await getPowerByRoleId({ role_id: data.id });
    if (!data1.includes(37)) {
      setQuanXian(true);
    }
  };

  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 getChapterVal = async () => {
    setLoading(true);
    const data = await getInfoByChapterId({ chapter_id: chapterId });
    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();
    getQuanXian();
  }, []);
  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);
          autoSaveContent(newMd5);
          dispatch(setAutosaveTime(Date.now()));
        }
      }
    }
  };
  // 定时器轮询
  const autoSaveContent = (newMd5) => {
    // clearInterval(saveInterRef.current);
    // saveInterRef.current = setInterval(async () => {
    //   if (!contentMd5 || (newMd5 !== contentMd5 && contentMd5)) {
    //     // console.log('save', newMd5, '不一样的');
    //     await saveContent();
    //   } else {
    //     // console.log('save', newMd5, '一样的');
    //   }
    // }, 5000);
  };
  useEffect(() => {
    if (!loading && contentId) {
      let newMd5 = md5(html);
      clearInterval(saveInterRef.current);
      autoSaveContent(newMd5);
    } else {
      clearInterval(saveInterRef.current);
    }
  }, [contentId, loading, contentMd5, html]);

  const addChapterParent = () => {
    setEditKey(-1);
    setEditValue('');
    setParentId(-1);
  };
  const dropDownMenuHandler = async (e, node) => {
    e.domEvent.stopPropagation();
    e.domEvent.preventDefault();

    if (parseInt(e.key) === 1) {
      // 展开
      const ids = findNodeById(gData, 'key', node.key);
      const expandedKeysTemp = [...expandedKeys, node.key];
      ids.forEach((item, index) => {
        if (!expandedKeysTemp.includes(item)) {
          expandedKeysTemp.push(item);
        }
      });
      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) {
      setDelNode(node);
      setOpenDel(true);
    }
  };

  const delChapter = async (node) => {
    setDelLoading(true);
    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 }),
      );
      setDelNode({});
      setOpenDel(false);
      await getChapterTreeList();
    }
    setDelLoading(false);
  };

  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]);

  useEffect(() => {
    console.log(expandedKeys);
  }, [expandedKeys]);

  // 编辑章节名称
  const titleRenderDom = (node) => {
    return (
      <div className='tree-customer-item'>
        <div className='title'>
          <div className='title-node'>{node.title}</div>
        </div>
        <div className='opaeration'>
          {quanXian ? (
            <Dropdown
              trigger={['click']}
              overlayClassName='dropmenu_list'
              destroyPopupOnHide={true}
              menu={{
                items: [
                  {
                    key: '1',
                    label: <Button type='text'>展开全部</Button>,
                  },
                  {
                    key: '2',
                    label: <Button type='text'>添加子节</Button>,
                  },

                  {
                    key: '4',
                    label: <Button type='text'>删除</Button>,
                  },
                ],
                onClick: (e) => dropDownMenuHandler(e, node),
              }}
            >
              <div className='dashed'>
                <span></span>
                <span></span>
                <span></span>
              </div>
              {/* <EllipsisOutlined /> */}
            </Dropdown>
          ) : (
            <Dropdown
              trigger={['click']}
              overlayClassName='dropmenu_list'
              destroyPopupOnHide={true}
              menu={{
                items: [
                  {
                    key: '1',
                    label: <Button type='text'>展开全部</Button>,
                  },
                  {
                    key: '2',
                    label: <Button type='text'>添加子节</Button>,
                  },
                  {
                    key: '3',
                    label: <Button type='text'>编辑</Button>,
                  },
                  {
                    key: '4',
                    label: <Button type='text'>删除</Button>,
                  },
                ],
                onClick: (e) => dropDownMenuHandler(e, node),
              }}
            >
              <div className='dashed'>
                <span></span>
                <span></span>
                <span></span>
              </div>
              {/* <EllipsisOutlined /> */}
            </Dropdown>
          )}
        </div>
      </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>
                                <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) => titleRenderDom(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}
                  recordList={recordList}
                />
              </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>

      <Modal
        open={openDel}
        footer={null}
        centered
        destroyOnClose
        title={'删除确认'}
        maskClosable={false}
        mask={true}
        closeIcon={false} // 添加这一行以隐藏关闭按钮
        onCancel={() => setOpenDel(false)}
        classNames={{
          wrapper: 'chapter-title-modal',
        }}
      >
        <Divider />
        <div className=''>确认删除子节【{delNode.title}】？</div>
        <div className='' style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <Space>
            <Button type='primary' danger loading={delLoading} onClick={() => delChapter(delNode)}>
              确定
            </Button>
            <Button
              type='default'
              onClick={() => {
                setDelNode({});
                setOpenDel(false);
              }}
            >
              取消
            </Button>
          </Space>
        </div>
      </Modal>
    </div>
  );
};

export default Examine;
