<!-- @format -->

<template>
  <div
    class="nav-shutters-container"
    :class="leftMenuTrigger ? 'nav-shutters-collapsed' : 'nav-shutters'">
    <div class="shutters-left">
      <ns-icon
        @click.stop="moveTags('right')"
        :id="isdisabledr ? '' : 'disabled'"
        name="fastBackward"
        class="icon_kj" />
    </div>
    <div class="fatherTags">
      <ul id="tag-list" ref="tags">
        <div v-for="(item, index) in tagList" :key="index" @click="clickTag(item)">
          <li :id="selectTags.path === item.path ? 'ischoice' : ''">
            <a-dropdown :trigger="['contextmenu']" @visibleChange="(v) => visibleChange(v, item)">
              <span>
                {{ isdisabledl || isdisabledr ? item.title.substring(0, 4) : item.title }}
              </span>

              <template #overlay>
                <a-menu>
                  <a-menu-item key="1"> <li @click="closeAllMenu">关闭所有标签页</li></a-menu-item>
                  <a-menu-item key="2">
                    <li @click="closeOhterMenu">关闭其他标签页</li>
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
            <ns-icon
              v-if="item.path !== baseHeader.redirect"
              name="close"
              @click="delTags($event, item)" />
          </li>
        </div>
      </ul>
    </div>
    <div class="shutters-right">
      <ns-icon
        @click.stop="moveTags('left')"
        :id="isdisabledl ? '' : 'disabled'"
        name="fastBackward"
        class="icon_kt" />
    </div>
    <!-- <ul v-show="visible" :style="{ left: left + 'px', top: top + 'px' }" class="contextmenu">
      <li @click="closeAllMenu">关闭所有标签页</li>
      <li @click="closeOhterMenu">关闭其他标签页</li>
    </ul> -->
  </div>
</template>
<script lang="ts">
  import { computed, defineComponent, inject, ref } from 'vue';
  import { tagsClass } from '../application';
  import { useRouter } from 'vue-router';
  import { useKeepAlive } from '/nerv-base/store/modules/keepAlive';
  import { useTags } from '/nerv-base/store/modules/tags';
  import { Emitter } from 'mitt';
  import { emitEvents } from '/nerv-base/view/system/application.d';
  export default defineComponent({
    name: 'NsTags',
    setup() {
      const mittEmit = inject('mittEmit') as Emitter<emitEvents>;
      const visible = ref<boolean>(false);
      const leftMenuTrigger = ref(false);
      mittEmit.on('leftMenuTrigger', (val) => {
        leftMenuTrigger.value = val;
      });
      // const tagList = ref<tagsClass[]>([]);
      const rightNumber = ref<number>(0);
      const rightTarget = ref();
      const tagsStore = useTags();
      const router = useRouter();
      const keepAliveStore = useKeepAlive();
      const keepAliveList = computed(() => {
        return keepAliveStore.getKeepAlive;
      });
      const tagList = computed(() => tagsStore.getTags);
      //右键关闭所有标签页
      const closeAllMenu = () => {
        // tagsStore.sliceTags(0);
        tagsStore.clearTags();
      };
      //右键关闭其他标签页
      const closeOhterMenu = () => {
        // let choicetag = tagList.value[rightNumber.value];
        tagsStore.clearTags();
        tagsStore.addTags(rightTarget.value);
        clickTag(rightTarget.value);
      };
      const selectTags = inject('selectTags');
      const baseHeader = inject('baseHeader');
      const closeMenu = () => {
        visible.value = false;
      };
      const clickTag = (e: any) => {
        if (e.params) {
          router.push({
            name: e.name,
            query: e.params,
          });
        } else {
          router.push({
            name: e.name,
          });
        }
      };
      const visibleChange = (visible, target) => {
        if (visible) rightTarget.value = target;
      };
      return {
        visibleChange,
        leftMenuTrigger,
        router,
        clickTag,
        visible,
        tagList,
        tagsStore,
        selectTags,
        keepAliveStore,
        closeAllMenu,
        closeOhterMenu,
        closeMenu,
        baseHeader,
        keepAliveList,
        rightNumber,
        left: ref<number>(0),
        top: ref<number>(0),
        number: ref<number>(0),
        currentPage: ref<number>(0),
        isdisabledl: ref<boolean>(false),
        isdisabledr: ref<boolean>(false),
      };
    },
    watch: {
      tagList: {
        deep: true,
        handler() {
          this.resizeButtom();
        },
      },
      selectTags: {
        deep: true,
        handler(val) {
          this.delWithTags(val);
          this.move(val.path);
        },
      },
      visible(val) {
        val
          ? document.body.addEventListener('click', this.closeMenu)
          : document.body.removeEventListener('click', this.closeMenu);
      },
    },
    mounted() {
      this.delWithTags(this.selectTags);
      this.move(this.selectTags.path);
      this.resizeButtom();
      window.onresize = () => {
        this.resizeButtom();
      };
    },
    methods: {
      //处理tags
      delWithTags(val: any) {
        if (this.tagList.findIndex((item) => item.path === val.path) === -1) {
          // if (val.meta?.keepAlive) {
          //   if (this.keepAliveList.findIndex((x) => x === val.name) === -1) {
          //     this.keepAliveStore.addKeepAlive(val.name);
          //   }
          // }
          val.path === this.baseHeader.redirect
            ? this.tagsStore.unshiftTags({ title: val.meta.title, path: val.path, name: val.name })
            : this.tagsStore.addTags({ title: val.meta.title, path: val.path, name: val.name });
          this.$nextTick(() => {
            const arr = Array.prototype.slice.call((this.$refs.tags as HTMLElement).children);
            arr[arr.length - 1].id = 'moveIn';
          });
        }
      },
      openMenu(e: any, i: number) {
        e.preventDefault();
        if (i !== 0) {
          this.rightNumber = i;
          const menuMinWidth = 100;
          const offsetLeft = this.$el.getBoundingClientRect().left;
          const offsetTop = this.$el.getBoundingClientRect().top;
          let offset = 0;
          const str = (this.$refs.tags as HTMLElement).style.transform;
          if (str !== '') {
            offset = str.match(/\d+/)[0];
          }
          this.left = offsetLeft + menuMinWidth * (i - 1) - 30 - offset;
          this.top = offsetTop - 20;
          this.visible = true;
        }
      },
      delTags(e: { stopPropagation: () => void }, val: tagsClass) {
        e.stopPropagation();

        this.resizeButtom();
        let i = this.tagList.findIndex((x) => x.path === val.path);
        this.tagsStore.spliceTags(i);
        // const index = this.keepAliveList.value.findIndex(
        //   (x: string) => x === this.router.currentRoute.value.name,
        // );
        // this.keepAliveStore.removeKeepAlive(index);
        if (val.path === this.selectTags.path) {
          // this.selectTags.path = this.tagList[i === 0 ? 0 : i - 1].path;
          this.$router.push(this.tagList[i === 0 ? 0 : i - 1].path);
        }
      },
      moveTags(val: string) {
        switch (val) {
          case 'left':
            this.currentPage += 1;
            this.buttomRealize();
            break;
          case 'right':
            this.currentPage -= 1;
            this.buttomRealize();
            break;
        }
      },
      buttomRealize() {
        this.$nextTick(() => {
          const clientWidth = (this.$refs.tags as HTMLElement).clientWidth;
          this.number = Math.floor(clientWidth / 100);
          if (this.number * this.currentPage >= this.tagList.length) {
            let multiple = Math.floor(this.tagList.length / this.number);
            this.currentPage =
              multiple !== 0 && this.number * multiple === this.tagList.length
                ? multiple - 1
                : multiple;
          }
          (this.$refs.tags as HTMLElement).style.cssText = `transform: translateX(${
            -this.number * 100 * this.currentPage
          }px)`;
          this.isdisabledl = (this.currentPage + 1) * this.number < this.tagList.length;
          this.isdisabledr = this.currentPage > 0;
        });
      },
      move(val: string) {
        this.$nextTick(() => {
          const clientWidth = (this.$refs.tags as HTMLElement).clientWidth;
          this.number = Math.floor(clientWidth / 100);
          const index = this.tagList.findIndex((x: tagsClass) => x.path === val) + 1;
          if (index !== 0) {
            let multiple = Math.floor(index / this.number);
            multiple = index % this.number === 0 ? multiple - 1 : multiple;
            this.moveRealize(index, multiple);
            this.changeButtom(index, multiple);
          }
        });
      },
      moveRealize(index: number, multiple: number) {
        index > this.number
          ? ((this.$refs.tags as HTMLElement).style.cssText = `transform: translateX(${
              this.number * 100 * -multiple
            }px)`)
          : ((this.$refs.tags as HTMLElement).style.cssText = `transform: translateX(${
              this.number * 100 * (index === this.number ? 0 : multiple)
            }px)`);
      },
      resizeButtom() {
        this.$nextTick(() => {
          if (this.$refs.tags !== undefined) {
            const clientWidth = (this.$refs.tags as HTMLElement).clientWidth;
            if (this.currentPage === 0) {
              this.isdisabledl = this.tagList.length * 100 > clientWidth;
            } else {
              this.isdisabledl =
                (this.tagList.length - this.number * this.currentPage) * 100 > clientWidth;
              if (this.tagList.length * 100 < clientWidth) {
                (this.$refs.tags as HTMLElement).style.cssText = `transform: translateX(${0}px)`;
                this.isdisabledr = false;
                this.currentPage = 0;
              }
            }
          }
        });
      },
      changeButtom(index: number, multiple: number) {
        if (index !== this.number * multiple) {
          this.isdisabledl = this.tagList.length > (multiple + 1) * this.number;
          this.isdisabledr = multiple > 0;
          this.currentPage = multiple;
        }
      },
    },
  });
</script>

<style lang="less" scoped>
  .nav-shutters {
    width: calc(100% - @layout-sider-width);
    // padding: 0 12px;
    min-height: @ns-nav-shutters-height;
    height: @ns-nav-shutters-height;
    background: @white;
    display: flex;
    align-items: center;
    position: fixed;
    top: @layout-header-height;
    z-index: 6;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  }
  .nav-shutters-collapsed {
    width: calc(100% - @layout-sider-collapsed-width);
    // padding: 0 12px;
    min-height: @ns-nav-shutters-height;
    height: @ns-nav-shutters-height;
    background: @white;
    display: flex;
    align-items: center;
    position: fixed;
    top: @layout-header-height;
    z-index: 10;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  }
  .nav-shutters-container {
    display: flex;
    align-items: center;
  }
  .shutters-left {
    height: @ns-nav-shutters-height;
    width: @ns-nav-shutters-height;
    border-right: 1px solid #f0f2f5;
    min-width: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    .icon_kj {
      mix-blend-mode: normal;
      cursor: pointer;
      // width: 12px !important;
      // height: 12px !important;
    }
  }
  .shutters-right {
    height: @ns-nav-shutters-height;
    width: @ns-nav-shutters-height;
    border-left: 1px solid #f0f2f5;
    cursor: pointer;
    min-width: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    .icon_kt {
      cursor: pointer;
      // width: 12px !important;
      // height: 12px !important;
      transform: rotateY(180deg);
    }
  }
  #disabled {
    pointer-events: none;
    cursor: default;
    opacity: 0.524902;
  }

  .fatherTags {
    flex: 1;
    // width: calc(100% - 64px);
    height: @ns-nav-shutters-height;
    min-width: 400px;
    overflow: hidden;
  }
  #moveIn {
    animation: move-in 0.5s;
  }

  #tag-list {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: left;
    list-style-type: none;
    padding: 0;
    transition: transform 1s;

    a:hover {
      background: #f5f9fb;
      color: @layout-sider-arrow-color;
    }
    /* will-change: transform; 增
  加动画流畅度但较耗性能，推荐动态添加该属性 动画执行完再去除该属性 */
    li {
      min-width: 100px;
      padding: 0 5px 0 16px;
      text-align: center;
      justify-content: center;
      display: flex;
      align-items: center;
      border-right: 1px solid #ecedef;
      cursor: pointer;
      font-size: 14px;
      height: 100%;
      color: #808d96;
      span {
        font-size: 14px;
        color: @text-color-secondary;
        margin-right: 6px;
        height: 20px;
        overflow: hidden;
      }
    }
  }
  @keyframes move-in {
    0% {
      transform: translateY(-50px);
      opacity: 0;
    }
    100% {
      transform: translateY(0px);
      opacity: 1;
    }
  }
  #ischoice {
    // background-color: #f5f9fb;
    position: relative;
    &::after {
      position: absolute;
      content: '';
      bottom: 0;
      width: 30%;
      height: 3px;
      background-color: @primary-color;
      left: 50%;
      transform: translateX(-50%);
    }
  }
  #ischoice span {
    color: @primary-color !important;
  }
  .checkBox {
    height: 200px;
    width: 100px;
    background-color: #fff;
    box-shadow: 1px 3px 3px 0px #b5deff;
    border-radius: 5px;
    position: absolute;
    left: 599px;
    top: 99px;
    z-index: 999;
  }
  .contextmenu {
    margin: 0;
    min-width: 135px;
    background: #fff;
    z-index: 3000;
    position: absolute;
    list-style-type: none;
    padding: 5px 0;
    border-radius: @border-radius-base;
    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;
      }
    }
  }
  @keyframes move-down {
    0% {
      transform: translateY(-50px) scale(0);
      opacity: 0;
    }
    100% {
      transform: translateY(0px) scale(1);
      opacity: 1;
    }
  }
  .tagTitle {
    max-width: 56px;
    text-align: center;
    overflow: hidden;
    white-space: nowrap;
    transition: all 1.5s;
  }
</style>
