import {onMounted, reactive, watch} from 'vue';
import {useTabStore, storeToRefs} from '@stores';
import {find} from 'lodash-es';
import {useRoute, useRouter} from 'vue-router';
import {formatMenu} from '@utils';
import {useQueryClient} from '@tanstack/vue-query';
import {MenuListData} from '@models';
import {getMenuByUserId} from '@apis';

export function useMenu() {
  const queryClient = useQueryClient();
  const data = queryClient.getQueryData<MenuListData[]>([getMenuByUserId.name]);

  const basicMenu = [
    {
      name: '首页',
      koreanName: '첫 페이지',
      id: '-1',
      img: 'HomeMenuIcon',
      pid: '0',
      url: '/main',
      orderBy: '',
      modifyTime: '',
      modifyUser: '',
    },
    ...(data ?? []),
  ];

  const menuOptions = formatMenu(basicMenu);

  const tabStore = useTabStore();
  const {activeKey, tabList} = storeToRefs(tabStore);
  const expandKeys = reactive<string[]>([]);
  const {push} = useRouter();

  function onExpandedUpdate(keys: string[] | string) {
    expandKeys.length = 0;
    expandKeys.push(...(Array.isArray(keys) ? keys : [keys]));
  }

  function onUpdate(
    key: string,
    item: typeof menuOptions[0],
  ) {
    const {label, pid, url, koLabel} = item;

    tabStore.dispatch({
      type: 'ADD',
      payload: {label, key, url, pid, koLabel},
    });
  }

  const route = useRoute();
  onMounted(function() {
    // 页面初始页面不一定是首页需要判断是否需要增加tab
    const idx = basicMenu.findIndex(val => val.url === route.path);
    if (idx < 0) return;
    const {name, pid, url, id, koreanName} = basicMenu[idx];

    tabStore.dispatch({
      type: 'ADD',
      payload: {label: name, key: id, url, pid, koLabel: koreanName},
    });
  });

  // activeKey变化后更新菜单的展开菜单的值并跳转到对应的url
  watch(activeKey, function(value) {
    if (expandKeys[0] === value) return;

    const temp = find(
      tabList.value,
      val => val.key === value,
    );

    if (!temp) return;
    onExpandedUpdate(temp.pid);
    push(temp.url);
  });

  return [
    {activeKey, expandKeys, menuOptions},
    {onUpdate, onExpandedUpdate},
  ] as const;
}
