import { ITagType } from "@/const/interface_type";
import { RouterOptions } from "vue-router";

export default {
  install: (router: any, store: any) => {
    function isURL(s: string) {
      return /^http[s]?:\/\/.*/.test(s);
    }

    function objToform(obj: any) {
      const result: any = [];
      Object.keys(obj).forEach((ele) => {
        result.push(`${ele}=${obj[ele]}`);
      });
      return result.join("&");
    }
    router.$avueRouter = {
      // 全局配置
      $website: store.getters.website,
      $defaultTitle: "中央应急物资储备管理系统",
      routerList: [],
      group: "",
      // 设置标题
      setTitle: function (title: string) {
        title = title ? `${title}——${this.$defaultTitle}` : this.$defaultTitle;
        document.title = title;
      },
      closeTag: (value: string) => {
        const tag = value || store.getters.tag;
        store.commit("DEL_TAG", tag);
      },
      // 关闭当前标签，并打开最后一个tag
      openLastTag: (value: ITagType) => {
        const tag = value || store.getters.tag;
        store.commit("DEL_TAG", tag);
        const tagList = store.getters.tagList;
        const lastLen = tagList.length - 1;
        const last = tagList[lastLen];
        router.push({
          path: last.value
        });
      },
      // 处理路由
      getPath: function (params: any) {
        const { src } = params;
        let result = src || "/";
        if (src.includes("http") || src.includes("https")) {
          result = `/myiframe/urlPath?${objToform(params)}`;
        }
        return result;
      },
      // 正则处理路由
      vaildPath: function (list: any, path: any) {
        let result = false;
        list.forEach((ele: any) => {
          if (new RegExp("^" + ele + ".*", "g").test(path)) {
            result = true;
          }
        });
        return result;
      },
      // 设置路由值
      getValue: function (route: any) {
        let value = "";
        if (route.query.src) {
          value = route.query.src;
        } else {
          value = route.path;
        }
        return value;
      },
      // 动态路由
      formatRoutes: function (aMenu = [], first: any) {
        const aRouter: any = [];
        const propsConfig = this.$website.menu.props;
        const propsDefault = {
          label: propsConfig.label || "label",
          path: propsConfig.path || "path",
          icon: propsConfig.icon || "icon",
          children: propsConfig.children || "children",
          meta: propsConfig.meta || "meta"
        };
        if (aMenu.length === 0) return;
        for (let i = 0; i < aMenu.length; i++) {
          const oMenu: any = aMenu[i];
          if (this.routerList.includes(oMenu[propsDefault.path])) return;
          const path = (() => {
            if (!oMenu[propsDefault.path]) {
              return;
            } else if (first) {
              return oMenu[propsDefault.path].replace("/index", "");
            } else {
              return oMenu[propsDefault.path];
            }
          })();

          // 特殊处理组件
          const component = "views" + oMenu.path;

          const name = oMenu[propsDefault.label];

          const icon = oMenu[propsDefault.icon];

          const children = oMenu[propsDefault.children];

          const meta = {
            keepAlive: Number(oMenu["keepAlive"]) === 1
          };
          const isChild = children.length !== 0;
          const oRouter = {
            path: path,
            component(resolve: any) {
              // 判断是否为首路由
              if (first) {
                require(["@/layout/index"], resolve);
                // import("@/layout/index.vue");

                // 判断是否为多层路由
              } else if (isChild && !first) {
                require(["@/layout/components/layout.vue"], resolve);
                // import("@/layout/components/layout.vue");

                // 判断是否为最终的页面视图
              } else {
                require([`@/${component}.vue`], resolve);
                // import(`@/${component}.vue`);
              }
            },
            name: name,
            icon: icon,
            meta: meta,
            redirect: (() => {
              if (!isChild && first && !isURL(path)) return `${path}/index`;
              else return "";
            })(),
            // 处理是否为一级路由
            children: !isChild
              ? (() => {
                  if (first) {
                    if (!isURL(path)) oMenu[propsDefault.path] = `${path}/index`;
                    return [
                      {
                        component(resolve: any) {
                          require([`../${component}.vue`], resolve);
                        },
                        icon: icon,
                        name: name,
                        meta: meta,
                        path: "index"
                      }
                    ];
                  }
                  return [];
                })()
              : (() => {
                  return this.formatRoutes(children, false);
                })()
          };
          aRouter.push(oRouter);
        }
        if (first) {
          if (!this.routerList.includes(aRouter[0][propsDefault.path])) {
            const addRoutes = (routes: any, parentName?: string) => {
              routes.forEach((item: any) => {
                if (parentName) {
                  router.addRoute(parentName, item);
                } else {
                  router.addRoute(item);
                }
                if (item.children?.length > 0) {
                  addRoutes(item.children, item.name);
                }
              });
            };
            addRoutes(aRouter);
            this.routerList.push(aRouter[0][propsDefault.path]);
          }
        } else {
          return aRouter;
        }
      }
    };
  }
};
