<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,getComponents } from '@/services/api';
import { getDownloadList, getPayList,getFrameDownloadList, Frame} from '@/services/download';
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();
  //js线性图元
  if (globalThis.meta2dTools?.length !== globalThis.jsDiagramNum) {
    let jsLoadInterval = setInterval(() => {
      if (globalThis.meta2dTools?.length == globalThis.jsDiagramNum) {
        if (globalThis.registerToolsNew) {
            globalThis.registerToolsNew();
        }
        clearInterval(jsLoadInterval);
      }
    }, 500);
  } else {
    if (globalThis.registerToolsNew) {
      globalThis.registerToolsNew();
    }
  }
  open();
  meta2d.on('opened', opened);
  window.addEventListener('message', dealWithMessage);
  window.addEventListener('resize', viewResize);
});

let timer:any;
const viewResize = ()=>{
  clearTimeout(timer);
  timer = setTimeout(()=>{
    let fit: any =
    (meta2d.store.data as any).scaleMode === '3'
      ? 'height'
      : (meta2d.store.data as any).scaleMode === '2'
      ? 'width'
      : true;
    meta2d.fitSizeView(fit, 0);
  },500);
}

const dealWithMessage = (e) => {
  if (typeof e.data !== 'string'||!e.data ||
    e.data.startsWith('setImmediate')) {
    return;
  }
  try {
    let data = JSON.parse(e.data);
    if (typeof data === 'object') {
      if (data.type) {
        if (data.name === 'downloadHtml') {
          //处理下载
           doDownload(data.path);
        } else if (data.name === 'prePayList') {
          doGetPayList();
        } else if (data.name === 'downloadVue3') {
          doGetFrameDownload(Frame.vue3,data.path);
        } else if (data.name === 'downloadVue2') {
          doGetFrameDownload(Frame.vue2,data.path);
        } else if (data.name === 'downloadReact') {
          doGetFrameDownload(Frame.react,data.path);
        }
      } else {
        // 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 + '');
    let ret: any;
    if (route.query.c) {
      ret = await getComponents(route.query.id + '');
    } else {
      ret = await getLe5leV(route.query.id + '',undefined , route.query.historyId as string);
    }
    if(ret && ret.data){
      if(!ret.data.background){
        ret.data.background = '#1e2430';
      }
      if(!ret.data.color){
        ret.data.color = '#bdc7db';
      }
      ret.data.locked = 1;
      if(!ret.data.width){ret.data.width= 1920};
      if(!ret.data.height){ret.data.height= 1080};
      meta2d.open(ret.data);
    }
  } else {
    let data: any = await localforage.getItem(localStorageName);
    if (data) {
      data = JSON.parse(data);
      data.locked = 1;
      data.rule = false;
      if(!data.background){
        data.background = '#1e2430';
      }
      if(!data.color){
        data.color = '#bdc7db';
      }
      if(!data.width){data.width= 1920};
      if(!data.height){data.height= 1080};
      meta2d.open(data);
      bgColor.value = data.background;
    }
  }
};

const opened = () => {
  meta2d.store.options.shadowColor = '#0000'
  meta2d.canvas.parentElement.style.background = meta2d.store.data.background|| meta2d.store.theme[meta2d.store.data.theme].background;
  let fit: any =
    (meta2d.store.data as any).scaleMode === '3'
      ? 'height'
      : (meta2d.store.data as any).scaleMode === '2'
      ? 'width'
      : true;
  meta2d.fitSizeView(fit, 0);
  meta2d.setOptions({
    scroll: (meta2d.store.data as any).scroll,
    disableScale: (meta2d.store.data as any).isDisableScale,
    disableTranslate: (meta2d.store.data as any).isDisableTranslate,
  });
};

//获取下载列表
const doDownload =async (path: string) => {
  const list = getDownloadList(meta2d.data(), path);
  window.parent.postMessage(
    JSON.stringify({
      name: 'download',
      data: [...list],
      type: 1,
    }),
    '*'
  );
};

//获取框架下载列表
const doGetFrameDownload = (frame: Frame,path:string) => {
  const list = getFrameDownloadList(meta2d.data(),path, frame);
  window.parent.postMessage(
    JSON.stringify({
      name: 'download',
      data: [...list],
      type: 1,
    }),
    '*'
  );
};

//获取付费图元列表
const doGetPayList = () => {
  const list = getPayList(meta2d.data());
  window.parent.postMessage(
    JSON.stringify({
      name: 'payList',
      data: list,
      type: 1,
    }),
    '*'
  );
};

onUnmounted(() => {
  watcher();
  if (meta2d) {
    meta2d.off('opened', opened);
    meta2d.destroy();
  }
  window.removeEventListener('message', dealWithMessage);
  window.removeEventListener('resize', viewResize);
});
</script>
<style lang="postcss" scoped>
.preview {
  width: 100vw;
  height: 100vh;

  /* background-color: var(--color-background-editor); */
  .meta2d-canvas {
    width: 100%;
    height: 100%;
  }
}
</style>
