import { defineStore } from "pinia";
import { KeepAliveState } from "@/stores/interface";
import { cloneDeep } from "lodash-es";

export const useKeepAliveStore = defineStore({
  id: "geeker-keepAlive",
  state: (): KeepAliveState => ({
    keepAliveName: [],
    keepAliveList: []
  }),
  getters: {
    getKeepAliveList(): any[] {
      return this.keepAliveList;
    }
  },
  actions: {
    setKeepAliveList(keepAliveList: any) {
      this.keepAliveList = keepAliveList;

      console.log("getKeepAliveName routeItem setKeepAliveList :>> ", JSON.stringify(this.keepAliveList));
      console.log("getKeepAliveName routeItem setKeepAliveList :>> ", this.keepAliveList);
    },
    // Add KeepAliveName
    async addKeepAliveName(route: any) {
      !this.keepAliveName.includes(route.name) && this.keepAliveName.push(route.name);

      let routeItem = this.keepAliveList.find((item: any) => item.fullPath == route.fullPath);
      if (!routeItem) {
        routeItem = {
          fullPath: route.fullPath,
          times: 0
        };
        this.keepAliveList.push(routeItem);
      }
    },
    // Remove KeepAliveName
    removeKeepAliveName(route: any) {
      this.keepAliveName = this.keepAliveName.filter(item => item !== route.name);

      let index = this.keepAliveList.findIndex(item => item.fullPath === route.path);
      if (index > -1) {
        // this.keepAliveList.splice(index, 1);
        this.keepAliveList[index].times = this.keepAliveList[index].times + 1;
      }

      console.log("getKeepAliveName routeItem removeKeepAliveName :>> ", JSON.stringify(this.keepAliveList));
      console.log("getKeepAliveName routeItem removeKeepAliveName :>> ", this.keepAliveList);
      console.log("getKeepAliveName routeItem keepAliveName :>> ", this.keepAliveName);
    },
    // Set KeepAliveName
    async setKeepAliveName(keepAliveName: string[] = []) {
      this.keepAliveName = keepAliveName;
    },
    async updateKeepAliveName(route: any) {
      this.addKeepAliveName(route);
      this.keepAliveList.forEach((item: any) => {
        console.log("updateKeepAliveName item :>> ", item.fullPath, route.fullPath, item.fullPath == route.fullPath);
        if (item.fullPath == route.fullPath) {
          item.times++;
        }
      });
    },
    getKeepAliveName(name: string) {
      let routeItem = this.keepAliveList.find((item: any) => item.fullPath == name);
      if (!routeItem) {
        routeItem = {
          fullPath: name,
          times: 0
        };
        this.keepAliveList.push(routeItem);
      }
      return routeItem;
    }
  }
});
