<template>
  <div class="preview" :style="{ background: bgColor }">
    <div class="meta2d-canvas" ref="meta2dDom"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted } from 'vue';
import localforage from 'localforage';
import { localStorageName } from '@/services/utils';
import { defaultFormat } from '@/services/defaults';
import { useRouter, useRoute } from 'vue-router';
import { Meta2d, Options, Pen } from '@meta2d/core';
import { registerBasicDiagram } from '@/services/register';
import { cdn, getLe5leV } from '@/services/api';
const route = useRoute();

const meta2dDom = ref('');

const meta2dOptions: Options = {
  cdn,
  background: '#1e2430',
  x: 10,
  y: 10,
  width: 1920,
  color: '#bdc7db',
  height: 1080,
  defaultFormat: { ...defaultFormat },
};

const bgColor = ref('#1e2430');

onMounted(() => {
  meta2d = new Meta2d(meta2dDom.value, meta2dOptions);
  registerBasicDiagram();
  open();
  meta2d.on('opened', opened);
  window.addEventListener('message', function (e) {
    if (typeof e.data !== 'string') {
      return;
    }
    try {
      let data = JSON.parse(e.data);
      if (typeof data === 'object') {
        meta2d.emit(data.name);
      } else {
        meta2d.emit(data);
      }
    } catch (e) {
      console.info(e);
    }
  });
});

const watcher = watch(
  () => route.query.id,
  async () => {
    open();
  }
);

const open = async () => {
  if (route.query.id) {
    const ret: any = await getLe5leV(route.query.id + '');
    ret && meta2d.open(ret);
  } else {
    let data: any = await localforage.getItem(localStorageName);
    if (data) {
      data = JSON.parse(data);
      data.locked = 1;
      data.rule = false;
      meta2d.open(data);
      bgColor.value = data.background;
    }
  }
};

const opened = () => {
  let fit: any =
    (meta2d.store.data as any).scaleMode === '3'
      ? 'height'
      : (meta2d.store.data as any).scaleMode === '2'
      ? 'width'
      : true;
  meta2d.fitSizeView(fit, 10);
  meta2d.setOptions({
    scroll: (meta2d.store.data as any).scroll,
    disableScale: (meta2d.store.data as any).isDisableScale,
    disableTranslate: (meta2d.store.data as any).isDisableTranslate,
  });
};

onUnmounted(() => {
  watcher();
  if (meta2d) {
    meta2d.off('opened', opened);

    meta2d.destroy();
  }
});
</script>
<style lang="postcss" scoped>
.preview {
  width: 100vw;
  height: 100vh;
  /* background-color: var(--color-background-editor); */
  .meta2d-canvas {
    width: 100%;
    height: 100%;
  }
}
</style>
