/*
 * @Description:
 * @Author: zangsuyun
 * @Date: 2021-03-19 18:05:23
 * @LastEditors: wufan
 * @LastEditTime: 2021-05-30 16:48:46
 * @Copyright: © 2020 杭州杰竞科技有限公司 版权所有
 */

import React, { Component } from "react";
import { Input, Button, Tree } from "antd";
import "./Classification.less";
import User from "@/common/js/user";
import KnowledgeAPI from "@/data-source/knowledge/request-api";
import Bus from "@/core/bus";

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

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

  componentDidMount() {
    this.queryCategoryTree();
    Bus.bind('knowledgeCategoryTree', this.queryCategoryTree)
  }

  componentWillUnmount() {
    Bus.unbind('knowledgeCategoryTree', this.queryCategoryTree)
  }

  shouldComponentUpdate = (nextProps, nextState) => {
    const { updateCategoryFlag } = nextProps;
    if (this.props.updateCategoryFlag !== updateCategoryFlag) {
      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 });
    console.log(selectedKeys);
    this.props.getSelectedCategoryId(selectedKeys[0]);
  };

  // 查询分类树
  queryCategoryTree = (categoryName) => {
    let query = {
      categoryName,
      storeId: User.getStoreId(),
      withCount: true,
    };
    KnowledgeAPI.getCategoryTree(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 === "未分类" ? (
          <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="question-bank-sider">
        <div className="sider-title">知识分类</div>
        <Search
          className="sider-search"
          placeholder="搜索名称分类"
          onSearch={(value) => {
            this.queryCategoryTree(value);
          }}
          enterButton={<span className="icon iconfont">&#xe832;</span>}
          style={{width: 230}}
        />
        <div className="sider-btn">
          <Button
            onClick={() => {
              window.RCHistory.push({
                pathname: "/course-category-manage?from=knowledge",
              });
            }}
          >
            分类管理
          </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 Classification;
