import React from 'react'
import { Cascader } from 'antd'
import PropTypes from 'prop-types'

class KpiCascader extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      options: [],
      defaultValue: []
    }
  }

  componentDidMount() {
    this.getUnitTreeData()
  }

  getUnitTreeData = () => {
    const json = {
      OrgId: this.props.OrgId
    }
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'BD/BDMeterNode/UnitTreeData',
      payload: json,
      onlyData: false,
      onComplete: (re) => {
        if (re && re.IsSuccessful && re.Data) {
          if (re.Data.length > 0) {
            let defaultValue = []
            const model = re.Data[0];
            this.recursive(model, defaultValue);
          }
          this.setState({ options: re.Data }, () => {
            this.props.onLoadData instanceof Function && this.props.onLoadData()
          })
        }
      }
    })
  };

  recursive = (model, defaultValue) => {
    if (model.Children && model.Children.length > 0) {
      defaultValue.push(model.Value)
      this.recursive(model.Children[0], defaultValue)
    }
    else {
      defaultValue.push(model.Value)
      this.setState({ defaultValue })
      this.props.onChange(defaultValue.length > 0 ? defaultValue[defaultValue.length - 1] : '');
    }
  }
  onCascaderChange = (value) => {
    this.setState({defaultValue:value})
    this.props.onChange(value.length > 0 ? value[value.length - 1] : '');
  }
  displayRender = (label) => {
    return label[label.length - 1];
  }


  render() {
    const { options, defaultValue } = this.state
    return (
      <Cascader
        allowClear={false}
        options={options}
        value={defaultValue}
        onChange={this.onCascaderChange}
        fieldNames={{ label: 'Label', value: 'Value', children: 'Children' }}
        displayRender={this.displayRender}
        placeholder='请选择节点'
      />
    )
  }
}

KpiCascader.propTypes = {
  onChange: PropTypes.func,
  OrgId:PropTypes.string,
  dispatch: PropTypes.func,
}

export default KpiCascader