import * as React from 'react';
import { PlumbEleNode, placement } from 'amos-jsplumb';
import { PubSub } from 'ray-eventpool';
import classNames from 'classnames';
import { DB_CLICK_ELE, completeItemTypeIcon } from './../../modelConf/stageConst';
import { sourceEndPoint, targetEndpoint } from './../../modelConf/nodeConf';
import ElementEditor from './ElementEditor';

const DefaultNode = PlumbEleNode.DefaultNode;
const { Anchors } = placement;

/**
 * 告警节点
 *
 * @class DataNodeEle
 * @extends {DefaultNode}
 */
export default function(options) {
  const { type, nodeIcon } = options;
  const bgImg = completeItemTypeIcon(nodeIcon);
  return class DataNodeEle extends DefaultNode {
    constructor(props) {
      super(props);
      this.state = {
        active: false
      };
    }

    componentDidMount() {
      const { id, initNode } = this.props;

      const initConfig = {
        endPointParams: [
          {
            element: this.container,
            params: sourceEndPoint,
            referenceParams: {
              anchor: Anchors.RightMiddle,
              uuid: `obj-ep-${Anchors.RightMiddle}-${id}`
            }
          },
          {
            element: this.container,
            params: targetEndpoint,
            referenceParams: {
              anchor: Anchors.LeftMiddle,
              uuid: `obj-ep-${Anchors.LeftMiddle}-${id}`
            }
          }
        ],
        makeTargetParams: {
          allowLoopback: false,
          // left
          anchor: Anchors.ContinuousLeft,
          dropOptions: { hoverClass: 'drag-hover' },
          isTarget: true
        },
        makeSourceParams: {
          filter: '.ele-source-bar',
          allowLoopback: false,
          anchor: Anchors.Right,
          dropOptions: { hoverClass: 'drag-hover' }
        },
        nodeId: id
      };
      initNode(initConfig);
    }

    dbClickTrigger = ({ id, config, parentConfig }) => {
      //
      PubSub.publish(DB_CLICK_ELE, {
        id,
        config,
        parentConfig,
        type
      });
    };

    render() {
      const { active } = this.state;
      const { id, config, parentConfig } = this.props;
      const { style, label } = config;

      const cls = classNames({
        'node-wrapper': true,
        'node-wrapper-active': active
      });

      const wrapperCls = classNames('fire-node-ele', nodeIcon);
      const newStyle = {
        ...style,
        background: `url("${bgImg}") no-repeat`
      };

      return (
        <div
          id={id}
          className={wrapperCls}
          style={newStyle}
          ref={node => (this.container = node)}
          onDoubleClick={() => this.dbClickTrigger({ id, config, parentConfig })}
        >
          <div className={cls}>
            <div className="ele-node-content">
              <ElementEditor label={label} eleId={id} />
            </div>
          </div>
        </div>
      );
    }
  };
}
