import { local, session } from '~/utils/Storage';
import { defineStore } from 'pinia';

type Menu = {
  url: string
  children: Menu[]
}

export default defineStore('menu', {
  state: () => {
    return {
      menu: [],
      openMenu: [],
      routers: [],
    };
  },
  actions: {
    setOpenMenu(payload: string) {
      this.openMenu = [payload]
    },
    setMenu(payload: Menu[]) {
      this.menu = payload;
      const routers = [];
      const def = (v: Menu[]) => {
        v.forEach((value: Menu) => {
          if (!routers.includes(value.url)) {
            routers.push(value.url);
          }
          if (Array.isArray(value.children) && value.children.length != 0) {
            def(value.children);
          }
        });
      };
      def(payload);
      this.routers = routers;
    },
  },
  persist: {
    enabled: true,
    strategies: [{
      storage: local,
      paths: ['menu', 'routers']
    }, {
      storage: session,
      paths: ['openMenu']
    }]
  }
})
