<script lang="ts" setup>
import { ref } from 'vue';
import Postmate from 'postmate';
import { Engine, widgetManager } from '@vtj/pro';
import { request, jsonp } from '@vtj/utils';
import { useUserStore } from '@/store';
import { LowCodeService } from '@/service';

const container = ref();
const service = new LowCodeService();
const userStore = useUserStore();

onMounted(async () => {
  // 数据模型
  const model = {
    name: '',
    url: '',
    applicationId: -1,
    projectId: -1,
    accessToken: ''
  };

  const handshake = new Postmate.Model({});
  await handshake.then((parent) => {
    parent.emit('sync-context', 'y-code-designer is ready');
    Object.assign(model, parent.model);
    // console.log('get parent model', model);
    userStore.setToken(model.accessToken);
    request.useRequest((req) => {
      req.headers.set('Authorization', `Bearer ${model.accessToken}`);
      return req;
    });
    const engine = new Engine({
      container,
      service,
      project: {
        // @ts-ignore
        id: model.projectId,
        name: model.name
      },
      adapter: {
        request,
        jsonp
      }
    });
    widgetManager.set('Previewer', {
      props: {
        path: (block: any) => {
          const pathname = location.pathname;
          return `${pathname}#/preview/${block.id}`;
        }
      }
    });

    widgetManager.set('Templates', {
      invisible: true
    });
  });
});
</script>

<template>
  <div
    class="designer-container"
    ref="container"
    :token="userStore.token"></div>
</template>

<style scoped>
.designer-container {
  height: 100%;
  width: 100%;
}
</style>
