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

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

class QuestionBankSider extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedKeys: getParameterByName("categoryId")
        ? [getParameterByName("categoryId")]
        : ["0"],
      searchValue: null,
      NewEditQuestionBankCategory: null, //新增或编辑分类模态框
      ImportCourseCategory: null, // 引用课程分类模态框
      treeData: this.props.treeData || [],
      autoExpandParent: false
    };
  }

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

  shouldComponentUpdate(nextProps, nextState) {
    const { updatedCategoryId } = nextProps;
    if (this.props.updatedCategoryId !== updatedCategoryId) {
      this.setState({ selectedKeys: [updatedCategoryId] }, () =>
        this.queryCategoryTree()
      );
    }
    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 = (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);
          });
          this.setState({ expandedKeys: nodeId });
        } else {
          const defaultNode = {
            id: "0",
            categoryName: "未分类",
            categoryCount: noCategoryCnt,
          };
          categoryList.unshift(defaultNode);
          this.setState({
            treeData: this.renderTreeNodes(categoryList, categoryName),
          });
          let nodeId = [];
          Object.keys(this.state.treeMap).forEach((item) => {
            nodeId.push(item);
          });
          this.setState({ expandedKeys: nodeId });
        }
      } else {
        this.setState({ autoExpandParent: false });
        const defaultNode = {
          id: "0",
          categoryName: "未分类",
          categoryCount: noCategoryCnt,
        };
        categoryList.unshift(defaultNode);
        this.setState({
          treeData: this.renderTreeNodes(categoryList, categoryName),
        });
        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 === "未分类" ? (
          <span className="icon iconfont" style={{ color: "#FBD140" }}>
            &#xe7f6;
          </span>
        ) : (
          <span className="icon iconfont" style={{ color: "#FBD140" }}>
            &#xe7f1;
          </span>
        );
      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="question-bank-sider">
        <div className="sider-title">题目分类</div>
        <Search
          className="sider-search"
          placeholder="搜索名称分类"
          onSearch={(value) => {
            // TODO 调用查询分类接口
            this.queryCategoryTree(value);
          }}
        />
        <div className="sider-btn">
          <Button
            onClick={() => {
              window.RCHistory.push({
                pathname: "/question-category-manage",
              });
            }}
          >
            分类管理
          </Button>
        </div>
        <div className="sider-tree">
          <DirectoryTree
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            onExpand={this.onExpand}
            selectedKeys={selectedKeys}
            onSelect={this.onSelect}
            showIcon
            treeData={treeData}
          />
        </div>
        {this.state.NewEditQuestionBankCategory}
        {this.state.ImportCourseCategory}
      </div>
    );
  }
}

export default QuestionBankSider;
