import { createApp } from 'vue';
import VueGridLayout from 'vue-grid-layout'; // 引入layout

import { baseAxios } from '@/utils/request';
import { createPinia } from 'pinia';
import Postmate from 'postmate';
import {
  qiankunWindow,
  renderWithQiankun,
} from 'vite-plugin-qiankun/dist/helper';

import App from './App.vue';
import { createProjectRouter } from './router';

import './global.less';

// Postmate 握手协议
const postmate = new Postmate.Model({
  sayHi: (data: any) => {
    console.log('sayHi', data);
  },
});

// 数据模型
const model = {
  name: '',
  applicationId: -1,
  projectId: -1,
  fileId: '',
  url: '',
  accessToken: '',
};

await postmate.then((parent) => {
  parent.emit('some-event', 'y-code-renderer is ready');
  Object.assign(model, parent.model);
  localStorage.setItem('y-code-access-token', model.accessToken || '');
  baseAxios.interceptors.request.use((config) => {
    config.headers.Authorization = `Bearer ${model.accessToken}`;
    return config;
  });
});

let app;
function render(props: object = {}) {
  app = createApp(App);
  setStyleSheet(props.styles);
  const router = createProjectRouter(props.base);
  app.use(router);
  app.use(VueGridLayout);
  app.use(createPinia());
  app.mount('#y-code-app');
}

function setStyleSheet(styles: object = {}) {
  const styleEle = document.createElement('style');
  styleEle.type = 'text/css';
  styleEle.innerHTML = `
  :root {
    --primary-color: ${styles.primaryColor || '#1677ff'};
    --primary-light-color: ${styles.primaryLightColor || '#4096ff'};
    --table-head-bg-color: ${styles.tableHeadBgColor || '#fafafa'};
    --table-head-font-color: ${styles.tableHeadFontColor || '#191919'};
  }
  `;
  document.head.append(styleEle);
}

const __POWERED_BY_QIANKUN__ =
  qiankunWindow?.__POWERED_BY_QIANKUN__ ||
  window?.proxy?.__POWERED_BY_QIANKUN__;

if (__POWERED_BY_QIANKUN__) {
  renderWithQiankun({
    bootstrap() {
      console.log('bootstrap');
      return Promise.resolve();
    },
    mount(props) {
      console.log('mount');
      render(props);
      return Promise.resolve();
    },
    unmount() {
      console.log('unmount');
      if (app) {
        app.unmount();
      }
      return Promise.resolve();
    },
    update() {},
  });
} else {
  render();
}
