import { defineComponent, onMounted } from 'vue';
import qs from 'qs';
import { getModelService } from '@ibiz-template/model';
import { IBizContext, RuntimeError } from '@ibiz-template/core';
import { OpenAppViewCommand } from '@ibiz-template/runtime';

export default defineComponent({
  setup() {
    const context = new IBizContext(ibiz.appData?.context || {});

    const { href } = window.location;

    const i = href.lastIndexOf('?');

    const queryStr: string = decodeURIComponent(
      href.substring(i + 1, href.length),
    );

    if (!queryStr) {
      throw new RuntimeError(`重定向参数不足无法跳转`);
    }

    async function toRedirect(): Promise<void> {
      const params = qs.parse(queryStr, { delimiter: ';' }) as IData;

      const deName: string = params.srfdename || '';

      if (!deName) {
        throw new RuntimeError('重定向参数缺少实体名称');
      }

      const upperDeName = deName.toUpperCase();

      const modelService = await getModelService();

      const app = modelService.app;

      const entity = app.getAllPSAppDataEntities()!.find(item => {
        return (item.name || item.refM.name) === upperDeName;
      });

      if (!entity) {
        throw new RuntimeError(`未找到指定实体: ${deName}`);
      }

      const deCodeName: string = entity.codeName || entity.refM.codeName;

      params[deCodeName.toLowerCase()] = params[deName.toLowerCase()];

      const deRdView = app.getAllPSAppViews()?.find(view => {
        const { refM } = view;
        if (refM.resource === deCodeName && refM.view === 'RedirectView') {
          return view;
        }
        return null;
      });

      if (!deRdView) {
        throw new Error(`未找到实体[${deName}]默认重定向视图[RedirectView]`);
      }

      // 删除跳转用参数
      delete params.srfdename;

      await ibiz.commands.execute(
        OpenAppViewCommand.TAG,
        deRdView,
        context,
        params,
      );
    }

    onMounted(() => {
      const el = document.querySelector('.app-loading-x') as HTMLDivElement;
      if (el) {
        el.style.display = 'block';
      }
    });

    toRedirect();
  },
  render() {
    return <div>重定向跳转中</div>;
  },
});
