import {defineStore} from "pinia";
import type {IAppMenuList} from "@/interface/app/IAppMenuList.ts";
import {computed, ref} from "vue";
import type {IUserMenuPermission} from "@/interface/page/user/IPermissionResponse.ts";
import type {IBaseMenuPermissionVo} from "@/model/table/IBaseMenuPermissionVo.ts";

export const menuStore = defineStore('menu',
    () => {
        let appMenu = ref<IAppMenuList[]>([]); // 用户拥有的菜单权限，层级表示
        let userMenu = ref<IUserMenuPermission[]>([]); // 用户拥有的二级菜单权限，单行表示
        let operationPermission = ref<IBaseMenuPermissionVo[]>([]); // 用户拥有的操作权限，单行表示
        const returnMenu = computed(() => appMenu);
        let selectMenu = ref<string>('');
        function clearMenu(): void {
            appMenu.value = [];
        }
        function setMenu(menu: IAppMenuList[]): void {
            appMenu.value = menu;
        }
        function getMenu(): IAppMenuList[] {
            return appMenu.value;
        }
        function resetSelectMenu(): void {
            selectMenu.value = '';
        }
        function setSelectedMenu(menu: string): void {
            selectMenu.value = menu;
        }
        function setUserMenu(needUserMenu: IUserMenuPermission[]): void {
            userMenu.value = needUserMenu;
        }
        function getUserMenuWithRouterName(routerName: string | undefined): IUserMenuPermission| undefined {
            return userMenu.value.find(item => item.routerName == routerName);
        }
        function getUserMenuWithId(menuId: string | undefined): IUserMenuPermission| undefined {
            return userMenu.value.find(item => item.menuId == menuId);
        }

        /* ******************* 操作全选方法 ******************** */

        /**
         * 设置用户操作权限
         * @param needOperationPermission 需要设置的用户操作权限
         */
        function setOperationPermission(needOperationPermission: IBaseMenuPermissionVo[]): void {
            operationPermission.value = needOperationPermission;
        }

        /**
         * 获取用户操作权限
         * @returns 用户操作权限
         */
        function getOperationPermission(): IBaseMenuPermissionVo[] {
            return operationPermission.value;
        }

        /**
         * 判断用户操作权限是否存在
         * @param permissionId 操作权限id
         * @returns 用户操作权限是否存在
         */
        function checkOperationPermission(permissionId: string): boolean {
            return operationPermission.value.some(item => item.permissionId == permissionId);
        }

        return {appMenu, returnMenu, selectMenu, clearMenu, setMenu, getMenu, resetSelectMenu, setSelectedMenu,setUserMenu, getUserMenuWithRouterName,getUserMenuWithId,
            setOperationPermission, getOperationPermission, checkOperationPermission };
    }, {
        persist: {
            key: 'menu',
        }
    })