import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { AmosFetch } from '../../../utils/processor';
import { OltSerUrl,realTimeMetricWsURL } from '../../../consts/urlConsts';
import Icon from 'amos-icon';
import { Badge,Popover,Notification } from 'amos-antd';
import AmosWebSocket from 'amos-websocket';
import { getToken } from '../../../utils/request';
// import { currentUser } from 'amos-security/lib/model/auth';
import AlarmList from './AlarmList';


class AlarmTools extends Component {

  static propTypes = {
    showText: PropTypes.bool
  };

  static defaultProps = {
  };

  constructor(props) {
    super(props);
    this.state = {
      total: 0,
      visible: false
    };
    const token = getToken();
    this.websocketUrl = `${realTimeMetricWsURL}alarm.ws?token=${token}`;
  }

  componentWillMount() {

  }

  componentDidMount(){
    this.getAlarmMessageCount();
  }

  getAlarmMessageCount = () =>{
    let list = [];
    list.push({ name: 'status',type: 'EQUAL',value: 1 });
    list.push({ name: 'raiseTime',type: 'ORDER BY',value: 'DESC' });
    let url = `${OltSerUrl.getHistoryAlarm}?pageNumber=0&pageSize=10`;
    AmosFetch.post(url,{ data: list }).then(res => {
      if (res.ok) {
        return res.json();
      } else
      {
        throw new Error('从服务端获取数据失败！');
      }
    }).then((data)=>{
      if (data.result === 'SUCCESS'){
        let total = data.dataList.totalElements;
        if (data.content !== null){
          // this.setState({ dataList: data.dataList.content,total,orgCode: data.dataList.content[0].orgCode });
        }
      } else {
        this.setState({ dataList: [],total: 0 });
      }
    });
  }

  //webSocket 接收消息
  handleData = (param) => {
    console.log('我应该是告警信息：');
    console.log(param);

    let user = currentUser();
    let orgCode = user.company.compCode;
    console.log(`orgCode=${orgCode}`);
    // let orgCode = this.state.orgCode;
    if (param.orgCode === orgCode){
      let { name,descr } = param;
      Notification.open({
        message: `设备：${name}`,
        description: `${name}${descr}`
      });
      this.getAlarmMessageCount();
    }
  }

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

  hide = () => {
    this.setState({
      visible: false
    });
  }
  handleVisibleChange = (visible) => {
    this.getAlarmMessageCount();
    this.setState({ visible });
  }

  render() {
    let { total,dataList } = this.state;
    return (
      <Popover
        title='告警消息列表'
        trigger="click"
        content={<AlarmList dataList={dataList} onHide={this.hide} getAlarmMessageCount={this.getAlarmMessageCount} />}
        visible={this.state.visible}
        onVisibleChange={this.handleVisibleChange}
      >
        <div className="dispatch-mask" ref={node => this.dispatchMask = node}>
          <AmosWebSocket
            ref={node => this.aws = node}
            url={this.websocketUrl}
            onMessage={this.handleData}
            reconnect
            debug
          />
        </div>
        <div className="alarm-logo-css" >
          <Badge count={total} overflowCount={99} >
            <Icon icon='xiaoxi2' />
          </Badge>
        </div>
      </Popover>
    );
  }
}

export default AlarmTools;
