/*
 * @Author: yuananting
 * @Date: 2021-02-22 10:59:43
 * @LastEditors: yuananting
 * @LastEditTime: 2021-03-27 13:51:43
 * @Description: 助学工具-题库-课程分类侧边栏
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from "react";
import { Input, Button, Tree } from "antd";
import "./CourseCategorySiderTree.less";
import User from "@/common/js/user";
import QuestionBankService from "@/domains/question-bank-domain/QuestionBankService";

const { Search } = Input;
const { DirectoryTree } = Tree;

class CourseCategorySiderTree extends Component {
  constructor(props) {
    super(props);
    const categoryId = getParameterByName("categoryId");
    this.state = {
      selectedKeys: categoryId
        ? categoryId === "null"
          ? ["0"]
          : [categoryId]
        : ["0"],
      searchValue: null,
      treeData: this.props.treeData || [],
      autoExpandParent: false,
    };
  }

  componentDidMount() {
    this.queryCategoryTree("change");
    this.props.getSelectedCategoryId(
      getParameterByName("categoryId")
        ? [getParameterByName("categoryId")]
        : ["0"]
    );
  }

  shouldComponentUpdate(nextProps, nextState) {
    const { currentTotal, updatedCategoryId } = nextProps;
    if (
      this.props.currentTotal !== currentTotal &&
      this.props.updatedCategoryId === updatedCategoryId
    ) {
      this.queryCategoryTree("remain");
    }
    return true;
  }

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

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

  /** 树状选中事件 */
  onSelect = (selectedKeys) => {
    this.setState({ selectedKeys });
    this.props.getSelectedCategoryId(selectedKeys);
  };

  // 查询分类树
  queryCategoryTree = (type, categoryName) => {
    let query = {
      source: 0,
      categoryName,
      userId: User.getStoreUserId(),
      tenantId: User.getStoreId(),
    };
    QuestionBankService.queryQuestionCategoryTree(query).then((res) => {
      const { categoryList = [], noCategoryCnt = 0 } = res.result;
      let str = "未分类";
      if (categoryName) {
        this.setState({ autoExpandParent: true });
        if (str.indexOf(categoryName) < 0) {
          this.setState({
            treeData: this.renderTreeNodes(categoryList, categoryName),
          });
          let nodeId = [];
          Object.keys(this.state.treeMap).forEach((item) => {
            nodeId.push(item);
          });
          if (type === "change") {
            this.setState({ expandedKeys: nodeId });
          }
        } else {
          const defaultNode = {
            id: "0",
            categoryName: "未分类",
            categoryCount: noCategoryCnt,
            parentId: "0",
            categoryLevel: 0,
          };
          categoryList.unshift(defaultNode);
          this.setState({
            treeData: this.renderTreeNodes(categoryList, categoryName),
          });
          let nodeId = [];
          Object.keys(this.state.treeMap).forEach((item) => {
            nodeId.push(item);
          });
          if (type === "change") {
            this.setState({ expandedKeys: nodeId });
          }
        }
      } else {
        this.setState({ autoExpandParent: false });
        const defaultNode = {
          id: "0",
          categoryName: "未分类",
          categoryCount: noCategoryCnt,
          parentId: "0",
          categoryLevel: 0,
        };
        categoryList.unshift(defaultNode);
        this.setState({
          treeData: this.renderTreeNodes(categoryList, categoryName),
        });
        if (type === "change") {
          this.setState({ expandedKeys: [] });
        }
      }
    });
  };

  getTreeMap = (data, map) => {
    data.forEach((item) => {
      map[item.id] = item;
      if (item.sonCategoryList && item.sonCategoryList.length > 0) {
        this.getTreeMap(item.sonCategoryList, map);
      }
    });
    return map;
  };

  renderTreeNodes = (data, value) => {
    let newTreeData = data.map((item) => {
      item.title = item.categoryName;
      item.key = item.id;
      item.title =
        !value || (value && item.categoryName.indexOf(value) > -1) ? (
          <span>
            {item.categoryName}（{item.categoryCount}）
          </span>
        ) : (
          <span style={{ opacity: 0.5 }}>
            {item.categoryName}（{item.categoryCount}）
          </span>
        );
      item.icon =
        item.categoryName === "未分类" ? (
          <img
            style={{ width: "24px", height: "24px", opacity: !value || (value && item.categoryName.indexOf(value) > -1) ? 1 : 0.5 }}
            src="https://image.xiaomaiketang.com/xm/defaultCategory.png"
            alt=""
          />
        ) : (
          <img
            style={{ width: "24px", height: "24px", opacity: !value || (value && item.categoryName.indexOf(value) > -1) ? 1 : 0.5  }}
            src="https://image.xiaomaiketang.com/xm/hasCategory.png"
            alt=""
          />
        );
      if (item.sonCategoryList) {
        item.children = this.renderTreeNodes(item.sonCategoryList, value);
      }
      return item;
    });
    let map = {};
    this.setState({ treeMap: this.getTreeMap(data, map) });
    return newTreeData;
  };

  render() {
    const {
      treeData,
      expandedKeys,
      selectedKeys,
      autoExpandParent,
    } = this.state;
    return (
      <div className="category-tree-sider">
        <div className="sider-title">题目分类</div>
        <Search
          className="sider-search"
          placeholder="搜索名称分类"
          onSearch={(value) => {
            this.queryCategoryTree("change", value);
          }}
          enterButton={<span className="icon iconfont">&#xe832;</span>}
        />
        {User.getUserRole() !== "CloudLecturer" && (
          <div className="sider-btn">
            <Button
              onClick={() => {
                window.RCHistory.push({
                  pathname: "/course-category-manage?from=aid",
                });
              }}
            >
              分类管理
            </Button>
          </div>
        )}
        <div className="sider-tree">
          <DirectoryTree
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            onExpand={this.onExpand}
            selectedKeys={selectedKeys}
            onSelect={this.onSelect}
            showIcon
            treeData={treeData}
          />
        </div>
      </div>
    );
  }
}

export default CourseCategorySiderTree;
