<!-- @format -->

<template>
  <div
    :id="`${dealMenus(menuList) ? '' : 'fullTab'}`"
    :class="leftMenuTrigger ? 'ns-tabs-collapsed' : 'ns-tabs'">
    <Tabs
      type="editable-card"
      size="small"
      style="width: 100%"
      ref="tags"
      :animated="false"
      :hideAdd="true"
      :tabBarGutter="3"
      :activeKey="activeKeyRef"
      @change="handleChange"
      @edit="handleEdit">
      <template
        v-for="(item, index) in getTabsState"
        :key="item.currentUrl ? item.currentUrl : item.query ? item.fullPath : item.path">
        <TabPane :closable="!(item && item.meta && index === 0)">
          <template #tab>
            <a-dropdown :trigger="index === 0 ? [] : ['contextmenu']">
              <div>
                {{ item?.title }}
                <ReloadOutlined
                  @click="reload"
                  v-if="
                    activeKeyRef ===
                    (item.currentUrl ? item.currentUrl : item.query ? item.fullPath : item.path)
                  "
                  :class="loadingClass" />
              </div>
              <template #overlay>
                <a-menu>
                  <a-menu-item>
                    <a @click="closeMenu('all', item)">关闭所有标签页</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a @click="closeMenu('other', item)">关闭其他标签页</a>
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
        </TabPane>
      </template>
    </Tabs>
  </div>
</template>
<script lang="ts">
  import { ReloadOutlined } from '@ant-design/icons-vue';
  import { defineComponent, computed, unref, ref, inject } from 'vue';
  import { Tabs } from 'ant-design-vue';
  import { useTags } from '/nerv-base/store/modules/tags';
  import { listenerRouteChange, setReloadChange } from '/nerv-lib/util/routeChange';
  import { useKeepAlive } from '/nerv-base/store/modules/keepAlive';
  import { useRouter } from 'vue-router';
  import { Emitter } from 'mitt';
  import { emitEvents } from '/nerv-base/view/system/application.d';
  export default defineComponent({
    name: 'NsTags',
    components: {
      Tabs,
      ReloadOutlined,
      TabPane: Tabs.TabPane,
    },
    props: {
      menuList: { type: Array },
    },
    setup(props) {
      const mittEmit = inject('mittEmit') as Emitter<emitEvents>;
      const leftMenuTrigger = ref(false);
      mittEmit.on('leftMenuTrigger', (val) => {
        leftMenuTrigger.value = val;
      });
      const dealMenus = (arr: object[]) => {
        if (!arr || !arr.length) {
          return true;
        } else {
          let isTrue = false;
          arr.forEach((item) => {
            if (item.type !== 'op') {
              isTrue = true;
            }
          });
          return isTrue;
        }
      };
      const activeKeyRef = ref('');
      const router = useRouter();
      const visible = ref(false);
      const tagsStore = useTags();
      const loadingClass = ref('reload');
      const keepAliveStore = useKeepAlive();
      const getTabsState = computed(() => tagsStore.getTags);
      console.log(getTabsState);

      const reload = () => {
        setReloadChange();
        loadingClass.value = 'iconLoading';
        setTimeout(() => {
          loadingClass.value = 'reload';
        }, 1000);
      };
      const keepAliveList = computed(() => {
        return keepAliveStore.getKeepAlive;
      });
      const closeMenu = (key: string, info: object) => {
        if (key === 'all') {
          tagsStore.sliceTags(0);
        } else {
          tagsStore.sliceTags(0);
          tagsStore.addTags(info);
        }
      };

      const unClose = computed(() => unref(getTabsState).length === 1);

      listenerRouteChange((route) => {
        if (!route) {
          return;
        }
        console.log('rrr', route);

        if (
          getTabsState.value.findIndex(
            (x) => x.currentUrl === route.fullPath || x.path === route.fullPath,
          ) !== -1
        ) {
          if (activeKeyRef.value !== route.fullPath) {
            activeKeyRef.value = route.fullPath as string;
          }
        } else {
          const { name } = route;

          const index = route.matched.findIndex((x) => (x.meta ? x.meta.hideChildren : ''));
          const parentRoute = route.matched[index];

          if (parentRoute) {
            if (activeKeyRef.value !== route.fullPath) {
              activeKeyRef.value = route.fullPath as string;
            }
            if (route?.meta?.type === 'op') {
              if (route.matched.length) {
                if (getTabsState.value.findIndex((x: any) => x.name === parentRoute?.name) === -1) {
                  parentRoute.currentUrl = route.fullPath;
                  tagsStore.addTags(parentRoute);
                  if (route.meta?.keepAlive) {
                    if (keepAliveList.value.findIndex((x) => x === route.name) === -1) {
                      keepAliveStore.addKeepAlive(route.name);
                    }
                  }
                } else {
                  const info = getTabsState.value.filter(
                    (x: any) => x.name === parentRoute?.name,
                  )[0];
                  if (info) {
                    info.currentUrl = route.fullPath;
                  }
                }
              }
            } else {
              if (getTabsState.value.findIndex((x: any) => x.name === parentRoute?.name) === -1) {
                parentRoute.currentUrl = route.fullPath;
                tagsStore.addTags(parentRoute);
                if (route.meta?.keepAlive) {
                  if (keepAliveList.value.findIndex((x) => x === route.name) === -1) {
                    keepAliveStore.addKeepAlive(route.name);
                  }
                }
              } else {
                const info = getTabsState.value.filter((x: any) => x.name === parentRoute?.name)[0];
                if (info) {
                  info.currentUrl = route.fullPath;
                }
              }
            }
          }
        }
      });

      function handleChange(activeKey: any) {
        loadingClass.value = 'reload';
        activeKeyRef.value = activeKey;
        console.log('activeKey', activeKey);
        router.push(activeKey);
        // router.replace(activeKey);
      }

      function handleEdit(targetKey: string, action: string) {
        console.log('targetKey', targetKey);
        console.log('activeKeyRef', activeKeyRef.value);
        if (action === 'remove') {
          const i = getTabsState.value.findIndex((x) => {
            if (x.currentUrl) {
              return x.currentUrl === targetKey;
            } else {
              return x.fullPath === targetKey;
            }
          });
          const index = keepAliveList.value.findIndex(
            (x: string) => x === router.currentRoute.value.name,
          );
          tagsStore.spliceTags(i);
          keepAliveStore.removeKeepAlive(index);
          if (activeKeyRef.value === targetKey) {
            const nowTag = getTabsState.value[i === 0 ? 0 : i - 1];
            if (nowTag) {
              router.push(nowTag.currentUrl ? nowTag.currentUrl : nowTag.fullPath);
            }
          }
        }

        if (unref(unClose)) {
          return;
        }
      }
      return {
        dealMenus,
        leftMenuTrigger,
        keepAliveList,
        loadingClass,
        reload,
        visible,
        unClose,
        handleEdit,
        handleChange,
        activeKeyRef,
        closeMenu,
        getTabsState,
      };
    },
  });
</script>
<style lang="less" scoped>
  #fullTab {
    width: 100% !important;
  }
  .iconLoading {
    color: @primary-color;
    margin-right: -4px;
    margin-left: 2px;
    font-size: 13px;
    animation: loadingCircle 1s linear;
  }
  :deep(.ant-tabs-tab-remove) {
    margin-left: 2px !important;
    font-size: 14px !important;
    margin-right: -8px;
  }
  .reload {
    color: rgba(0, 0, 0, 0.45);
    margin-right: -4px;
    margin-left: 2px;
    font-size: 13px;
    &:hover {
      color: @primary-color;
    }
  }
  .ns-tabs {
    width: calc(100% - 208px);
    padding: 0 12px;
    min-height: 32px;
    background: #ffffff;
    display: flex;
    align-items: center;
    position: fixed;
    top: @layout-header-height;
    z-index: 505;
  }
  #iframeApplication .ns-tabs {
    top: 0px;
  }

  .ns-tabs-collapsed {
    width: calc(100% - 40px);
    padding: 0 12px;
    min-height: 55px;
    background: #ffffff;
    display: flex;
    align-items: center;
    position: fixed;
    top: @layout-header-height;
    z-index: 505;
  }
  :deep(.ant-tabs-nav) {
    margin: 0px !important;
  }
  .contextmenu {
    margin: 0;
    min-width: 135px;
    background: #fff;
    z-index: 3000;
    position: absolute;
    list-style-type: none;
    padding: 5px 0;
    border-radius: 2px;
    font-size: 12px;
    font-weight: 400;
    color: #333;
    border-radius: 2px;
    outline: none;
    box-shadow: 0 2px 8px rgb(0 0 0 / 15%);
    li {
      margin: 0;
      padding: 7px 25px;
      cursor: pointer;
      &:hover {
        background: #eee;
      }
    }
  }
</style>
