import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withSubscribeMQTT, parseMessage, MQTTProvider } from 'amos-mqtt';
import { Modal, briskWarningTip } from 'amos-designer';
import ExecuteProgressContent from './ExecuteProgressContent';

/**
 * 执行进度
 * @class ExecuteProgress
 * @extends {ExecuteProgress}
 */
class ExecuteProgress extends Component {
  constructor(props) {
    super(props);
    this.state = {
      content: null,
      data: {}
    };
  }

  componentDidMount() {
    this.initMqttTopic();
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.props.exeId !== prevProps.exeId) {
      this.initMqttTopic();
    }
  }

  initMqttTopic = () => {
    const { exeId } = this.props;
    if (exeId) {
      const content = withSubscribeMQTT({
        topic: `/topicTable/solidify/${exeId.indexOf(',') !== -1 ? exeId.split(',')[0] : exeId}`,
        dispatch: (_topic, message, packet) => {
          const newMsg = parseMessage(message);
          this.setState({ data: { message: newMsg, messageFlag: Date.now() } });
        }
      })(ExecuteProgressContent);
      this.setState({ content });
    }
  }

  cancel = () => {
    const { data } = this.state;
    if (!data.message || data.message.status === 'running') {

    }
    this.props.onClose && this.props.onClose();
  }

  render() {
    const { visible, mqttUrl } = this.props;
    const { data, content: Content } = this.state;
    if (!Content) {
      return null;
    }
    return (
      <MQTTProvider url={mqttUrl || '/mqtt'}>
        <Modal
          header="立即执行进度"
          visible={visible}
          width={474}
          noDefaultFooter
          showMax
          onCancel={this.cancel}
          outterClosable={false}
          content={
            <Content message={data.message} messageFlag={data.messageFlag} />
          }
        />
      </MQTTProvider>
    );
  }
}

ExecuteProgress.propTypes = {
  visible: PropTypes.bool,
  onClose: PropTypes.func,
  exeId: PropTypes.string,
  mqttUrl: PropTypes.string
};

export default ExecuteProgress;
