import { defineComponent, defineAsyncComponent, ref, reactive, computed, onBeforeMount, onUnmounted, onBeforeUpdate, onMounted, watch, resolveComponent, openBlock, createElementBlock, normalizeClass, createVNode, withModifiers, withCtx, createElementVNode, Fragment, renderList, createCommentVNode, createBlock, toDisplayString, unref, nextTick } from 'vue';
import { useRoute, useRouter, onBeforeRouteUpdate } from 'vue-router';
import Sortable from 'sortablejs';
import { ElMessage } from 'element-plus';
import { storeToRefs } from 'pinia';
import '../../../../../stores/index.mjs';
import '../../../../../utils/index.mjs';
import emitter from '../../../../../utils/mitt.mjs';
import other from '../../../../../hooks/other.mjs';
import { useTagsViewRoutes } from '../../../../../stores/tagsViewRoutes.mjs';
import { useThemeConfig } from '../../../../../stores/themeConfig.mjs';
import { useRoutesList } from '../../../../../stores/routesList.mjs';
import { useKeepALiveNames } from '../../../../../stores/keepAliveNames.mjs';
import { Session } from '../../../../../utils/storage.mjs';
import { isObjectValueEqual } from '../../../../../utils/arrayOperation.mjs';

const _hoisted_1 = ["data-url", "onContextmenu", "onMousedown", "onClick"];
const _hoisted_2 = {
  key: 0,
  class: "iconfont icon-webicon318 layout-navbars-tagsview-ul-li-iconfont"
};
var _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "tagsView",
  setup(__props) {
    const Contextmenu = defineAsyncComponent(() => import('./contextmenu.vue.mjs'));
    const tagsRefs = ref([]);
    const scrollbarRef = ref();
    const contextmenuRef = ref();
    const tagsUlRef = ref();
    const stores = useTagsViewRoutes();
    const storesThemeConfig = useThemeConfig();
    const storesTagsViewRoutes = useTagsViewRoutes();
    const storesRoutesList = useRoutesList();
    const { themeConfig } = storeToRefs(storesThemeConfig);
    const { tagsViewRoutes } = storeToRefs(storesTagsViewRoutes);
    const { routesList } = storeToRefs(storesRoutesList);
    const storesKeepALiveNames = useKeepALiveNames();
    const route = useRoute();
    const router = useRouter();
    const state = reactive({
      routeActive: "",
      routePath: route.path,
      dropdown: { x: "", y: "" },
      sortable: "",
      tagsRefsIndex: 0,
      tagsViewList: [],
      tagsViewRoutesList: []
    });
    const setTagsStyle = computed(() => {
      return themeConfig.value.tagsStyle;
    });
    const getThemeConfig = computed(() => {
      return themeConfig.value;
    });
    const setTagsViewNameI18n = computed(() => {
      return (v) => {
        return other.setTagsViewNameI18n(v);
      };
    });
    const isActive = (v) => {
      if (getThemeConfig.value.isShareTagsView) {
        return v.path === state.routePath;
      } else {
        if (v.query && Object.keys(v.query).length || v.params && Object.keys(v.params).length) {
          return v.url ? v.url === state.routeActive : v.path === state.routeActive;
        } else {
          return v.path === state.routePath;
        }
      }
    };
    const addBrowserSetSession = (tagsViewList) => {
      Session.set("tagsViewList", tagsViewList);
    };
    const getTagsViewRoutes = async () => {
      state.routeActive = await setTagsViewHighlight(route);
      state.routePath = await route.meta.isDynamic ? route.meta.isDynamicPath : route.path;
      state.tagsViewList = [];
      state.tagsViewRoutesList = tagsViewRoutes.value;
      initTagsView();
    };
    const initTagsView = async () => {
      if (Session.get("tagsViewList") && getThemeConfig.value.isCacheTagsView) {
        state.tagsViewList = await Session.get("tagsViewList");
      } else {
        await state.tagsViewRoutesList.map((v) => {
          var _a;
          if (((_a = v.meta) == null ? void 0 : _a.isAffix) && !v.meta.isHide) {
            v.url = setTagsViewHighlight(v);
            state.tagsViewList.push({ ...v });
            storesKeepALiveNames.addCachedView(v);
          }
        });
        await addTagsView(route.path, route);
      }
      getTagsRefsIndex(getThemeConfig.value.isShareTagsView ? state.routePath : state.routeActive);
    };
    const solveAddTagsView = async (path, to) => {
      var _a, _b;
      let isDynamicPath = ((_a = to == null ? void 0 : to.meta) == null ? void 0 : _a.isDynamic) ? to.meta.isDynamicPath : path;
      let current = state.tagsViewList.filter(
        (v) => {
          var _a2, _b2;
          return v.path === isDynamicPath && isObjectValueEqual(((_a2 = to == null ? void 0 : to.meta) == null ? void 0 : _a2.isDynamic) ? v.params ? v.params : null : v.query ? v.query : null, ((_b2 = to == null ? void 0 : to.meta) == null ? void 0 : _b2.isDynamic) ? (to == null ? void 0 : to.params) ? to == null ? void 0 : to.params : null : (to == null ? void 0 : to.query) ? to == null ? void 0 : to.query : null);
        }
      );
      if (current.length <= 0) {
        let findItem = state.tagsViewRoutesList.find((v) => v.path === isDynamicPath);
        if (!findItem) return false;
        if (findItem.meta.isAffix) return false;
        if (findItem.meta.isLink && !findItem.meta.isIframe) return false;
        ((_b = to == null ? void 0 : to.meta) == null ? void 0 : _b.isDynamic) ? findItem.params = to.params : findItem.query = to == null ? void 0 : to.query;
        findItem.url = setTagsViewHighlight(findItem);
        state.tagsViewList.push({ ...findItem });
        await storesKeepALiveNames.addCachedView(findItem);
        addBrowserSetSession(state.tagsViewList);
      }
    };
    const singleAddTagsView = (path, to) => {
      var _a;
      let isDynamicPath = ((_a = to == null ? void 0 : to.meta) == null ? void 0 : _a.isDynamic) ? to.meta.isDynamicPath : path;
      state.tagsViewList.forEach((v) => {
        var _a2, _b, _c;
        if (v.path === isDynamicPath && !isObjectValueEqual(((_a2 = to == null ? void 0 : to.meta) == null ? void 0 : _a2.isDynamic) ? v.params ? v.params : null : v.query ? v.query : null, ((_b = to == null ? void 0 : to.meta) == null ? void 0 : _b.isDynamic) ? (to == null ? void 0 : to.params) ? to == null ? void 0 : to.params : null : (to == null ? void 0 : to.query) ? to == null ? void 0 : to.query : null)) {
          ((_c = to == null ? void 0 : to.meta) == null ? void 0 : _c.isDynamic) ? v.params = to.params : v.query = to == null ? void 0 : to.query;
          v.url = setTagsViewHighlight(v);
          addBrowserSetSession(state.tagsViewList);
        }
      });
    };
    const addTagsView = (path, to) => {
      nextTick(async () => {
        var _a, _b, _c;
        let item;
        if ((_a = to == null ? void 0 : to.meta) == null ? void 0 : _a.isDynamic) {
          if (!getThemeConfig.value.isShareTagsView) await solveAddTagsView(path, to);
          else await singleAddTagsView(path, to);
          if (state.tagsViewList.some((v) => {
            var _a2;
            return v.path === ((_a2 = to == null ? void 0 : to.meta) == null ? void 0 : _a2.isDynamicPath);
          })) {
            addBrowserSetSession(state.tagsViewList);
            return false;
          }
          item = state.tagsViewRoutesList.find((v) => {
            var _a2;
            return v.path === ((_a2 = to == null ? void 0 : to.meta) == null ? void 0 : _a2.isDynamicPath);
          });
        } else {
          if (!getThemeConfig.value.isShareTagsView) await solveAddTagsView(path, to);
          else await singleAddTagsView(path, to);
          if (state.tagsViewList.some((v) => v.path === path)) {
            addBrowserSetSession(state.tagsViewList);
            return false;
          }
          item = state.tagsViewRoutesList.find((v) => v.path === path);
        }
        if (!item) return false;
        if (((_b = item == null ? void 0 : item.meta) == null ? void 0 : _b.isLink) && !item.meta.isIframe) return false;
        if ((_c = to == null ? void 0 : to.meta) == null ? void 0 : _c.isDynamic) item.params = (to == null ? void 0 : to.params) ? to == null ? void 0 : to.params : route.params;
        else item.query = (to == null ? void 0 : to.query) ? to == null ? void 0 : to.query : route.query;
        item.url = setTagsViewHighlight(item);
        await storesKeepALiveNames.addCachedView(item);
        await state.tagsViewList.push({ ...item });
        await addBrowserSetSession(state.tagsViewList);
      });
    };
    const refreshCurrentTagsView = async (fullPath) => {
      var _a;
      const decodeURIPath = decodeURI(fullPath);
      let item = {};
      state.tagsViewList.forEach((v) => {
        v.transUrl = transUrlParams(v);
        if (v.transUrl) {
          if (v.transUrl === transUrlParams(v)) item = v;
        } else {
          if (v.path === decodeURIPath) item = v;
        }
      });
      if (!item) return false;
      await storesKeepALiveNames.delCachedView(item);
      emitter.emit("onTagsViewRefreshRouterView", fullPath);
      if ((_a = item.meta) == null ? void 0 : _a.isKeepAlive) storesKeepALiveNames.addCachedView(item);
    };
    const closeCurrentTagsView = (path) => {
      state.tagsViewList.map((v, k, arr) => {
        var _a;
        if (!((_a = v.meta) == null ? void 0 : _a.isAffix)) {
          if (getThemeConfig.value.isShareTagsView ? v.path === path : v.url === path) {
            storesKeepALiveNames.delCachedView(v);
            state.tagsViewList.splice(k, 1);
            setTimeout(() => {
              if (state.tagsViewList.length === k && getThemeConfig.value.isShareTagsView ? state.routePath === path : state.routeActive === path) {
                if (arr[arr.length - 1].meta.isDynamic) {
                  if (k !== arr.length) router.push({ name: arr[k].name, params: arr[k].params });
                  else router.push({ name: arr[arr.length - 1].name, params: arr[arr.length - 1].params });
                } else {
                  if (k !== arr.length) router.push({ path: arr[k].path, query: arr[k].query });
                  else router.push({ path: arr[arr.length - 1].path, query: arr[arr.length - 1].query });
                }
              } else {
                if (state.tagsViewList.length !== k && getThemeConfig.value.isShareTagsView ? state.routePath === path : state.routeActive === path) {
                  if (arr[k].meta.isDynamic) {
                    router.push({ name: arr[k].name, params: arr[k].params });
                  } else {
                    router.push({ path: arr[k].path, query: arr[k].query });
                  }
                }
              }
            }, 0);
          }
        }
      });
      addBrowserSetSession(state.tagsViewList);
    };
    const closeOtherTagsView = (path) => {
      if (Session.get("tagsViewList")) {
        state.tagsViewList = [];
        Session.get("tagsViewList").map((v) => {
          var _a;
          if (((_a = v.meta) == null ? void 0 : _a.isAffix) && !v.meta.isHide) {
            v.url = setTagsViewHighlight(v);
            storesKeepALiveNames.delOthersCachedViews(v);
            state.tagsViewList.push({ ...v });
          }
        });
        addTagsView(path, route);
        addBrowserSetSession(state.tagsViewList);
      }
    };
    const closeAllTagsView = () => {
      if (Session.get("tagsViewList")) {
        storesKeepALiveNames.delAllCachedViews();
        state.tagsViewList = [];
        Session.get("tagsViewList").map((v) => {
          var _a;
          if (((_a = v.meta) == null ? void 0 : _a.isAffix) && !v.meta.isHide) {
            v.url = setTagsViewHighlight(v);
            state.tagsViewList.push({ ...v });
            router.push({ path: state.tagsViewList[state.tagsViewList.length - 1].path });
          }
        });
        addBrowserSetSession(state.tagsViewList);
      }
    };
    const openCurrenFullscreen = async (path) => {
      const item = state.tagsViewList.find((v) => getThemeConfig.value.isShareTagsView ? v.path === path : v.url === path);
      if (item.meta.isDynamic) await router.push({ name: item.name, params: item.params });
      else await router.push({ name: item.name, query: item.query });
      stores.setCurrenFullscreen(true);
    };
    const getCurrentRouteItem = (item) => {
      let resItem = {};
      state.tagsViewList.forEach((v) => {
        v.transUrl = transUrlParams(v);
        if (v.transUrl) {
          if (v.transUrl === transUrlParams(v) && v.transUrl === item.commonUrl) resItem = v;
        } else {
          if (v.path === decodeURI(item.path)) resItem = v;
        }
      });
      if (!resItem) return null;
      else return resItem;
    };
    const onCurrentContextmenuClick = async (item) => {
      item.commonUrl = transUrlParams(item);
      if (!getCurrentRouteItem(item)) return ElMessage({ type: "warning", message: "\u8BF7\u6B63\u786E\u8F93\u5165\u8DEF\u5F84\u53CA\u5B8C\u6574\u53C2\u6570\uFF08query\u3001params\uFF09" });
      const { path, name, params, query, meta, url } = getCurrentRouteItem(item);
      switch (item.contextMenuClickId) {
        case 0:
          if (meta.isDynamic) await router.push({ name, params });
          else await router.push({ path, query });
          await refreshCurrentTagsView(route.fullPath);
          break;
        case 1:
          closeCurrentTagsView(getThemeConfig.value.isShareTagsView ? path : url);
          break;
        case 2:
          if (meta.isDynamic) await router.push({ name, params });
          else await router.push({ path, query });
          closeOtherTagsView(path);
          break;
        case 3:
          closeAllTagsView();
          break;
        case 4:
          await openCurrenFullscreen(getThemeConfig.value.isShareTagsView ? path : url);
          break;
      }
    };
    const onContextmenu = (v, e) => {
      const { clientX, clientY } = e;
      state.dropdown.x = clientX;
      state.dropdown.y = clientY;
      contextmenuRef.value.openContextmenu(v);
    };
    const onMousedownMenu = (v, e) => {
      var _a;
      if (!((_a = v.meta) == null ? void 0 : _a.isAffix) && e.button === 1) {
        const item = Object.assign({}, { contextMenuClickId: 1, ...v });
        onCurrentContextmenuClick(item);
      }
    };
    const onTagsClick = (v, k) => {
      state.tagsRefsIndex = k;
      router.push(v);
      if (getThemeConfig.value.layout === "columns") {
        const item = routesList.value.find((r) => r.path.indexOf(`/${v.path.split("/")[1]}`) > -1);
        !item.children ? getThemeConfig.value.isCollapse = true : getThemeConfig.value.isCollapse = false;
      }
    };
    const transUrlParams = (v) => {
      var _a, _b;
      let params = v.query && Object.keys(v.query).length > 0 ? v.query : v.params;
      if (!params) return "";
      let path = "";
      for (let [key, value] of Object.entries(params)) {
        if ((_a = v.meta) == null ? void 0 : _a.isDynamic) path += `/${value}`;
        else path += `&${key}=${value}`;
      }
      if ((_b = v.meta) == null ? void 0 : _b.isDynamic) {
        return v.isFnClick ? decodeURI(v.path) : `${v.path.split(":")[0]}${path.replace(/^\//, "")}`;
      } else {
        return `${v.path}${path.replace(/^&/, "?")}`;
      }
    };
    const setTagsViewHighlight = (v) => {
      var _a;
      let params = v.query && Object.keys(v.query).length > 0 ? v.query : v.params;
      if (!params || Object.keys(params).length <= 0) return v.path;
      let path = "";
      for (let i in params) {
        path += params[i];
      }
      return `${((_a = v.meta) == null ? void 0 : _a.isDynamic) ? v.meta.isDynamicPath : v.path}-${path}`;
    };
    const onHandleScroll = (e) => {
      scrollbarRef.value.$refs.wrapRef.scrollLeft += e.wheelDelta / 4;
    };
    const tagsViewmoveToCurrentTag = () => {
      nextTick(() => {
        if (tagsRefs.value.length <= 0) return false;
        let liDom = tagsRefs.value[state.tagsRefsIndex];
        let liIndex = state.tagsRefsIndex;
        let liLength = tagsRefs.value.length;
        let liFirst = tagsRefs.value[0];
        let liLast = tagsRefs.value[tagsRefs.value.length - 1];
        let scrollRefs = scrollbarRef.value.$refs.wrapRef;
        let scrollS = scrollRefs.scrollWidth;
        let offsetW = scrollRefs.offsetWidth;
        let scrollL = scrollRefs.scrollLeft;
        let liPrevTag = tagsRefs.value[state.tagsRefsIndex - 1];
        let liNextTag = tagsRefs.value[state.tagsRefsIndex + 1];
        let beforePrevL = 0;
        let afterNextL = 0;
        if (liDom === liFirst) {
          scrollRefs.scrollLeft = 0;
        } else if (liDom === liLast) {
          scrollRefs.scrollLeft = scrollS - offsetW;
        } else {
          if (liIndex === 0) beforePrevL = liFirst.offsetLeft - 5;
          else beforePrevL = (liPrevTag == null ? void 0 : liPrevTag.offsetLeft) - 5;
          if (liIndex === liLength) afterNextL = liLast.offsetLeft + liLast.offsetWidth + 5;
          else afterNextL = liNextTag.offsetLeft + liNextTag.offsetWidth + 5;
          if (afterNextL > scrollL + offsetW) {
            scrollRefs.scrollLeft = afterNextL - offsetW;
          } else if (beforePrevL < scrollL) {
            scrollRefs.scrollLeft = beforePrevL;
          }
        }
        scrollbarRef.value.update();
      });
    };
    const getTagsRefsIndex = (path) => {
      nextTick(async () => {
        let tagsViewList = await state.tagsViewList;
        state.tagsRefsIndex = tagsViewList.findIndex((v) => {
          if (getThemeConfig.value.isShareTagsView) {
            return v.path === path;
          } else {
            return v.url === path;
          }
        });
        tagsViewmoveToCurrentTag();
      });
    };
    const initSortable = async () => {
      const el = document.querySelector(".layout-navbars-tagsview-ul");
      if (!el) return false;
      state.sortable.el && state.sortable.destroy();
      state.sortable = Sortable.create(el, {
        animation: 300,
        dataIdAttr: "data-url",
        disabled: getThemeConfig.value.isSortableTagsView ? false : true,
        onEnd: () => {
          const sortEndList = [];
          state.sortable.toArray().map((val) => {
            state.tagsViewList.map((v) => {
              if (v.url === val) sortEndList.push({ ...v });
            });
          });
          addBrowserSetSession(sortEndList);
        }
      });
    };
    const onSortableResize = async () => {
      await initSortable();
      if (other.isMobile()) state.sortable.el && state.sortable.destroy();
    };
    onBeforeMount(() => {
      onSortableResize();
      window.addEventListener("resize", onSortableResize);
      emitter.on("onCurrentContextmenuClick", (data) => {
        data.isFnClick = true;
        onCurrentContextmenuClick(data);
      });
      emitter.on("openOrCloseSortable", () => {
        initSortable();
      });
      emitter.on("openShareTagsView", () => {
        if (getThemeConfig.value.isShareTagsView) {
          router.push("/home");
          state.tagsViewList = [];
          state.tagsViewRoutesList.map((v) => {
            var _a;
            if (((_a = v.meta) == null ? void 0 : _a.isAffix) && !v.meta.isHide) {
              v.url = setTagsViewHighlight(v);
              state.tagsViewList.push({ ...v });
            }
          });
        }
      });
    });
    onUnmounted(() => {
      emitter.off("onCurrentContextmenuClick", () => {
      });
      emitter.off("openOrCloseSortable", () => {
      });
      emitter.off("openShareTagsView", () => {
      });
      window.removeEventListener("resize", onSortableResize);
    });
    onBeforeUpdate(() => {
      tagsRefs.value = [];
    });
    onMounted(() => {
      getTagsViewRoutes();
      initSortable();
    });
    onBeforeRouteUpdate(async (to) => {
      state.routeActive = setTagsViewHighlight(to);
      state.routePath = to.meta.isDynamic ? to.meta.isDynamicPath : to.path;
      await addTagsView(to.path, to);
      getTagsRefsIndex(getThemeConfig.value.isShareTagsView ? state.routePath : state.routeActive);
    });
    watch(
      () => tagsViewRoutes.value,
      (val) => {
        if (val.length === state.tagsViewRoutesList.length) return false;
        getTagsViewRoutes();
      },
      {
        deep: true
      }
    );
    return (_ctx, _cache) => {
      const _component_SvgIcon = resolveComponent("SvgIcon");
      const _component_el_scrollbar = resolveComponent("el-scrollbar");
      return openBlock(), createElementBlock(
        "div",
        {
          class: normalizeClass(["layout-navbars-tagsview", { "layout-navbars-tagsview-shadow": getThemeConfig.value.layout === "classic" }])
        },
        [
          createVNode(
            _component_el_scrollbar,
            {
              ref_key: "scrollbarRef",
              ref: scrollbarRef,
              onWheel: withModifiers(onHandleScroll, ["prevent"])
            },
            {
              default: withCtx(() => [
                createElementVNode(
                  "ul",
                  {
                    class: normalizeClass(["layout-navbars-tagsview-ul", setTagsStyle.value]),
                    ref_key: "tagsUlRef",
                    ref: tagsUlRef
                  },
                  [
                    (openBlock(true), createElementBlock(
                      Fragment,
                      null,
                      renderList(state.tagsViewList, (v, k) => {
                        return openBlock(), createElementBlock("li", {
                          key: k,
                          class: normalizeClass(["layout-navbars-tagsview-ul-li", { "is-active": isActive(v) }]),
                          "data-url": v.url,
                          onContextmenu: withModifiers(($event) => onContextmenu(v, $event), ["prevent"]),
                          onMousedown: ($event) => onMousedownMenu(v, $event),
                          onClick: ($event) => onTagsClick(v, k),
                          ref_for: true,
                          ref: (el) => {
                            if (el) tagsRefs.value[k] = el;
                          }
                        }, [
                          isActive(v) ? (openBlock(), createElementBlock("i", _hoisted_2)) : createCommentVNode("v-if", true),
                          getThemeConfig.value.isTagsviewIcon ? (openBlock(), createBlock(_component_SvgIcon, {
                            key: 1,
                            name: v.meta.icon,
                            class: "pr5",
                            size: 18
                          }, null, 8, ["name"])) : createCommentVNode("v-if", true),
                          createElementVNode(
                            "span",
                            null,
                            toDisplayString(setTagsViewNameI18n.value(v)),
                            1
                            /* TEXT */
                          ),
                          isActive(v) ? (openBlock(), createElementBlock(
                            Fragment,
                            { key: 2 },
                            [
                              createVNode(_component_SvgIcon, {
                                name: "ele-RefreshRight",
                                class: "ml5 layout-navbars-tagsview-ul-li-refresh",
                                onClick: _cache[0] || (_cache[0] = withModifiers(($event) => refreshCurrentTagsView(_ctx.$route.fullPath), ["stop"]))
                              }),
                              !v.meta.isAffix ? (openBlock(), createBlock(_component_SvgIcon, {
                                key: 0,
                                name: "ele-Close",
                                class: "layout-navbars-tagsview-ul-li-icon layout-icon-active",
                                onClick: withModifiers(($event) => closeCurrentTagsView(getThemeConfig.value.isShareTagsView ? v.path : v.url), ["stop"])
                              }, null, 8, ["onClick"])) : createCommentVNode("v-if", true)
                            ],
                            64
                            /* STABLE_FRAGMENT */
                          )) : createCommentVNode("v-if", true),
                          !v.meta.isAffix ? (openBlock(), createBlock(_component_SvgIcon, {
                            key: 3,
                            name: "ele-Close",
                            class: "layout-navbars-tagsview-ul-li-icon layout-icon-three",
                            onClick: withModifiers(($event) => closeCurrentTagsView(getThemeConfig.value.isShareTagsView ? v.path : v.url), ["stop"])
                          }, null, 8, ["onClick"])) : createCommentVNode("v-if", true)
                        ], 42, _hoisted_1);
                      }),
                      128
                      /* KEYED_FRAGMENT */
                    ))
                  ],
                  2
                  /* CLASS */
                )
              ]),
              _: 1
              /* STABLE */
            },
            512
            /* NEED_PATCH */
          ),
          createVNode(unref(Contextmenu), {
            dropdown: state.dropdown,
            ref_key: "contextmenuRef",
            ref: contextmenuRef,
            onCurrentContextmenuClick
          }, null, 8, ["dropdown"])
        ],
        2
        /* CLASS */
      );
    };
  }
});

export { _sfc_main as default };
