import { safeRedirect } from '@ibiz-template/runtime';
import { useRouter } from '@ibiz-template/vue-util';
import qs from 'qs';
import { defineComponent, getCurrentInstance } from 'vue';

export default defineComponent({
  setup() {
    const inst = getCurrentInstance()!.proxy;

    const router = useRouter(inst);

    const { href } = window.location;

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

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

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

    const params = qs.parse(queryStr, { delimiter: ';' }) as IData;

    const { apptype, todotype, todoid } = params;

    const data: IData = { srfapptype: 'pc', srfapp: '' };

    if (!apptype) {
      data.todourltype = 'RouterUrl';
    }

    async function getLinkUrl(): Promise<void> {
      const res = await ibiz.net.post(`/systodos/${todoid}/getlinkurl`, data);
      let url: string = res.data.linkurl;
      // apptype存在，带ip、端口等完整数据
      if (apptype) {
        safeRedirect(url, { type: 'href' });
      } else {
        if (url.indexOf('/') !== 0) {
          url = `/${url}`;
        }
        url += `;srfwf=${todotype}`;
        router.push(`/index${url}`);
      }
    }

    getLinkUrl();
  },
  render() {
    return <div>待办列表重定向</div>;
  },
});
