<template>
  <div id="draw-edit">
    <div v-if="loading">资源加载中...</div>
  </div>
</template>

<script lang="ts">
import 'embed-drawio/dist/index.css';
import { defineComponent, onMounted, ref, PropType } from 'vue';
import { XML_DATA } from './constant';
import { stringToXml, xmlToString } from './utils';
import { diagramLoader } from './diagram-loader';

export default defineComponent({
  name: 'draw-edit',
  components: {},
  props: {
    value: { type: String, default: XML_DATA },
    change: {
      type: Function as PropType<(val: string) => void>,
      default: null,
    },
  },
  setup(props) {
    const { value, change } = { ...props };
    let diagramEditor: any = null;
    const loading = ref(true);
    const xmlExample = ref(value);

    onMounted(() => {
      diagramLoader().then(diagram => {
        setTimeout(() => {
          loading.value = false;
          editXML();
        }, 400);
      });
    });
    // 在线编辑
    const editXML = () => {
      diagramLoader().then(diagram => {
        const renderExit = (el: HTMLDivElement) => {
          const div = document.createElement('div');
          div.innerText = '保存';
          div.style.marginRight = '20px';
          div.onclick = diagramEditorExit;
          el.appendChild(div);
        };
        const draw = document.body as HTMLDivElement;
        diagramEditor = new diagram.DiagramEditor(draw, renderExit);
        diagram.getLanguage('zh').then(res => {
          diagramEditor.start(res, stringToXml(xmlExample.value), (xml: Node) => {
            const xmlString = xmlToString(xml);
            xmlExample.value = xmlString || '';
          });
        });
      });
    };

    const diagramEditorExit = () => {
      if (diagramEditor) {
        diagramEditor.exit();
      }

      change && change(xmlExample.value);
    };

    return {
      loading,
      xmlExample,
    };
  },
});
</script>

<style lang="less" scoped></style>
