import { defineComponent, onMounted, ref, watch, watchEffect } from 'vue';
import { useRouter, RouterView, useRoute } from 'vue-router';
import Menus from '@/layout/ManagementLayout/Menus';
import {
  PATH_LINK_NAV_BAR_MENU,
  PATH_LINK_NAV_BAR_MENU_DICT,
} from '@/constants/constants';
import './index.scss';
import { useCommonStore } from '@/store';

export default defineComponent({
  name: 'ManagementLayout',

  setup() {
    const router = useRouter();
    const route = useRoute();
    const currentRoute = router.currentRoute.value.path;
    const paths = Object.keys(PATH_LINK_NAV_BAR_MENU);

    const currentKey = ref(paths.find((p) => currentRoute.includes(p)));

    const store = useCommonStore();

    const handleRedirect = async (path: string) => {
      let item = '1';

      for (const menu of PATH_LINK_NAV_BAR_MENU_DICT) {
        if (path === menu.path) {
          await store.getGlobalDict(menu.dict);
          item = store.globalDict[menu.dict]?.[0]?.dictValue ?? '';
          item && router.replace(`${menu.path}/${menu.subpath}/${item}`);
        }
      }
    };

    onMounted(() => {
      PATH_LINK_NAV_BAR_MENU_DICT.forEach((i) => {
        store.getGlobalDict(i.dict);
      });
      handleRedirect(route.path);
    });

    watchEffect(() => {
      handleRedirect(route.path);
    });

    watch(
      () => route.path,
      (next) => {
        currentKey.value = paths.find((p) => next.includes(p));
      },
    );

    return () => (
      <div class="management-container">
        <Menus
          type={
            (currentKey.value as keyof typeof PATH_LINK_NAV_BAR_MENU) ??
            'incident-management'
          }
        />
        <div class="main-content">
          <RouterView />
        </div>
      </div>
    );
  },
});
