import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Tabs, Button } from 'amos-antd';
import Icon from 'amos-icon';
import { OltSerUrl,onlineTestWsURL } from '../../../consts/urlConsts';
import { AmosFetch } from '../../../utils/processor';
import { PubSub } from 'ray-eventpool';
import { getToken } from '../../../utils/request';
import AmosWebSocket from 'amos-websocket';
import { CONFIG_PANEL_HIDE_TOPIC } from './../common/ActionConf';

import ConnectTest from './ConnectTest';
import './onlineTest.scss';
import PerformanceTest from './PerformanceTest';

const TabPane = Tabs.TabPane;

/**
 * 在线测试
 *
 * @class AddDeviceCard
 * @extends {Component}
 */
class OnlineTest extends Component {
  constructor(props) {
    super(props);
    this.state = {
      quotaSelecteList: [],
      collapsed: false,
      connectData: {},
      connectPercent: 0,
      metricPercent: 0
    };
    const token = getToken();
    this.websocketUrl = `${onlineTestWsURL}test-equipment.ws?token=${token}`;
  }

  componentDidMount(){
    this.getProInfo();
  }

  componentWillReceiveProps(nextProps) {
    let { quotaSelected } = this.props;
    if (nextProps.quotaSelected !== quotaSelected ) {
      this.getProInfo();
    }
  }

  getProInfo = () =>{
    let { quotaSelected } = this.props;
    if (JSON.stringify(quotaSelected) !== '{}'){
      let idArr = [];
      for (let key in quotaSelected){
        if (quotaSelected[key].length > 0){
          idArr.push(quotaSelected[key]);
        }
      }
      let url = `${OltSerUrl.quotaSelecteds}/${idArr}`;
      AmosFetch.get(url).then(res => {
        if (res.ok) {
          return res.json();
        }
        else
        {
          throw new Error('从服务端获取数据失败！');
        }
      }).then((data)=>{
        if (data.result === 'SUCCESS'){
          this.setState({
            quotaSelecteList: data.dataList
          });
        }
      });
    } else {
      this.setState({
        quotaSelecteList: []
      });
    }
  }

  callback=(key)=> {
    console.log(key);
  }

  closeQuotaPanel = () => {
    PubSub.publish(CONFIG_PANEL_HIDE_TOPIC.trigger, {});
  }

  //webSocket 接收消息
  handleData = (param) => {
    console.log('我应该链接测试数据：');
    console.log(param);
    if (param.connectData){
      this.getConnectNeeddata(param);
    } else if (param.metricData){
      this.getMetricNeeddata(param);
    }
  }

  getConnectNeeddata=(param)=>{
    let id = param.connectData.id;
    let connectData = this.state.connectData;
    connectData[id] = param.connectData.result;
    this.setState({ connectData,connectPercent: param.connectData.percent });
  }

  getMetricNeeddata=(param)=>{
    let quotaSelecteList = this.state.quotaSelecteList;
    quotaSelecteList.map((data)=>{
      let newAttribute = param.metricData.attributes;
      newAttribute.map((obj)=>{
        let attrId = obj.id;
        if (attrId === data.id){
          data.value = obj.value;
        }
      });
    });
    this.setState({ quotaSelecteList,metricPercent: param.metricData.percent });
  }

  //webSocket 发送消息
  send = () => {
    // const ws = this.aws.getWebSocket();
    // ws.send(JSON.stringify());
  }

  render() {
    let list = [];
    list.push(<Button type="primary" style={{ marginRight: '10px',marginTop: '7px' }} size="small" onClick={this.closeQuotaPanel} >关闭</Button>);
    
    return (
      <div className='online-test-custom' >
        <div className="dispatch-mask" ref={node => this.dispatchMask = node}>
          <AmosWebSocket
            ref={node => this.aws = node}
            url={this.websocketUrl}
            onMessage={this.handleData}
            onOpen={this.send}
            reconnect
            debug
          />
        </div>
        <div>
          <Tabs defaultActiveKey="1" onChange={this.callback} tabBarExtraContent={list}>
            <TabPane tab="连接测试" key="1">
              <ConnectTest  connectData={this.state.connectData} percent={this.state.connectPercent} {...this.props} />
            </TabPane>
            <TabPane tab="性能测试" key="2">
              <PerformanceTest  quotaSelecteList={this.state.quotaSelecteList} percent={this.state.metricPercent} {...this.props} />
            </TabPane>
          </Tabs>
        </div>
      </div>
    );
  }
}

OnlineTest.propTypes = {
  visible: PropTypes.any,
  quotaSelected: PropTypes.any,
  onlinTestSwich: PropTypes.func,
  quotaSelecteList: PropTypes.any
};

export default OnlineTest;
