import React, { Component } from 'react';
import { Editable, message } from 'amos-framework';
import PropTypes from 'prop-types';
import { PubSub } from 'ray-eventpool';
import { ELE_UPDATE_TOPIC } from './../ruleStatge/modelConf/stageConf';
import { updateNodeLabel } from './../../../services/ruleDesignService';


const textOverFlow = {
  overflow: 'hidden',
  textOverflow: 'ellipsis',
  whiteSpace: 'nowrap',
  display: 'inline-block'
};

const buttonProps = {
  transparent: true,
  size: 'sm',
  style: {
    margin: 0
  }
};

const inputProps = {
  size: 'sm'
};

/**
 *
 * 编辑对象
 * @class ElementEditor
 * @extends {Component}
 */
class ElementEditor extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: this.props.label
    };
  }

  componentDidMount(){
    // 配置页面改动后更新视图上的信息
    this.pubsub_update = PubSub.subscribe(ELE_UPDATE_TOPIC.eleUpdate, (topic,{ label,nodeId }) => {
      if (nodeId === this.props.eleId) {
        this.setState({ value: label });
      }
    });
  }

  componentWillReceiveProps(nextProps) {

  }

  componentWillUnmount() {
    PubSub.unsubscribe(this.pubsub_update);
  }

  saveNodeLabel = (id, displayName, editCallBack) => {
    PubSub.publish(ELE_UPDATE_TOPIC.trigger,{ label: displayName,nodeId: id });
    updateNodeLabel({
      id,
      displayName
    }).then(data => {
      editCallBack && editCallBack(displayName);
      this.setState({ value: displayName });
    },
    err => {
      message.danger(err || '修改节点名称失败！');
    });
  };

  render() {
    const { eleId, editCallBack } = this.props;
    return (
      <Editable
        innerClassName="element-editor"
        value={this.state.value}
        onChange={(value) => this.saveNodeLabel(eleId, value, editCallBack)}
        size="sm"
        editIcon={false}
        buttonProps={buttonProps}
        innerValueStyle={textOverFlow}
        inputProps={inputProps}
        showOkCancel={false}
      />
    );
  }
}

ElementEditor.propTypes = {
  label: PropTypes.string,
  eleId: PropTypes.string,
  editCallBack: PropTypes.func
};

export default ElementEditor;
