import React from 'react';
import Tree from '../../components/Tree';
import { inject, observer } from 'mobx-react';
import IconFont from '../../themeComponents/IconFont';
import { treeHelper } from '@zenview/micro-utils';
import { Checkbox } from 'antd';
import './index.less';

@inject('place')
@observer
class PlaceTreeWithExpend extends React.Component {
  constructor(props) {
    super(props);
    const { expandedKeys } = this.props;
    this.state = {
      expandedKeys: expandedKeys
    };
  }
  static getDerivedStateFromProps(props, state) {
    const options = {};
    if (!state.expandedKeys && props.expandedKeys) {
      options.expandedKeys = props.expandedKeys;
    }

    if (Object.keys(options).length > 0) {
      return options;
    }
    return null;
  }

  onExpand = expandedKeys => {
    this.setState({
      expandedKeys
    });
  };
  renderSuffix = node => {
    const { showCount, renderSuffix } = this.props;
    if (!renderSuffix && !showCount) {
      return null;
    }
    return (
      <span className="tree-node-suffix">
        {showCount && (
          <>
            <i className="online-count">{node.deviceCount.onlineCount}/</i>
            <i className="count">{node.deviceCount.count}</i>
          </>
        )}
        {renderSuffix && renderSuffix(node)}
      </span>
    );
  };
  onChange = flag => {
    let { placeList } = this.props.place;
    const ids = flag ? placeList.map(v => v.placeId) : [placeList.filter(v => v.level !== 0)[0].placeId];

    this.setState({
      expandedKeys: ids
    });
  };
  render() {
    const { place, className = '', disableCheckbox = false, renderHeader, treeNodeClass, activeKey, treeData, RenderTreeTitle, hasHeader = true, ...props } = this.props;
    const { expandedKeys } = this.state;
    const treeDatas = treeData || treeHelper.computPlaceTree(place.placeList);
    return (
      <div className={`lm-c-place-tree ${className}`}>
        {renderHeader && renderHeader()}
        {hasHeader && (
          <div className="place-tree-header">
            <div className="place-tree-header-icon">
              <IconFont type="icon-S_Place_Place" />
              场所
            </div>
            <Checkbox onChange={e => this.onChange(e.target.checked)}>展开全部</Checkbox>
          </div>
        )}
        <Tree
          {...props}
          treeData={treeDatas}
          onExpand={this.onExpand}
          selectedKeys={[activeKey]}
          expandedKeys={expandedKeys}
          treeNodeProps={{
            treeNodeIcon: node => <IconFont type={`${node.level >= 5 ? 'icon-S_Place_Place' : 'icon-S_Bar_Add'}`} />,
            key: 'id',
            nameKey: 'areaName',
            suffix: this.renderSuffix,
            treeNodeClass: treeNodeClass,
            disableCheckbox: disableCheckbox,
            RenderTreeTitle: RenderTreeTitle
          }}
        />
      </div>
    );
  }
}

export default PlaceTreeWithExpend;
