import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Progress } from 'amos-framework';

/**
 * 立即执行进度
 * @class ExecuteProgressContent
 * @extends {ExecuteProgress}
 */
class ExecuteProgressContent extends Component {                                                                                   
  constructor(props) {
    super(props);
    this.state = {
      percent: 0,
      status: 'running',
      flag: false,
      logs: []
    };
  }

  componentDidMount() {
    this.onMessage();
  }

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

  onMessage = () => {
    const { message } = this.props;
    const { status, percent } = message || {};
    if (status) {
      const { logs } = this.state;
      logs.push(message);
      this.setState({ logs, percent, status }, () => {
        this.scrollToBottom();
      });
    }
  }

  scrollToBottom = () => {
    if (this.content && this.content.scrollHeight > this.content.clientHeight) {
      const state = 10;
      if (this.content.scrollHeight - this.content.clientHeight > state) {
        this.content.scrollTop = this.content.scrollHeight - this.content.clientHeight;
      }
    }
  }

  render() {
    const { logs, status, percent } = this.state;
    return (
      <div className="ig-execute-progress">
        <Progress percent={percent} strokeWidth={16} status={status === 'error' ? 'exception' : status === 'finished' ? undefined : 'active'} />
        <div className="ig-execute-progress-switch">进度详情</div>
        <div className="ig-execute-progress-content" ref={node => this.content = node}>
          <ul>
            {
              logs.map((e, index) => (
                <li key={index} style={{ color: e.status === 'error' ? 'red' : '' }}>[{e.time}] {e.logInfo}{e.detail}</li>
              ))
            }
          </ul>
        </div>
      </div>
    );
  }
}

ExecuteProgressContent.propTypes = {
  messageFlag: PropTypes.number,
  message: PropTypes.object
};

export default ExecuteProgressContent;
