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 = IBizContext.newTempContext(
      {},
      IBizContext.newByIContext(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;

      // 转换 processDefinitionKey 中的工作流流程以及版本到参数中
      const tags = params.processDefinitionKey.split('-');
      const wfTag = tags[3] as string;
      const wf = wfTag.substring(0, wfTag.lastIndexOf('v'));
      const wfVersion = wfTag.substring(wfTag.lastIndexOf('v'));
      params.wf = wf;
      params.wfVersion = wfVersion;

      // 工作流附加参数转到上下文里
      if (params.srfprocessinstanceid) {
        context.srfprocessinstanceid = params.srfprocessinstanceid;
        delete params.srfprocessinstanceid;
      }

      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>;
  },
});
