<template>
  <div id="draw-view">
    <Spin :spinning="loading" tip="资源加载中..."></Spin>
    <div v-if="!loading" class="draw-view" ref="xmlContainer"></div>
  </div>
</template>

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

export default defineComponent({
  name: 'draw-view',
  components: { Spin },
  props: {
    value: { type: String, default: XML_DATA },
  },
  setup(props) {
    const { value } = { ...props };
    const loading = ref(true);
    const xmlExample = ref(value);
    const xmlContainer = ref<HTMLDivElement | null>(null);

    watch(xmlExample, () => convertXML());

    onMounted(() => {
      diagramLoader().then(() => {
        setTimeout(() => {
          loading.value = false;
          nextTick(() => convertXML());
        }, 400);
      });
    });
    // 显示图像
    const convertXML = (xml: string = xmlExample.value) => {
      const div = xmlContainer.value;
      if (div) {
        diagramLoader().then(diagram => {
          const diagramViewer = new diagram.DiagramViewer(stringToXml(xml));
          const svg = diagramViewer.renderSVG(null, 1, 1);
          svg && div.appendChild(svg);
        });
      }
    };

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

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