export default {
  namespaced: true,
  state: {
    visitedViews: [],
    cachedViews: [],
    isFullScreen: false,
  },
  mutations: {
    // 全屏
    FULL_SCREEN_VIEW(state, isFullScreen) {
      // eslint-disable-next-line
      state.isFullScreen = isFullScreen;
    },
    ADD_VISITED_VIEW: (state, view) => {
      const tmp = { ...view, title: view.meta?.title };
      if (!tmp.title) {
        return;
      }
      const i = state.visitedViews.findIndex((v) => v.path === tmp.path);
      if (i !== -1) {
        // 更新
        state.visitedViews.splice(i, 1, tmp);
        return;
      }
      // 找到插入位置 获取固定view的index
      const index = state.visitedViews.find((item) => !item?.meta?.affix);
      if (index === 0 && this.state.visitedViews.length === 1) {
        state.visitedViews.splice(index, 0, tmp);
      } else if (tmp.title === "MENU:CORE:HOME") {
        let num = 0;
        const arr = [];
        // eslint-disable-next-line no-shadow
        state.visitedViews.forEach((item, index) => {
          if (item.title === "MENU:CORE:HOME") {
            // eslint-disable-next-line no-plusplus
            num++;
            arr.push(index);
          }
        });
        if (num > 1) {
          state.visitedViews.splice(arr[1], 1);
        } else {
          state.visitedViews.push(tmp);
        }
      } else {
        state.visitedViews.push(tmp);
      }
    },
    ADD_CACHED_VIEW: (state, view) => {
      if (state.cachedViews.includes(view.name)) return;
      if (view.meta?.cache) {
        state.cachedViews.push(view.name);
      }
    },
    DEL_VISITED_VIEW: (state, view) => {
      // eslint-disable-next-line
      for (const [i, v] of state.visitedViews.entries()) {
        if (v.path === view?.path) {
          state.visitedViews.splice(i, 1);
          break;
        }
      }
    },
    DEL_CACHED_VIEW: (state, view) => {
      const index = state.cachedViews.indexOf(view?.name);
      index > -1 && state.cachedViews.splice(index, 1);
    },
    DEL_OTHERS_VISITED_VIEWS: (state, view) => {
      // eslint-disable-next-line
      state.visitedViews = state.visitedViews.filter((v) => {
        return v.meta.affix || v.path === view.path;
      });
    },
    DEL_OTHERS_CACHED_VIEWS: (state, view) => {
      const index = state.cachedViews.indexOf(view.name);
      if (index > -1) {
        // eslint-disable-next-line
        state.cachedViews = state.cachedViews.slice(index, index + 1);
      } else {
        // if index = -1, there is no cached tags
        // eslint-disable-next-line
        state.cachedViews = [];
      }
    },
    DEL_LEFT_VISITED_VIEWS: (state, view) => {
      const index = state.visitedViews.findIndex((v) => v.path === view.path);
      const affixIndex = state.visitedViews.findIndex((v) => !v?.meta?.affix);
      if (index > affixIndex && affixIndex > -1) {
        state.visitedViews.splice(affixIndex, index - affixIndex);
      }
    },
    DEL_LEFT_CACHED_VIEWS: (state, view) => {
      const index = state.cachedViews.indexOf(view.name);
      if (index > -1) {
        state.cachedViews.slice(index, 0);
      }
    },
    DEL_RIGHT_VISITED_VIEWS: (state, view) => {
      const index = state.visitedViews.findIndex((v) => v.path === view.path);
      const { length } = state.visitedViews;
      if (index > -1 && index < length - 1) {
        state.visitedViews.splice(index + 1, length - index);
      }
    },
    DEL_RIGHT_CACHED_VIEWS: (state) => {},
    DEL_ALL_VISITED_VIEWS: (state, payload) => {
      // eslint-disable-next-line
      state.visitedViews = payload;
    },
    DEL_ALL_CACHED_VIEWS: (state) => {
      // eslint-disable-next-line
      state.cachedViews = [];
    },
    UPDATE_VISITED_VIEW: (state, view) => {
      // eslint-disable-next-line
      for (let v of state.visitedViews) {
        if (v.path === view.path) {
          v = Object.assign(v, view);
          break;
        }
      }
    },
    ADJUST_VIEW_POS: (state, { view, pos }) => {
      let _view = null;
      const foundIndex = state.visitedViews.findIndex((v, index) => {
        if (v.path === view.path) {
          _view = v;
          return true;
        }
        return false;
      });

      if (foundIndex > -1) {
        state.visitedViews.splice(foundIndex, 1);
        state.visitedViews.splice(pos - 1, 0, _view);
      }
    },
  },
  actions: {
    // 添加view
    addView({ dispatch }, view) {
      let cachedViewName = view.name;
      const options = view.matched?.[0]?.components?.default?.options;
      if (options) {
        const { name, __file } = options;
        cachedViewName = name || __file;
      }
      const { code, path, fullPath, icon, meta = {}, query = {} } = view;
      const { title, cache, affix, key, keyPath, module, combinationMenuName } =
        {
          ...query,
          ...meta,
        };

      const tmp = {
        name: cachedViewName,
        code,
        fullPath,
        path:
          path.endsWith("/") && path !== "/"
            ? path.substring(0, path.length - 1)
            : path,
        icon,
        meta: {
          title,
          cache,
          affix,
          key,
          keyPath,
          module,
          combinationMenuName,
        },
      };

      dispatch("addVisitedView", tmp);
      dispatch("addCachedView", tmp);
    },
    addVisitedView({ commit }, view) {
      commit("ADD_VISITED_VIEW", view);
    },
    addCachedView({ commit }, view) {
      commit("ADD_CACHED_VIEW", view);
    },
    // 删除view
    delView({ dispatch, state }, view) {
      return new Promise((resolve) => {
        dispatch("delVisitedView", view);
        dispatch("delCachedView", view);
        resolve({
          visitedViews: [...state.visitedViews],
          cachedViews: [...state.cachedViews],
        });
      });
    },
    delVisitedView({ commit, state }, view) {
      return new Promise((resolve) => {
        commit("DEL_VISITED_VIEW", view);
        resolve([...state.visitedViews]);
      });
    },
    delCachedView({ commit, state }, view) {
      return new Promise((resolve) => {
        commit("DEL_CACHED_VIEW", view);
        resolve([...state.cachedViews]);
      });
    },
    // 删除左边views
    delLeftViews({ dispatch, state }, view) {
      return new Promise((resolve) => {
        dispatch("delLeftVisitedViews", view);
        dispatch("delLeftCachedViews", view);
        resolve({
          visitedViews: [...state.visitedViews],
          cachedViews: [...state.cachedViews],
        });
      });
    },
    delLeftVisitedViews({ commit, state }, view) {
      return new Promise((resolve) => {
        commit("DEL_LEFT_VISITED_VIEWS", view);
        resolve([...state.visitedViews]);
      });
    },
    delLeftCachedViews({ commit, state }, view) {
      return new Promise((resolve) => {
        commit("DEL_LEFT_CACHED_VIEWS", view);
        resolve([...state.cachedViews]);
      });
    },
    // 删除右边views
    delRightViews({ dispatch, state }, view) {
      return new Promise((resolve) => {
        dispatch("delRightVisitedViews", view);
        dispatch("delRightCachedViews", view);
        resolve({
          visitedViews: [...state.visitedViews],
          cachedViews: [...state.cachedViews],
        });
      });
    },
    delRightVisitedViews({ commit, state }, view) {
      return new Promise((resolve) => {
        commit("DEL_RIGHT_VISITED_VIEWS", view);
        resolve([...state.visitedViews]);
      });
    },
    delRightCachedViews({ commit, state }, view) {
      return new Promise((resolve) => {
        commit("DEL_RIGHT_CACHED_VIEWS", view);
        resolve([...state.cachedViews]);
      });
    },
    // 删除其他views
    delOthersViews({ dispatch, state }, view) {
      return new Promise((resolve) => {
        dispatch("delOthersVisitedViews", view);
        dispatch("delOthersCachedViews", view);
        resolve({
          visitedViews: [...state.visitedViews],
          cachedViews: [...state.cachedViews],
        });
      });
    },
    delOthersVisitedViews({ commit, state }, view) {
      return new Promise((resolve) => {
        commit("DEL_OTHERS_VISITED_VIEWS", view);
        resolve([...state.visitedViews]);
      });
    },
    delOthersCachedViews({ commit, state }, view) {
      return new Promise((resolve) => {
        commit("DEL_OTHERS_CACHED_VIEWS", view);
        resolve([...state.cachedViews]);
      });
    },
    // 删除所有views
    delAllViews({ dispatch, state }, view) {
      return new Promise((resolve) => {
        // keep affix tags
        const affixTags = state.visitedViews.filter((tag) => tag.meta.affix);
        dispatch("delAllVisitedViews", affixTags);
        dispatch("delAllCachedViews");
        resolve({
          visitedViews: affixTags,
          cachedViews: [],
        });
      });
    },
    delAllVisitedViews({ commit, state }, payload) {
      return new Promise((resolve) => {
        commit("DEL_ALL_VISITED_VIEWS", payload);
        resolve(payload);
      });
    },
    delAllCachedViews({ commit, state }) {
      return new Promise((resolve) => {
        commit("DEL_ALL_CACHED_VIEWS");
        resolve([]);
      });
    },

    updateVisitedView({ commit }, view) {
      commit("UPDATE_VISITED_VIEW", view);
    },

    /**
     * 调整View的位置
     * @param commit 提交方法
     * @param view 指定的View
     * @param pos 位置索引
     */
    adjustViewPos({ commit }, { view, pos }) {
      commit("ADJUST_VIEW_POS", { view, pos });
    },

    /**
     * 从当前tab并跳到新tab
     * @param {*} toView 要跳到的view
     * @param {*} view 现在的view
     */
    jumpBeforeView({ commit, state, dispatch }, { to, vm, del = true }) {
      // 删除当前View
      del &&
        dispatch(
          "delView",
          state.visitedViews.find((item) => item.path === vm.$route.path)
        );
      // 判断现在visitedView中是否有之前的View
      //   有，清缓存，跳页面，新加缓存
      //   没有，跳页面，加缓存
      const exist = state.visitedViews.find((item) => item.path === to.path);
      if (exist) {
        commit("DEL_CACHED_VIEW", exist);
        vm.$nextTick(() => {
          vm.$router.push({
            path: `/redirect${to.path}`,
            query: to.query || null,
          });
        });
      } else {
        vm.$router.push({
          path: to.path,
          query: to.query || null,
        });
      }
    },
  },
};
