/*
 * @Author: yuananting
 * @Date: 2021-02-22 10:59:43
 * @LastEditors: yuananting
 * @LastEditTime: 2021-03-18 09:33:50
 * @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 || [],
    };
  }

  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;
      const defaultNode = { id: "0", categoryName:"未分类", categoryCount: noCategoryCnt}
      categoryList.unshift(defaultNode);
      this.setState({ treeData: this.renderTreeNodes(categoryList, categoryName) });
      this.setState({
        expandedKeys: this.getFirstLevelKeys(categoryList),
      });
    });
  };

  renderTreeNodes = (data, value) => {
    return 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;
    });
  };

  render() {
    const { treeData, expandedKeys, selectedKeys } = 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}
            onExpand={this.onExpand}
            selectedKeys={selectedKeys}
            onSelect={this.onSelect}
            showIcon
            treeData={treeData}
          />
        </div>
        {this.state.NewEditQuestionBankCategory}
        {this.state.ImportCourseCategory}
      </div>
    );
  }
}

export default QuestionBankSider;
