import {
  WeaOrgTree
} from 'ecCom'

import {
  i18n
} from '../../public/i18n';

export default class LeftTree extends React.Component {
  constructor(props) {
    super(props);
    this.tree = null;

    this.setRef = element => {
      this.tree = element;
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.treeRefresh !== nextProps.treeRefresh || this.props.isOrgTreeShow !== nextProps.isOrgTreeShow) {
      return true
    }
    return false
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.treeRefresh !== nextProps.treeRefresh || this.props.isOrgTreeShow !== nextProps.isOrgTreeShow) {
      if (this.tree) this.tree.reset(() => this.tree.fetchData());
    }
  }


  renderItem(item) {
    if (this.hasSpeacialWord(item)) {
      let name = item.name,
        index = name.indexOf(i18n.label.canceled());
      return <div title={name}>
                    <span>{name.slice(0, index)}</span>
                    <span style={{color: 'red'}}>{name.slice(index, index+3)}</span>
                    <span>{name.slice(index+3)}</span>
               </div>
    } else {
      return <div title={item.name}>{item.name}</div>
    }
  }

  hasSpeacialWord(item) {
    return item.name && item.name.includes(i18n.label.canceled()) ? true : false;
  }

  treeNodeClick(e) {
    const {
      treeNodeClick
    } = this.props;

    let type = e.selectedNodes[0].props.type,
      id = e.selectedNodes[0].props.id,
      name = e.selectedNodes[0].props.name,
      pid = this.getParentId(e.selectedNodes[0].key);

    treeNodeClick(type, id, name, pid);
  }

  getParentId(key) {
    return key.split('-').slice(-2, -1);
  }

  render() {
    const {
      ltSearchChange,
      isDisplayBlock,
      orgTreeShValue
    } = this.props;

    return (
      <div style={{height: '100%'}}>
  		        <WeaOrgTree ecId={`${this && this.props && this.props.ecId || ''}_WeaOrgTree@j84sn2`} 
                  ref={this.setRef}
                  rootKey='rootManager' 
                  loading  
                  needSearch
                  noCache
                  inputLeftDom = {`<b>${i18n.label.administrativeDivision()}</b>`} 
                  isLoadAllSub={false}
                  dataUrl={'/api/hrm/area/getTreeDatas?isDisplayBlock='+isDisplayBlock+'&keywordtwo='+orgTreeShValue}
                  treeNodeClick={e => this.treeNodeClick(e)}
                  renderNode={ item => this.renderItem(item)}
                  onSearchChange={val => ltSearchChange(val)}
              />
  		    </div>
    )
  }
}