import React, { Component } from 'react';
import { TreeSelect } from 'antd';
import {
  systemComDepartGetTreeDepart
} from '../../../services/api';


export default class DepartSelect extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      treeData: [  // 部门数据
        //树
        { title: '', key: '' }
      ],
    };
  }


  componentWillMount() {
    this._getDepart();
  }

  _getDepart = (cb) => {
    //获取部门树数据
    systemComDepartGetTreeDepart().then(
      response => {
        let { data } = response;
        data = JSON.parse(
          JSON.stringify(data).replace(/\"children\":\[\]/g, '"isLeaf":true')
        );
        function digui(arr) {
          return arr.map(item => {
            item.value = item.key + '-' + item.title;
            if(item.children) {
              item.children = digui(item.children);
            }
            return item;
          });
        }
        const departs = digui(data);
        if(this.props.showAll) {
          departs.unshift({
            label: '全部',
            value: ''
          });
        }
        this.setState({
          treeData: departs
        }, () => {
          cb && cb();
        });
      },
      err => {
        console.log(err, 'getTreeDepart-选择部门-err');
      }
    );
  }




  render() {
    return (
      <TreeSelect
        treeData={this.state.treeData}
        {...this.props}
      />
    );
  }
}


export function departSelecter(TreeSelect) {
  return class DepartSelect extends Component {
    constructor(props, context) {
      super(props, context);
      this.state = {
        treeData: [  // 部门数据
          //树
          { title: '', key: '' }
        ],
      };
    }
    componentWillMount() {
      this._getDepart();
    }
  
    _getDepart = (cb) => {
      //获取部门树数据
      systemComDepartGetTreeDepart().then(
        response => {
          let { data } = response;
          data = JSON.parse(
            JSON.stringify(data).replace(/\"children\":\[\]/g, '"isLeaf":true')
          );
          function digui(arr) {
            return arr.map(item => {
              item.value = item.key + '-' + item.title;
              if(item.children) {
                item.children = digui(item.children);
              }
              return item;
            });
          }
          this.setState({
            treeData: digui(data)
          }, () => {
            cb && cb();
          });
        },
        err => {
          console.log(err, 'getTreeDepart-选择部门-err');
        }
      );
    }
  
    render() {
      return (
        <TreeSelect
          treeData={this.state.treeData}
          {...this.props}
        />
      );
    }
  }
}