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 {
  newestDanger50Action
} from './../api';

/**
 * 最新隐患
 * @class NewestDanger
 * @extends {Component}
 */
@withSubscribeMQTT({ topic: 'meteorological' })
class NewestDanger extends Component {
  constructor(props) {
    super(props);
    this.state = {
      newestDangerData: []
    };
  }

  componentDidMount() {
    this.onRequest();
  }

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

  onRequest = () => {
    newestDanger50Action('50').then(d => {
      this.setState({ newestDangerData: d || [] });
    });
  }

  textColor = (text, record) => {
    let color = 'white';
    if (record.dangerLevel === '1') {
      color = '#D87A16';
    } else if (record.dangerLevel === '2') {
      color = '#D32029';
    } else if (record.dangerLevel === '0') {
      color = '#E8D639';
    }
    return (
      <p style={{ color }}>{text}</p>
    );
  }

  NewestDangerColumns = () => {
    return [
      { dataIndex: 'dangerLevelName', title: '级别', width: '20%', render: (text, record) => this.textColor(text, record) },
      { dataIndex: 'dangerName', title: '隐患名称' , render: (text) =>
        <Popover content={text} direction="down"> <div className="ccs-security-longtext">{text}</div></Popover> },
      { dataIndex: 'dangerStateName', width: '20%', title: '进度' },
      { dataIndex: 'discoveryDate', title: '时间', width: '20%' , render: (text) => text && moment(text, 'YYYY-MM-DD HH:mm:ss').format('HH:mm:ss') }
    ];
  }

  render() {
    const { newestDangerData } = this.state;
    return (
      <ScreenCard title="最新隐患">
        <TableList
          columns={this.NewestDangerColumns()}
          rowKey="id"
          dataSource={newestDangerData} />
      </ScreenCard>
    );
  }
}

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

export default NewestDanger;
