import React from 'react';
import ReactDOM from 'react-dom';
import { Button } from 'antd';
import BpmnViewer from 'bpmn-js';
import moveCanvas from 'diagram-js/lib/navigation/movecanvas';
// import zoomScroll from 'diagram-js/lib/navigation/zoomscroll'
import styles from './BpmDiagram.less';
import * as bpmService from '../../services/common/bpm';
import * as R from 'ramda';

class BpmDiagram extends React.Component {
  componentWillMount = () => {
    this.fetchData();
  };
  handleZoomIn = (viewer, t) => {
    const { zLevel, zStep } = this.state;
    const level = Math.min(zLevel + zStep, 2);
    this.setState({
      zLevel: level,
    });
    viewer.get('canvas').zoom(level, 'auto');
  };
  handleZoomOut = (viewer) => {
    const { zLevel, zStep } = this.state;
    const level = Math.max(zLevel - zStep, zStep);
    this.setState({
      zLevel: level,
    });
    viewer.get('canvas').zoom(level, 'auto');
  };
  handleZoomReset = (viewer) => {
    viewer.get('canvas').zoom('fit-viewport');
  };
  paintAssignees = (viewer, prcId) => {
    bpmService.getAssignees(prcId).then((data) => {
      if (data.success) {
        const overlays = viewer.get('overlays');
        data.data.forEach((task) => {
          overlays.add(task.taskKey, {
            position: {
              top: 3,
              left: 25,
            },
            // html: task.assigneeName || task.candidateNames,
          });
        });
      } else {
        throw data;
      }
    });
  };
  paintTrace = (viewer, acts) => {
    const ageNameSort = R.sortWith([
      // R.compose(R.toLower, R.prop('taskKey')),
      R.ascend(R.prop('taskKey')),
      R.descend(R.prop('id'))
    ]);
    let latest = ageNameSort(R.filter((el) => el.result !== 'NOTIFIED', acts));
    // console.log(latest);
    latest = R.uniqWith((a, b) => {
      return a.taskKey === b.taskKey;
    })(latest);

    // console.log(latest);

    const canvas = viewer.get('canvas');
    // const overlays = viewer.get('overlays')
    latest.forEach((act) => {
      // overlays.add(act.taskKey, {
      //   position: {
      //     top: 3,
      //     left: 25,
      //   },
      // html: act.assigneeName,
      // })

      if (act.result === 'APPROVED') {
        canvas.addMarker(act.taskKey, 'passed');
      } else if (act.result === 'REJECTED') {
        canvas.addMarker(act.taskKey, 'reject');
      } else if (act.result === 'SUBMITTED') {
        canvas.addMarker(act.taskKey, 'submit');
      } else if (act.result === 'CONTINUED') {
        canvas.addMarker(act.taskKey, 'coutine');
      } else if (act.result === 'DISABLED') {
        canvas.addMarker(act.taskKey, 'disable');
      } else if (!act.result) {
        canvas.addMarker(act.taskKey, 'active');
      }
    });
  };
  renderDiagram = (containerDOM, xml, acts, instance) => {
    const viewer = new BpmnViewer({
      container: containerDOM,
      additionalModules: [
        // zoomScroll,
        moveCanvas,
      ],
      height: this.props.height || 300,
    });

    viewer.importXML(xml, (err) => {
      if (err) {
        console.log('[BPMN] error rendering', err);
        throw err;
      } else {
        viewer.get('canvas').zoom('fit-viewport');
        // viewer.get('canvas').zoom(0.7, 'auto')
        const eventBus = viewer.get('eventBus');

        // update our zoom level on viewbox change
        eventBus.on('canvas.viewbox.changed', (evt) => {
          this.setState({
            zLevel: evt.viewbox.scale,
          });
        });

        const navigator = document.createElement('div');
        navigator.setAttribute('id', 'navigator');

        // console.log(viewer);

        viewer._container.appendChild(navigator);

        ReactDOM.render(<div className={styles.navigator}>
          <Button key="zoomIn" icon="plus" onClick={this.handleZoomIn.bind(this, viewer)}/>
          <Button key="zoomOut" icon="minus" onClick={this.handleZoomOut.bind(this, viewer)}/>
          <Button key="zoomReset" icon="scan" onClick={this.handleZoomReset.bind(this, viewer)}/>
        </div>, document.getElementById('navigator'));

        this.paintTrace(viewer, acts);
        // this.paintAssignees(viewer, instance);
        // viewer._container.removeChild(viewer._container.firstChild); // Remove logo

        return viewer;
      }
    });
  };
  fetchData = () => {
    const { def, instance } = this.props;

    // console.log(def, instance);

    if (!def || !instance) {
      return '未查到流程信息';
    }

    this.setState({ fetching: true });

    bpmService.getDiagram(def).then((data) => {
      if (data.success) {
        const xml = data.data;
        bpmService.getTrace(instance).then((data2) => {
          if (data2.success) {
            let events = data2.data;
            if (events.filter(e => e.endTime === null).length && events.length) {
              const tail = events.slice(events.length - 1);
              const head = events.slice(0, events.length - 1);
              events = tail.concat(head);
            }

            this.renderDiagram(this.canvas, xml, events, instance);
            this.setState({
              fetching: false,
            });
          } else {
            throw data2.message;
          }
        });
      } else {
        throw data;
        ;
      }
    });
  };

  constructor(props) {
    super(props);

    this.state = {
      fetching: false,
      zLevel: 1,
      zStep: 0.2,
    };
  }

  render() {
    return (
      <div>
        <div ref={node => this.canvas = node}/>
      </div>
    );
  }
}

BpmDiagram.propTypes = {};

export default BpmDiagram;
