<script lang="ts" setup>
import { ref } from 'vue';

import { LowCodeService } from '@/service';
import { useUserStore } from '@/store';
import { Engine, widgetManager } from '@vtj/pro';
import { jsonp, request } from '@vtj/utils';
import Postmate from 'postmate';

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);
    localStorage.setItem('y-code-access-token', model.accessToken);
    // request.useRequest((req) => {
    //   req.headers.set('Authorization', `Bearer ${model.accessToken}`);
    //   return req;
    // });
    sessionStorage.setItem('projectId', model.projectId);
    const _engine = new Engine({
      container,
      service,
      window,
      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
    });

    widgetManager.set('About', {
      invisible: true
    });

    widgetManager.set('History', {
      // 有 bug，先隐藏
      invisible: true
    });
  });
});
</script>

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

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