<template>
  <div class="my-process-designer">
    <div class="my-process-designer__header">
      <slot name="control-header"></slot>
      <template v-if="!$slots['control-header']">
        <div slot="content">
          <a-space>
            <a-tooltip placement="bottom" class="ml-2" title="缩小视图">
              <a-button :disabled="data.defaultZoom <= 0.3" :icon="h(ZoomOutOutlined)" @click="processZoomOut()">
              </a-button>
            </a-tooltip>
            <a-button>{{ Math.floor(data.defaultZoom * 10 * 10) + "%" }}</a-button>
            <a-tooltip placement="bottom" title="放大视图">
              <a-button :disabled="data.defaultZoom >= 3.9" :icon="h(ZoomInOutlined)" @click="processZoomIn()">
              </a-button>
            </a-tooltip>
          </a-space>
        </div>

      </template>
      <div>
      </div>
    </div>
    <div class="my-process-designer__container">
      <div class="my-process-designer__canvas" ref="bpmn-canvas" id="view"></div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import '@/components/ProcessDesigner/package/theme/index.scss';
  import { h, ref, provide, reactive, onMounted, defineProps, computed, defineEmits, onBeforeMount, watch } from 'vue';
  import { SaveOutlined, ZoomOutOutlined, ZoomInOutlined, RotateLeftOutlined, RotateRightOutlined, ClearOutlined } from '@ant-design/icons-vue';
  import BpmnViewer from 'bpmn-js/lib/Viewer'
  import MoveCanvasModule from 'diagram-js/lib/navigation/movecanvas';
  const data = reactive({
    bpmnModeler: null,
    defaultZoom: 1,
  })

  const props = defineProps({
    xml: String,
    flowViewer:{
      type: Object,
      default: () => ({
        finishedTaskSet: [],
        finishedSequenceFlowSet: [],
        unfinishedTaskSet: [],
        rejectedTaskSet: [],
      })
    }
  })
  watch(
    () => props.xml,
    (newVal, oldVal) => {
      createDiagram(newVal)
    }
  )
  onMounted(() => {
    initBpmnModeler()
    createDiagram(props.xml)
  })
  function initBpmnModeler() {
    if (data.bpmnModerler) return
    const containerEl = document.getElementById('view')
    data.bpmnModerler && data.bpmnModerler.destroy() // 避免缓存
    data.bpmnModerler = new BpmnViewer({
      container: containerEl,
      additionalModules: [
        // 移动整个画布
        MoveCanvasModule
      ],
    })
  }
  async function createDiagram(xml) {
    const viewer = data.bpmnModerler
    if (xml != null && xml !== '') {
      try {
        const result = await data.bpmnModerler.importXML(xml)
        const { warnings } = result
        if (warnings && warnings.length) {
          warnings.forEach(warn => console.warn(warn))
        }
        const canvas = viewer.get('canvas')
        canvas.zoom('fit-viewport')
        addCustomDefs();
      } catch (e) {

      } finally {
        setNodeColor()
      }
    }
  }
  // 添加自定义箭头
  function addCustomDefs() {
    const canvas = data.bpmnModerler.get('canvas');
    const svg = canvas._svg;
    const customSuccessDefs = this.$refs.customSuccessDefs;
    const customFailDefs = this.$refs.customFailDefs;
    svg.appendChild(customSuccessDefs);
    svg.appendChild(customFailDefs);
  }
  // 设置节点颜色
  function setNodeColor() {
    const elementRegistry = data.bpmnModerler.get('elementRegistry')
    let { finishedTaskSet, rejectedTaskSet, unfinishedTaskSet, finishedSequenceFlowSet } = props.flowViewer
    if (Array.isArray(finishedSequenceFlowSet)) {
      finishedSequenceFlowSet.forEach(item => {
        if (elementRegistry._elements[item]) {
          const element = elementRegistry._elements[item].gfx
          element.classList.add('nodeSuccess')
        }
      });
    }
    if (Array.isArray(finishedTaskSet)) {
      finishedTaskSet.forEach((item) => {
        if (elementRegistry._elements[item]) {
          const element = elementRegistry._elements[item].gfx
          element.classList.add('nodeSuccess')
        }
      })
    }
    if (Array.isArray(unfinishedTaskSet)) {
      unfinishedTaskSet.forEach(item => {
        if (elementRegistry._elements[item]) {
          const element = elementRegistry._elements[item].gfx
          element.classList.add('nodeProcing')
        }
      });
    }
    if (Array.isArray(rejectedTaskSet)) {
      rejectedTaskSet.forEach(item => {
        // if (item != null) {
        //   let element = elementRegistry.get(item);
        //   if (element.type.includes('Task')) {
        //     canvas.addMarker(item, 'danger');
        //   } else {
        //     canvas.addMarker(item, 'warning');
        //   }
        // }
      })
    }
  }
  function processZoomIn(zoomStep = 0.1) {
    let newZoom = Math.floor(data.defaultZoom * 100 + zoomStep * 100) / 100;
    if (newZoom > 4) {
      throw new Error("[Process Designer Warn ]: The zoom ratio cannot be greater than 4");
    }
    data.defaultZoom = newZoom;
    data.bpmnModerler.get("canvas").zoom(data.defaultZoom);
  }
  function processZoomOut(zoomStep = 0.1) {
    let newZoom = Math.floor(data.defaultZoom * 100 - zoomStep * 100) / 100;
    if (newZoom < 0.2) {
      throw new Error("[Process Designer Warn ]: The zoom ratio cannot be less than 0.2");
    }
    data.defaultZoom = newZoom;
    data.bpmnModerler.get("canvas").zoom(data.defaultZoom);
  }

  function getOperationTagType(type) {
    return 'success';
  }
  
</script>
<style lang="less" scoped>
  .my-process-designer {
    width: 100%;
  }

  ::v-deep .bjs-container a {
    visibility: hidden;
  }

  .canvas {
    width: 100%;
    height: 100%;

    :global(.nodeSuccess .djs-visual > :nth-child(1)) {
      stroke: #52c41a !important;
      stroke-width: 3px;
    }

    :global(.nodeProcing .djs-visual > :nth-child(1)) {
      stroke: #1890ff !important;
      stroke-width: 3px;
    }
  }
</style>