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

@inject('place')
@observer
class PlaceTree extends React.Component {
  constructor(props) {
    super(props);
    const { expandedKeys, keyword } = this.props;
    this.state = {
      keyword: keyword || null,
      expandedKeys: expandedKeys,
      isKeywordChange: false,
    };
  }
  static getDerivedStateFromProps(props, state) {
    let options = {};
    if (!state.expandedKeys && props.expandedKeys) {
      options.expandedKeys = props.expandedKeys;
    }
    if (props.keyword !== undefined && props.keyword !== state.keyword) {
      options.keyword = props.keyword;
      options.isKeywordChange = true;
    }
    if (Object.keys(options).length > 0) {
      return options;
    }
    return null;
  }
  componentDidUpdate() {
    if (this.state.isKeywordChange) {
      this.setState({ isKeywordChange: false });
      this.onChange(this.state.keyword);
    }
  }
  onKeywordChange = (value) => {
    if (!this.props.keyword) {
      this.onChange(value);
    }
  };
  onChange = (value) => {
    const { place } = this.props;
    let expandedKeys = [];
    if (value) {
      let keys = [];
      const placeList = place.placeList.filter((v) => v.name.indexOf(value) > -1);
      const placeCodes = [];
      placeList.forEach((v) => {
        if (v.pcodes) {
          placeCodes.push(...v.pcodes);
        }
        placeCodes.push(v.areaCode);
      });
      keys = [...new Set([...keys])];
      placeCodes.forEach((v) => {
        let codes = place.getPlaceCodesWithParent(v);
        keys.push(...codes);
      });
      expandedKeys = [...new Set([...keys])];
    }
    this.setState({
      expandedKeys,
      keyword: value,
    });
  };
  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>
    );
  };
  render() {
    const { place, className, title, inputPlaceholder, disableCheckbox, treeNodeClass, activeKey, treeData, hasInput, titleExt = '', ...props } = this.props;
    const { expandedKeys } = this.state;
    const treeDatas = treeData || treeHelper.computPlaceTree(place.placeList);
    return (
      <CBox className={`lm-c-place-tree ${className}`} titleExt={titleExt}>
        <TreeTitle title={title} inputPlaceholder={inputPlaceholder} onChange={this.onKeywordChange} hasInput={hasInput} titleExt={titleExt} />
        {this.props.renderHeader && this.props.renderHeader()}
        <Tree
          {...props}
          treeData={treeDatas}
          onExpand={this.onExpand}
          selectedKeys={activeKey ? (Array.isArray(activeKey) ? activeKey : [activeKey]) : undefined}
          expandedKeys={expandedKeys}
          treeNodeProps={{
            treeNodeIcon: (node) => <IconFont type={`${node.level >= 5 ? 'icon-S_Place_Place' : title ? 'icon-S_Photo_ListTree' : 'icon-S_Bar_Add'}`} />,
            key: 'areaCode',
            nameKey: 'areaName',
            keyword: this.state.keyword,
            suffix: this.renderSuffix,
            treeNodeClass: treeNodeClass,
            disableCheckbox: disableCheckbox,
            RenderTreeTitle: this.props.RenderTreeTitle,
          }}
        />
      </CBox>
    );
  }
}

PlaceTree.defaultProps = {
  title: '行政区划',
  className: '',
  disableCheckbox: false,
};

export default PlaceTree;
