/*
 * @Author: yuananting
 * @Date: 2021-02-22 10:59:43
 * @LastEditors: fusanqiasng
 * @LastEditTime: 2021-06-15 11:20:48
 * @Description: 助学工具-侧边课程分类树
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from 'react';
import { Input, Button, Tree } from 'antd';
import './CourseCategorySiderTree.less';
import User from '@/common/js/user';
import AidToolService from '@/domains/aid-tool-domain/AidToolService';
import Bus from '@/core/bus';

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

class CourseCategorySiderTree extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedKeys: ['QUESTION_INDEX', 'PAPER_INDEX'].includes(props.fromModule) ? [getParameterByName('categoryId') || 'null'] : ['null'],
      treeData: props.treeData || [],
      autoExpandParent: false,
    };
  }

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

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

  // 查询分类树
  queryCategoryTree = (type = 'init', categoryName) => {
    let query = {
      bizType: ['QUESTION_INDEX', 'QUESTION_MODAL'].includes(this.props.fromModule) ? 'QUESTION' : 'PAPER',
      categoryName,
      count: true,
      source: 0,
      userId: User.getStoreUserId(),
      tenantId: User.getStoreId(),
    };
    AidToolService.queryCategoryTree(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 === 'init') {
            this.setState({ expandedKeys: nodeId });
          }
        } else {
          const defaultNode = {
            id: 'null',
            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 === 'init') {
            this.setState({ expandedKeys: nodeId });
          }
        }
      } else {
        this.setState({ autoExpandParent: false });
        const defaultNode = {
          id: 'null',
          categoryName: '未分类',
          categoryCount: noCategoryCnt,
          parentId: '0',
          categoryLevel: 0,
        };
        categoryList.unshift(defaultNode);
        this.setState({
          treeData: this.renderTreeNodes(categoryList, categoryName),
        });
        if (type === 'init') {
          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;
  };

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

  // 树状选中事件
  onSelect = (selectedKeys) => {
    this.setState({ selectedKeys }, () => {
      if (this.props.fromModule === 'QUESTION_INDEX') {
        Bus.trigger('queryQuestionPageList', selectedKeys[0]);
      } else if (this.props.fromModule === 'QUESTION_MODAL') {
        Bus.trigger('queryQuestionPageListWithContent', selectedKeys[0]);
      } else {
        Bus.trigger('queryPaperPageList', selectedKeys[0], 0);
      }
    });
  };

  // 树节点渲染-内容处理
  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 > 0 && <span>（{item.categoryCount}）</span>}
          </span>
        ) : (
          <span style={{ opacity: 0.5 }}>
            {item.categoryName}
            {item.categoryCount > 0 && <span>（{item.categoryCount}）</span>}
          </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'>
        {['QUESTION_INDEX', 'PAPER_INDEX'].includes(this.props.fromModule) && (
          <div className='sider-title'>{this.props.fromModule === 'QUESTION_INDEX' ? '题目分类' : '试卷分类'}</div>
        )}
        <Search
          className='sider-search'
          placeholder='搜索名称分类'
          onSearch={(value) => {
            this.queryCategoryTree('init', value);
          }}
          enterButton={<span className='icon iconfont'>&#xe832;</span>}
        />
        {['QUESTION_INDEX', 'PAPER_INDEX'].includes(this.props.fromModule) && User.getUserRole() !== 'CloudLecturer' && this.props.type !== 'modal-select' && (
          <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;
