import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Select,DatePicker,TreeSelect,Button } from 'amos-antd';
import { AmosFetch } from '../../../utils/processor';
import OltSerUrl from '../../../consts/urlConsts';
import { subViewListAction,subviewByOrgCodeAction,fetchCompanyById,fetchSubEgpListAction } from './../../../services/topoService';

const Option = Select.Option;
const TreeNode = Select.TreeNode;
/**
 * 查询
 *
 * @class QueryPanel
 * @extends {Component}
 */
class QueryPanel extends Component {
  constructor(props) {
    super(props);
    this.state = {
      treeData: [],
      selectedItem: {},
      deviceOption: [],
      capacityOption: []
    };
  }

  componentDidMount(){
    this.getCompanyByUserID();
  }

  //搜索
  onSearch = (e) => {
    this.props.getHistoryData();
  }


  onSelect = (selectedKeys, info) =>{
    let selectedItem = this.state;
    selectedItem[type] = value;
    if (value) {
      fetchCompanyById(value).then(data => {
        data && subviewByOrgCodeAction(data.compCode).then(data => {
          let viewOption = [];
          data.map(e=>viewOption.push(<Option key={e.id} value={e.id}>{e.name}</Option>));
          selectedItem.device = undefined;
          selectedItem.capacity = undefined;
          selectedItem.view = undefined;
          this.setState({ viewOption,selectedItem,deviceOption: [],capacityOption: [] });
          this.props.setEmptyParam();
        });
      });
    } else {
      selectedItem.device = undefined;
      selectedItem.capacity = undefined;
      selectedItem.view = undefined;
      this.setState({ selectedItem,deviceOption: [],capacityOption: [],viewOption: [] });
      this.props.setEmptyParam();
    }

  }


  onSelectedChange = (value,type) => {
    let selectedItem = this.state;
    selectedItem[type] = value;
    if (type === 'company') {
      if (value) {
        fetchCompanyById(value).then(data => {
          data && subviewByOrgCodeAction(data.orgCode).then(data => {
            let viewOption = [];
            data.map(e=>viewOption.push(<Option key={e.id} value={e.id}>{e.name}</Option>));
            selectedItem.device = undefined;
            selectedItem.capacity = undefined;
            selectedItem.view = undefined;
            this.setState({ viewOption,selectedItem,deviceOption: [],capacityOption: [] });
            this.props.setEmptyParam();
          });
        });
      } else {
        selectedItem.device = undefined;
        selectedItem.capacity = undefined;
        selectedItem.view = undefined;
        this.setState({ selectedItem,deviceOption: [],capacityOption: [],viewOption: [] });
        this.props.setEmptyParam();
      }
    } else if (type === 'view') {
      if (value) {
        fetchSubEgpListAction(value).then(data => {
          let deviceOption = [];
          data.map((item)=>{
            deviceOption.push(<Option key={item.id} value={`${item.id}`}>{item.name}</Option>);
          });
          selectedItem.device = undefined;
          selectedItem.capacity = undefined;
          this.setState({ deviceOption,capacityOption: [],selectedItem });
          this.props.setEmptyParam();
        });
      } else {
        selectedItem.device = undefined;
        selectedItem.capacity = undefined;
        this.setState({ capacityOption: [],selectedItem,deviceOption: [] });
        this.props.setEmptyParam();
      }
    } else if (type === 'device') {
      if (value) {
        let url = `${OltSerUrl.getDeviceTemplateByEgpId}/${value}`;
        AmosFetch.get(url).then(res => {
          if (res.ok) {
            return res.json();
          }
          else {
            throw new Error('从服务端获取数据失败！');
          }
        }).then((data) => {
          if (data.result === 'SUCCESS') {
            let deviceData = data.dataList;
            let capacityOption = [];
            deviceData.capabilities.map((item)=>{
              capacityOption.push(<Option key={item.id} value={`${item.id}`}>{item.name}</Option>);
            });
            this.setState({ capacityOption,selectedItem });
          }
        });
        //更新查询条件
      } else {
        selectedItem.capacity = undefined;
        this.setState({ selectedItem,capacityOption: [] });
        this.props.setEmptyParam();
      }
      this.props.setSearchDeviceParam(value);
    } else if (type === 'capacity') {
      this.setState({ selectedItem });
      this.props.setSearchCapacityParam(value);
    } else if (type === 'start') {
      let { setStartTimeParam } = this.props;
      if (value !== null) {
        let time = value.format('YYYY-MM-DD HH:mm:ss');
        setStartTimeParam(time);
      } else {
        setStartTimeParam(undefined);
      }
    } else if (type === 'end') {
      let { setEndTimeParam } = this.props;
      if (value !== null) {
        let time = value.format('YYYY-MM-DD HH:mm:ss');
        setEndTimeParam(time);
      } else {
        setEndTimeParam(undefined);
      }
    }
  }

  getCompanyByUserID = () => {
    subViewListAction().then(data => {
      console.log(data);
      this.setState({ treeData: data });
    });
  }


  renderTreeNodes = (data) => {
    return data && data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.companyName} key={item.orgCode} value={item.sequenceNbr} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      } else {
        return <TreeNode title={item.companyName} key={item.orgCode} value={item.sequenceNbr} {...item} />;
      }
    });
  }

  render() {
    let { treeData,deviceOption,capacityOption,viewOption,selectedItem } = this.state;
    let { company,view,device,capacity } = selectedItem;
    return (
      <div className='search-root'>
        <div className='company-select'>
          <TreeSelect
            dropdownMatchSelectWidth
            style={{ width: 160 }}
            //value={company}
            dropdownStyle={{ maxHeight: 160, overflow: 'auto' }}
            // treeData={treeData}
            placeholder="选择公司"
            treeDefaultExpandAll
            onChange={(e)=>this.onSelectedChange(e,'company')}
            allowClear
          >

          {this.renderTreeNodes(treeData)}
          </TreeSelect>

        </div>
        <div className='subgraph-select'>
          <Select
            style={{ width: '160px' }}
            dropdownStyle={{ width: '160px' }}
            dropdownMatchSelectWidth
            onChange={(e)=>this.onSelectedChange(e,'view')}
            placeholder='选择视图'
            value={view}
            allowClear
          >
            {viewOption}
          </Select>
        </div>
        <div className='device-select'>
          <Select
            style={{ width: '160px' }}
            dropdownStyle={{ width: '160px' }}
            dropdownMatchSelectWidth
            onChange={(e)=>this.onSelectedChange(e,'device')}
            placeholder='选择设备'
            value={device}
            allowClear
          >
            {deviceOption}
          </Select>
        </div>
        <div className='capacity-select'>
          <Select
            style={{ width: '160px' }}
            dropdownStyle={{ width: '160px' }}
            dropdownMatchSelectWidth
            onChange={(e)=>this.onSelectedChange(e,'capacity')}
            value={capacity}
            placeholder='选择设备能力'
            allowClear
          >
            {capacityOption}
          </Select>
        </div>
        <div className='starttime-select'>
          <DatePicker
            showTime
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="开始时间"
            onChange={(e)=>this.onSelectedChange(e,'start')}
            onOk={this.onStartTime}
            allowClear
          />
        </div>
        <div className='endtime-select'>
          <DatePicker
            showTime
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="结束时间"
            onChange={(e)=>this.onSelectedChange(e,'end')}
            onOk={this.onEndTime}
            allowClear
          />
        </div>
        <div className='confirm-select'>
          <Button type='primary' onClick={this.onSearch}>搜索</Button>
        </div>
      </div>
    );
  }
}

QueryPanel.propTypes = {
  setSearchDeviceParam: PropTypes.func,
  setSearchCapacityParam: PropTypes.func,
  setEndTimeParam: PropTypes.func,
  setStartTimeParam: PropTypes.func,
  setEmptyParam: PropTypes.func,
  getHistoryData: PropTypes.func
};

export default QueryPanel;
