import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { TableList, ScreenCard, withSubscribeMQTT } from './../../common';

import {
  iotEquipmentListAction
} from './../api';

/**
 * 站端物联监控
 * @class IotEquipment
 * @extends {Component}
 */
@withSubscribeMQTT({ topic: 'alertNotice' })
class IotEquipment extends Component {
  constructor(props) {
    super(props);
    this.state = {
      iotEquipmentData: [],
      stationName: ''
    };
  }

  componentDidMount() {
    this.onRequest();
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.props.messageFlag !== prevProps.messageFlag) {
      this.onRequest();
    }
  }

  onRequest = () => {
    const { stationName } = this.state;
    iotEquipmentListAction(stationName).then(d => {
      this.setState({ iotEquipmentData: d || [] });
    });
  }

  /**
   * 根据换流站名称搜索
   * @param {*} searchValue 换流站名称
   */
  iotEquipmentSearch = (searchValue) => {
    this.setState({
      stationName: searchValue,
      iotEquipmentData: []
    }, this.onRequest);
  }

  IotEquipmentColumns = () => {
    return [
      { dataIndex: 'name', title: '站名' },
      { dataIndex: 'iotEquipmentNumber', title: '物联设备' },
      { dataIndex: 'todayAlarmEquipmentNumber', title: '告警设备', render: (text, record) => <p style={{ color: text === '0' ? '#49AA19' : '#D32029' }}>{text}</p> }
    ];
  }

  render() {
    const { iotEquipmentData } = this.state;
    return (
      <ScreenCard title="站端物联设备" showSearch onSearch={this.iotEquipmentSearch}>
        <TableList
          columns={this.IotEquipmentColumns()}
          rowKey="id"
          dataSource={iotEquipmentData}
        />
      </ScreenCard>
    );
  }
}

IotEquipment.propTypes = {
  messageFlag: PropTypes.number
};

export default IotEquipment;
