import type { AccountModel } from '@/request/api/account.api';
import { defineStore }       from 'pinia';
import { VxeUI } from 'vxe-pc-ui';


export const useAccountStore = defineStore('account', () => {
  const token = ref<string>();
  const permission = ref<string[]>([]);
  const local = ref<AccountModel['local'] | null>();
  const menus = ref<AccountModel['menus']>([]);

  watch(
    permission,
    (value) => {
      if (!value.length) return;
      VxeUI.setConfig({
        permissionMethod({ code }) {
          const has = value.includes(code as string);
          return { visible: has, disabled: !has };
        },
      });
    },
    { deep: false }
  );

  const $init = (data: AccountModel) => {
    token.value = data.token;
    local.value = data.local;
    menus.value = data.menus;
    permission.value = data.permission;
    // 初次进入：若有患者管理权限，优先进入患者管理；否则进入第一个菜单
    const preferred = findMenuByKey(menus.value, '/patient/history');
    return preferred ?? getFirstMenu(menus.value) ?? '/';
  };

  const $reset = () => {
    token.value = '';
    local.value = null;
    menus.value = [];
  };

  return { token, local, menus, permission, $init, $reset };
});

function getFirstMenu(menus?: AccountModel['menus']): string | void {
  if ( !menus?.length ) return void 0;
  const { key, children = [] } = menus?.[ 0 ] ?? {};
  return getFirstMenu(children) ?? key;
}

function findMenuByKey(menus?: AccountModel['menus'], target?: string): string | void {
  if (!menus?.length || !target) return void 0;
  for (const item of menus) {
    if (item?.key === target) return item.key;
    const hit = findMenuByKey(item?.children as any, target);
    if (hit) return hit;
  }
  return void 0;
}
