import { inject, onMounted, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";

/**
 * @description 路由器跳转封装
 * */
export const usePageRouter = () => {
  const route = useRoute();
  const router = useRouter();
  const tabRemove: Function = inject("tabRemove") as Function;

  /**
   * @description 页面打开, 兼容：如果有pageid参数就postMessage给K3,由K3打开
   *   showType
   *       ModalInCurrentForm: 只在当前单据中模态显示，可以操作其它单据(这情况可以内部实现，不需要post给K3)
   *       MainNewTabPage: 主界面新页签(默认)
   * @param path 路由地址
   * @param title K3显示的标题
   */
  const pageOpen = (
    arg:
      | string
      | {
          name: string;
          params?: Record<string, any>;
          query?: Record<string, any>;
          replace?: boolean;
        }
  ) => {
    if (typeof arg === "string") {
      return router.push(arg);
    } else {
      const { name, params = {}, query = {} } = arg;
      return router.push({ name, params, query });
    }
  };

  /**
   * @description 页面关闭, 兼容：如果有pageid参数就postMessage给K3,由K3关闭
   * */
  const pageClose = () => {
    let pageid = window.location.href.split("pageid=")[1];
    if (pageid) {
      // let poststr = JSON.stringify({
      //   pageid: pageid,
      //   putdata: {
      //     url: "close"
      //   }
      // });
      // let _window = window as any;
      // if (_window?.chrome?.webview) {
      //   _window.chrome.webview.postMessage(poststr);
      // } else {
      //   window.top?.postMessage(poststr, "*");
      // }
    } else {
      tabRemove(route.fullPath);
    }
  };

  /**
   * @description 页面刷新, 兼容：如果有pageid参数就postMessage给K3,由K3刷新
   *   showType
   *       InCurrentForm: 在当前单据中刷新
   *       MainNewTabPage: 主界面新页签(默认)
   * @param path 路由地址
   * @param title K3显示的标题
   */
  const pageRefresh = (
    arg:
      | string
      | {
          name: string;
          params?: Record<string, any>;
          query?: Record<string, any>;
          replace?: boolean;
        }
  ) => {
    if (typeof arg === "string") {
      return router.replace(arg);
    } else {
      const { name, params = {}, query = {} } = arg;
      return router.replace({ name, params, query });
    }
  };

  /**
   * @description 自动监听message事件
   * */
  const useAutoMessageHandler = (handler: (e: MessageEvent) => void) => {
    onMounted(() => {
      addMessageHandler(handler);
    });

    onUnmounted(() => {
      removeMessageHandler(handler);
    });
  };

  /**
   * @description 手动监听message事件
   * */
  const addMessageHandler = (handler: (e: MessageEvent) => void) => {
    let _window = window as any;
    if (_window?.chrome?.webview) {
      _window.chrome.webview.addEventListener("message", handler);
    } else {
      window.addEventListener("message", handler);
    }
  };

  /**
   * @description 手动移除message事件
   * */
  const removeMessageHandler = (handler: (e: MessageEvent) => void) => {
    let _window = window as any;
    if (_window?.chrome?.webview) {
      _window.chrome.webview.removeEventListener("message", handler);
    } else {
      window.removeEventListener("message", handler);
    }
  };

  return {
    pageOpen,
    pageClose,
    pageRefresh,
    useAutoMessageHandler
  };
};
