import { defineComponent, onMounted, reactive, h, createVNode, render } from 'vue';
import VueRenderer from '@crami/lowcode-vue-renderer';
import { Spin } from '@crami/ui';
import './preview.css';
import ModalPage from '../../components/modal-page';
import { useRoute } from 'vue-router';
import { getSchemaById, normalizePageParams } from './helper';
import { previewProps } from './props';
import type { MenuRouteMeta } from 'pro-vip/src/router/typing';

export default defineComponent({
  name: 'editor-preview',
  props: previewProps,
  setup(props) {
    const data = reactive<any>({});

    // 获取token
    let tokenStr = '';
    const hostToken = localStorage.getItem('token');
    const clientToken = localStorage.getItem('access_token');
    if (hostToken) {
      tokenStr = JSON.parse(hostToken)?.token || '';
    } else if (clientToken) {
      tokenStr = clientToken;
    }
    const userToken = `Bearer ${tokenStr}`;

    // 获取当前路由
    const route = useRoute();
    const { projectCode, appCode } = route.meta as Required<MenuRouteMeta>;
    console.log('routermeta', route.meta);

    onMounted(async () => {
      const CramiLcUi = await import('@crami/lowcode-materials');
      const _W = window as any;
      _W.CramiLcUi = CramiLcUi;

      // 获取schema
      if (props.pageId) {
        Object.assign(
          data,
          await getSchemaById({
            pageId: props.pageId,
            projectCode,
            appCode,
          }),
        );
      }
    });

    return () => {
      const { schema, components } = data;

      // 定义一个弹窗方法
      async function openModal(params: any) {
        const vnode = createVNode(ModalPage, {
          params,
          components,
          routeMeta: route.meta,
          userToken,
          key: Math.random(),
        });
        render(vnode, document.body);
        vnode.component?.ctx?.open();
      }

      if (!schema || !components) {
        return h(Spin);
      }

      // 处理页面传参
      const _pageParams = route.meta.pageParams
        ? JSON.parse(route.meta.pageParams as string)
        : props.pageParams;
      const formularData = {
        projectCode,
        appCode,
      };
      const pageParams = normalizePageParams(_pageParams, schema.pageParamsConfig, formularData);

      return h('div', { class: 'lowcode-plugin-sample-preview' }, [
        h(VueRenderer, {
          scope: {
            openModal,
            routeMeta: route.meta,
            userToken,
            pageParams: pageParams,
          },
          class: 'lowcode-plugin-sample-preview-content',
          schema,
          components,
        }),
      ]);
    };
  },
});
