<!-- @format -->

<template>
  <a-layout class="ns-application" :id="iframe ? 'iframeApplication' : ''">
    <ns-header class="ns-header-menu" :initHeaderKey="selectedHeaderKeys" />
    <a-layout class="ns-application-layout">
      <ns-sider
        v-if="dealMenus(newMenu)"
        :menuList="newMenu"
        :initSiderKey="selectedSiderKeys"
        :initSiderOpenKey="selectedSiderOpenKeys" />
      <a-layout>
        <!-- <NsBreadcrumb :isCheck="false" :breadcrumbList="breadcrumbList" /> -->
        <newNsTags :menuList="newMenu" />
        <a-layout-content class="ns-content">
          <ns-content />
        </a-layout-content>
      </a-layout>
    </a-layout>
  </a-layout>
</template>
<script lang="ts">
  import { computed, defineComponent, provide, ref, watch, onMounted } from 'vue';
  import NsHeader from './layout/customHeader.vue';
  import NsSider from './layout/customSider.vue';
  import newNsTags from './layout/tag/index.vue';
  import NsBreadcrumb from './layout/breadcrumb.vue';
  import NsContent from './layout/baseContent.vue';
  import { useRouter } from 'vue-router';
  import { emitEvents } from './application.d';
  import { Cookies } from '/nerv-lib/util/cookie';
  import { appConfigStore } from '/nerv-lib/saas/store/modules/app-config';
  import { authorizationService } from '/nerv-base/store/modules/authorization-service';
  import mitt from 'mitt';
  import { storeToRefs } from 'pinia';
  export default defineComponent({
    name: 'NsApplication',
    components: { NsHeader, NsSider, NsContent, newNsTags, NsBreadcrumb },
    setup() {
      const mittEmit = mitt<emitEvents>();
      const breadcrumbList = ref<object[]>([]);
      provide('mittEmit', mittEmit);
      const configStore = appConfigStore();
      const authorizationStore = authorizationService();
      const { getInitRouterList: initRouterList } = storeToRefs(authorizationStore);
      const { getAllResourMenus: initAllMenus } = storeToRefs(authorizationStore);
      if (!authorizationStore.getPrjectId && Cookies.get('projectUuid')) {
        authorizationStore.setProjectId(Cookies.get('projectUuid'));
      }
      const newMenu = ref<object>([]);
      const selectedHeaderKeys = ref<string[]>([]);
      const selectedSiderOpenKeys = ref<string[]>([]);
      const selectedSiderKeys = ref<string[]>([]);
      const router = useRouter();
      const dealMenus = (arr: object[]) => {
        if (!arr.length) {
          return false;
        } else {
          let isTrue = false;
          arr.forEach((item) => {
            if (item.type !== 'op') {
              isTrue = true;
            }
          });
          return isTrue;
        }
      };
      //处理顶部菜单和左侧菜单选中展开
      const dealInitHeaderKey = async (key: string) => {
        if (!initAllMenus.value.length) {
          await authorizationStore.initMenuResource();
        }
        const info = initAllMenus.value.filter((x) => x.code === key)[0];

        if (info && info.parentCode) {
          dealInitHeaderKey(info.parentCode);
          selectedSiderKeys.value.push(info.code);
          selectedSiderOpenKeys.value.push(info.code);
        } else {
          if (info) {
            selectedHeaderKeys.value.push(info.code);
            newMenu.value = info.menus ? info.menus : [];
          }
        }
      };
      const dealBreadcrumb = (e) => {
        let info = authorizationStore.allResourMenus.filter((x) => e.code && x.code === e.code)[0];
        if (info) {
          breadcrumbList.value.unshift({
            name: info.code,
            menus: info.menus,
            type: info.type,
            meta: {
              title: info.label,
            },
          });
          if (info.parentCode) {
            dealBreadcrumb({ code: info.parentCode });
          }
        }
      };
      const dealRouterCode = (e) => {
        breadcrumbList.value = [];
        let code = '';
        if (e.name && e.name.endsWith('Index')) {
          const info = authorizationStore.allResourMenus.filter(
            (x) => x.code === `${configStore.resourceName}${e.name}`,
          )[0];
          if (info && info.type === 'menus') {
            code = `${configStore.resourceName}${e.name}`;
          } else {
            code = `${configStore.resourceName}${e.name.toString().replace('Index', '')}`;
          }
        } else {
          code = `${configStore.resourceName}${e.name}`;
        }
        if (authorizationStore.allResourMenus?.length) {
          dealBreadcrumb({ code });
        } else {
          setTimeout(() => {
            dealBreadcrumb({ code });
          }, 500);
        }
      };
      onMounted(() => {
        setTimeout(() => {
          dealRouterCode(router.currentRoute.value);
        }, 1000);
      });

      watch(
        () => router.currentRoute.value,
        async (e) => {
          dealRouterCode(e);

          if (e.fullPath !== '/login' && e.matched.length > 1) {
            selectedHeaderKeys.value = [];
            selectedSiderKeys.value = [];
            selectedSiderOpenKeys.value = [];
            if (!initAllMenus.value.length) {
              //写死
              const loginType = sessionStorage.getItem('loginType');
              if (loginType === '4') {
                await authorizationStore.initUserResource();
                authorizationStore.initMenus = authorizationStore.userResourceList;
              } else {
                await authorizationStore.initMenuResource();
              }
            }
            let code = e.meta?.bindView ? e.meta?.bindView : e.name;
            if (configStore.resourceName) {
              code = `${configStore.resourceName}${code}`;
            }
            if (initAllMenus.value.findIndex((x) => x.code === code) === -1) {
              dealInitHeaderKey(code?.toString().replace('Index', ''));
            } else {
              dealInitHeaderKey(code);
            }
            window.sessionStorage.setItem('url', e.fullPath);
          }
        },
        { immediate: true },
      );

      return {
        breadcrumbList,
        dealMenus,
        iframe: computed(() => configStore.iframe),
        configStore,
        initRouterList,
        selectedHeaderKeys,
        selectedSiderKeys,
        selectedSiderOpenKeys,
        newMenu,
        authorizationStore,
      };
    },
  });
</script>
<style lang="less" scoped>
  .ns-application {
    min-height: 100%;
    .ns-application-layout {
      min-height: 100%;
      flex-direction: row;
    }
  }

  .ns-content {
    position: relative;
    flex: 1 1 auto;
    padding-top: 84px;
    background-color: #e5ebf0;
    > div {
      height: 100%;
      background-color: #fff;
      margin: 0 16px 16px 16px;
    }
    .ns-content-main {
      // margin: @ns-content-padding;
      min-height: calc(100% - 48px);
      height: calc(100% - 16px);
      // background-color: @white;
    }
    .ns-view {
      // margin: @ns-content-padding;
      // min-height: calc(100% - 48px);
      // height: calc(100% - 48px);
      background-color: @white;
    }
  }
  #iframeApplication .ns-content {
    padding-top: 55px !important;
  }
</style>