/*
 * @Author: yuananting
 * @Date: 2021-02-23 18:28:50
 * @LastEditors: yuananting
 * @LastEditTime: 2021-03-05 10:19:34
 * @Description: 助学工具-题库-主页面分类管理
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from "react";
import Breadcrumbs from "@/components/Breadcrumbs";
import "./QuestionCategoryManage.less";
import NewEditQuestionBankCategory from "./modal/NewEditQuestionBankCategory";
import { Tree, Input, Space, Button, Menu, Dropdown, message } from "antd";
import ShowTips from "@/components/ShowTips";
const { DirectoryTree, Popconfirm } = Tree;
const { Search } = Input;

class QuestionCategoryManage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      NewEditQuestionBankCategory: null, //新增或编辑分类模态框
      treeData: [
        {
          tenantId: "1122334455667788",
          userId: "12345678",
          source: 0,
          id: "1367023655839768500",
          parentId: "0",
          rootId: "1367023655839768500",
          categoryLevel: 0,
          categoryName: "未分类",
          sort: 0,
        },
        {
          tenantId: "1122334455667788",
          userId: "12345678",
          source: 0,
          id: "1367023655839768577",
          parentId: "0",
          rootId: "1367023655839768577",
          categoryLevel: 0,
          categoryName: "分类1",
          subList: [
            {
              tenantId: "1122334455667788",
              userId: "12345678",
              source: 0,
              id: "1367023709942095873",
              parentId: "1367023655839768577",
              rootId: "1367023655839768577",
              categoryLevel: 1,
              categoryName: "test",
              sort: 0,
            },
            {
              tenantId: "1122334455667788",
              userId: "12345678",
              source: 0,
              id: "1367023725184196609",
              parentId: "1367023655839768577",
              rootId: "1367023655839768577",
              categoryLevel: 1,
              categoryName: "分类2",
              subList: [
                {
                  tenantId: "1122334455667788",
                  userId: "12345678",
                  source: 0,
                  id: "1367023805563838466",
                  parentId: "1367023725184196609",
                  rootId: "1367023655839768577",
                  categoryLevel: 2,
                  categoryName: "test",
                  sort: 0,
                },
              ],
              sort: 1,
            },
          ],
          sort: 1,
        },
        {
          tenantId: "1122334455667788",
          userId: "12345678",
          source: 0,
          id: "1367049864988516353",
          parentId: "0",
          rootId: "1367049864988516353",
          categoryLevel: 0,
          categoryName: "分类2",
          subList: [
            {
              tenantId: "1122334455667788",
              userId: "12345678",
              source: 0,
              id: "1367049931656978433",
              parentId: "1367049864988516353",
              rootId: "1367049864988516353",
              categoryLevel: 1,
              categoryName: "分类2",
              subList: [
                {
                  tenantId: "1122334455667788",
                  userId: "12345678",
                  source: 0,
                  id: "1367049973746819074",
                  parentId: "1367049931656978433",
                  rootId: "1367049864988516353",
                  categoryLevel: 2,
                  categoryName: "分类3",
                  subList: [
                    {
                      tenantId: "1122334455667788",
                      userId: "12345678",
                      source: 0,
                      id: "1367050021431861249",
                      parentId: "1367049973746819074",
                      rootId: "1367049864988516353",
                      categoryLevel: 3,
                      categoryName: "分类4",
                      subList: [
                        {
                          tenantId: "1122334455667788",
                          userId: "12345678",
                          source: 0,
                          id: "1367050063035162626",
                          parentId: "1367050021431861249",
                          rootId: "1367049864988516353",
                          categoryLevel: 4,
                          categoryName: "分类5",
                          sort: 0,
                        },
                      ],
                      sort: 0,
                    },
                  ],
                  sort: 0,
                },
              ],
              sort: 0,
            },
          ],
          sort: 2,
        },
      ],
      treeMap: {},
    };
  }

  componentDidMount() {
    this.setState({ treeData: this.renderTreeNodes(this.state.treeData) });
    this.setState({
      expandedKeys: this.getFirstLevelKeys(this.state.treeData),
    });
  }

  // 新增分类
  newEditQuestionCategory = (categoryType, id, parentId, addLevelType) => {
    let title = "";
    let label = "";
    switch (categoryType) {
      case "newEqualLevelCategory":
        title = "新增分类";
        label = "分类名称";
        break;
      case "newChildLevelCategory":
        title = "新增子分类";
        label = "子分类名称";
        break;
      case "editEqualLevelCategory":
        title = "编辑分类";
        label = "分类名称";
        break;
      case "editChildLevelCategory":
        title = "编辑子分类";
        label = "子分类名称";
        break;
    }
    const m = (
      <NewEditQuestionBankCategory
        id={id}
        parentId={parentId}
        addLevelType={addLevelType}
        treeData={this.state.treeData}
        title={title}
        label={label}
        close={() => {
          this.setState({
            NewEditQuestionBankCategory: null,
          });
        }}
      />
    );
    this.setState({ NewEditQuestionBankCategory: m });
  };

  initDropMenu = (item) => {
    return (
      <Menu>
        <Menu.Item key="0">
          <span
            onClick={() => {
              let categoryType =
                item.categoryLevel === 0
                  ? "editEqualLevelCategory"
                  : "editChildLevelCategory";
              this.newEditQuestionCategory(
                categoryType,
                item.id,
                item.parentId,
                "equal"
              );
            }}
          >
            重命名
          </span>
        </Menu.Item>
        <Menu.Item key="1">
          <span>删除</span>
        </Menu.Item>
      </Menu>
    );
  };

  getRelatedNodes = (parentId) => {
    console.log("parentId:", parentId);
    return this.state.treeMap[parentId].subList
      ? this.state.treeMap[parentId].subList
      : [];
  };

  onDrop = (info) => {
    console.log("info:", info);
    // 未分类不可以拖拽
    if (info.dragNode.id === "1367023655839768500") return;
    // 不允许其他节点拖拽到未分类之前
    if (
      info.node.id === "1367023655839768500" &&
      info.dropToGap &&
      info.dropPosition === -1
    )
      return;

    let targetParentId = info.dropToGap ? info.node.parentId : info.node.id;

    let relatedNodes = this.getRelatedNodes(targetParentId);

    console.log(
      "relatedNodes:",
      relatedNodes.length,
      relatedNodes,
      targetParentId
    );

    const dropKey = info.node.key;
    const dragKey = info.dragNode.key;
    const dropPos = info.node.pos.split("-");
    const dropPosition =
      info.dropPosition - Number(dropPos[dropPos.length - 1]);

    const loop = (data, key, callback) => {
      for (let i = 0; i < data.length; i++) {
        if (data[i].key === key) {
          return callback(data[i], i, data);
        }
        if (data[i].subList) {
          loop(data[i].subList, key, callback);
        }
      }
    };
    const data = [...this.state.treeData];

    let getSuf = function (name, sufIndex) {
      if (relatedNodes.length > 0) {
        let sameNameNodes = [];
        relatedNodes.forEach((item) => {
          if (item.id === info.dragNode.id) return true;
          if (item.categoryName === name) {
            sameNameNodes.push(item);
            console.log(item, sameNameNodes);
          }
        });

        if (sameNameNodes.length > 0) {
          sufIndex++;
          return getSuf(name + `(${sufIndex})`, sufIndex);
        }
      }
      return sufIndex;
    };

    let dragObj;
    loop(data, dragKey, (item, index, arr) => {
      arr.splice(index, 1);
      item.parentId = targetParentId;
      if (item.originCategoryName) {
        item.categoryName = item.originCategoryName;
      } else {
        item.originCategoryName = item.categoryName;
      }
      info.dragNode.categoryName = item.originCategoryName;

      console.log("info.dragNode.categoryName:", info.dragNode.categoryName);
      let sufIndex = getSuf(info.dragNode.categoryName, 0);

      console.log("sufIndex1:", sufIndex);
      console.log("sufIndex2:", sufIndex > 0 ? `${sufIndex}` : "");

      item.categoryName =
        item.originCategoryName + (sufIndex ? `(${sufIndex})` : "");
      dragObj = item;
    });

    if (!info.dropToGap) {
      loop(data, dropKey, (item) => {
        item.subList = item.subList || [];
        item.subList.push(dragObj);
      });
    } else if (
      (info.node.props.subList || []).length > 0 &&
      info.node.props.expanded &&
      dropPosition === 1
    ) {
      loop(data, dropKey, (item) => {
        item.subList = item.children || [];
        item.subList.push(dragObj);
      });
    } else {
      let ar;
      let i;
      loop(data, dropKey, (item, index, arr) => {
        ar = arr;
        i = index;
      });
      if (dropPosition === -1) {
        ar.splice(i, 0, dragObj);
      } else {
        ar.splice(i + 1, 0, dragObj);
      }
    }

    console.log("data:", data)
    this.setState({ treeData: this.renderTreeNodes(this.handleLoop(data, 0)) });
  };

  handleLoop = (data, level) => {
    data.map((item, index) => {
      item.categoryLevel = level;
      item.sort = index;
      if (item.children) {
        this.handleLoop(item.children, level + 1);
      }
      return item;
    });
    return data;
  };

  /** 获取树状第一级key 设置默认展开第一项 */
  getFirstLevelKeys = (data) => {
    let firstLevelKeys = [];
    data.forEach((item) => {
      if (item.categoryLevel === 0) {
        firstLevelKeys.push(item.key);
      }
    });
    return firstLevelKeys;
  };

  /** 树状展开事件 */
  onExpand = (expandedKeys) => {
    this.setState({ expandedKeys });
  };

  renderTreeNodes = (data, value) => {
    let newTreeData = data.map((item) => {
      item.title = item.categoryName;
      item.key = item.id;
      item.title = (
        <div
          style={{
            opacity:
              !value || (value && item.categoryName.indexOf(value) > -1)
                ? 1
                : 0.5,
          }}
          className="node-title-div"
          onMouseOver={(e) => {
            let mouseNodeOpts = e.currentTarget.getElementsByTagName("div")[0];
            mouseNodeOpts.style.visibility = "visible";
          }}
          onMouseOut={(e) => {
            let mouseNodeOpts = e.currentTarget.getElementsByTagName("div")[0];
            mouseNodeOpts.style.visibility = "hidden";
          }}
        >
          <span>{item.categoryName}</span>
          {item.id !== "1367023655839768500" && (
            <Space className="title-opts" size={50}>
              <span
                className="icon iconfont"
                onClick={() => {
                  let nodesCount = 0;
                  const { treeData } = this.state;
                  if (item.categoryLevel === 0) {
                    // 第一层级
                    nodesCount = treeData.length;
                  } else {
                    let parentNodes = this.getRelatedNodes(item.parentId);
                    nodesCount =
                      parentNodes.length > 0
                        ? parentNodes[0].subList.length
                        : 0;
                  }
                  if (nodesCount >= 30) {
                    message.info("最多只能添加30个分类");
                    return;
                  }
                  this.newEditQuestionCategory(
                    "newEqualLevelCategory",
                    item.id,
                    item.parentId,
                    "equal"
                  );
                }}
              >
                &#xe7f5; 同级
              </span>
              {item.categoryLevel < 4 && (
                <span
                  className="icon iconfont"
                  onClick={() => {
                    if (item.subList && item.subList.length >= 30) {
                      message.info("最多只能添加30个子分类");
                      return;
                    }
                    this.newEditQuestionCategory(
                      "newChildLevelCategory",
                      item.id,
                      item.parentId,
                      "child"
                    );
                  }}
                >
                  &#xe7f8; 子级
                </span>
              )}
              <Dropdown overlay={this.initDropMenu(item)}>
                <span className="icon iconfont">更多 &#xe7f7;</span>
              </Dropdown>
            </Space>
          )}
        </div>
      );
      item.icon =
        item.id === "default" ? (
          <span className="icon iconfont" style={{ color: "#FBD140" }}>
            &#xe7f6;
          </span>
        ) : (
          <span className="icon iconfont" style={{ color: "#FBD140" }}>
            &#xe7f1;
          </span>
        );

      if (item.subList) {
        item.children = this.renderTreeNodes(item.subList, value);
      }
      return item;
    });

    this.getFirstLevelKeys(newTreeData);

    let map = {};
    let getChildren = function (data) {
      data.forEach((item) => {
        map[item.id] = item;
        if (item.subList && item.subList.length > 0) {
          getChildren(item.subList);
        }
      });
    };
    getChildren(data);
    console.log("map:", map);

    this.setState({ treeMap: map });
    return newTreeData;
  };

  render() {
    const { treeData, expandedKeys } = this.state;
    return (
      <div className="page question-category-manage">
        <Breadcrumbs navList="课程分类" goBack={() => RCHistory.goBack()} />
        <div className="box">
          <div className="search-condition">
            <span className="search-label">搜索名称：</span>
            <Search
              placeholder="请输入名称"
              style={{ width: "calc(100% - 84px)" }}
              onSearch={(value) =>
                // TODO 调用查询分类接口
                this.setState({
                  treeData: this.renderTreeNodes(treeData, value),
                })
              }
            />
          </div>
          <Button
            type="primary"
            onClick={() => {
              if (treeData.length >= 30) {
                message.info("最多只能添加30个分类");
                return;
              }
              this.newEditQuestionCategory(
                "newEqualLevelCategory",
                "1367023655839768500",
                "0",
                "equal"
              );
            }}
          >
            新增一级分类
          </Button>
          <div className="show-tips" style={{ marginTop: 12 }}>
            <ShowTips message="为方便管理，该分类用于课程、培训计划、题库、知识库等模块，改动将同步各模块更新" />
          </div>
          <div className="course-category-tree">
            <DirectoryTree
              expandedKeys={expandedKeys}
              onExpand={this.onExpand}
              defaultSelectedKeys={["1367023655839768500"]}
              draggable
              blockNode
              onDrop={this.onDrop}
              treeData={treeData}
            ></DirectoryTree>
          </div>
        </div>
        {this.state.NewEditQuestionBankCategory}
      </div>
    );
  }
}

export default QuestionCategoryManage;
