import React, { Component } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import { Popover } from 'amos-framework';
import { TableList, ScreenCard, withSubscribeMQTT } from './../../common';
import { AlarmColorEnum } from './../../config';
import {
  signalEquipmentTop50Action
} from './../api';

/**
 * 警情动态
 * @class AlarmDynamic
 * @extends {Component}
 */
@withSubscribeMQTT({ topic: 'meteorological' })
class AlarmDynamic extends Component {
  constructor(props) {
    super(props);
    this.state = {
      alarmDynamicData: []
    };
  }

  componentDidMount() {
    this.onRequest();
  }

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

  onRequest = () => {
    signalEquipmentTop50Action().then(d => {
      this.setState({ alarmDynamicData: d || [] });
    });
  }

  textColor = (text, record) => {
    let color = 'white';
    AlarmColorEnum.getValues().forEach(item => {
      if (record.signalType === item.code) {
        color = item.color;
      }
    });
    return (
      <p style={{ color }}>{text}</p>
    );
  }

  AlarmDynamicColumns = () => {
    return [
      { dataIndex: 'signalTypeName', title: '类型', render: (text, record) => this.textColor(text, record) },
      { dataIndex: 'location', title: '告警内容',
        render: (text,record) =>
          <Popover content={`${record.fireEquipmentName}${record.signalTypeName}`} direction="down">
            <div className="ccs-comtablelist-longtext">{`${record.fireEquipmentName}${record.signalTypeName}`}</div>
          </Popover> },
      { dataIndex: 'createDate', title: '时间' , render: (text) => text && moment(text, 'YYYY-MM-DD HH:mm:ss').format('HH:mm:ss') }
    ];
  }

  render() {
    const { alarmDynamicData } = this.state;
    return (
      <ScreenCard title="警情动态">
        <TableList
          columns={this.AlarmDynamicColumns()}
          rowKey="id"
          dataSource={alarmDynamicData} />
      </ScreenCard>
    );
  }
}

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

export default AlarmDynamic;
