<template>
  <div
    id="tabs-bar-container"
    class="tabs-bar-container"
    :class="{ 'is-horizontal': layout === 'horizontal' }"
    :style="{
      background: variables[`${style}-top-bar-background`],
      '--borderColor': variables[`${style}-container-background`],
    }"
  >
    <el-tabs
      v-model="tabActive"
      type="card"
      class="tabs-content"
      :style="{
        '--color': variables[`${style}-tab-color`],
      }"
      @tab-click="handleTabClick"
      @tab-remove="handleTabRemove"
    >
      <el-tab-pane
        v-for="item in visitedMenus"
        :key="item.id"
        :label="item.name"
        :name="item.id"
        :closable="isCloseable"
      ></el-tab-pane>
    </el-tabs>

    <!-- 获取系统最新布局 -->
    <div v-if="isShowDefaultLayoutBtn" class="layout-content">
      <el-button class="new-layout add-column" @click="handleAddColumn">
        <i class="icon-f-plus"></i>
        添加栏目
      </el-button>
      <el-button
        v-if="isNewLayout || isDragColumn"
        class="new-layout"
        @click="getDefaultLayout"
      >
        <span class="btn-text">获取最新门户</span>
      </el-button>
    </div>

    <ul
      v-if="contextMenuVisible"
      :style="{ left: left + 'px', top: '108px' }"
      class="context-menu"
    >
      <li class="context-menu-item">
        <el-button type="text" @click="handleOperateTabs('all')">
          关闭全部标签页
        </el-button>
      </li>
      <li class="context-menu-item">
        <el-button
          type="text"
          :disabled="isDisabledCloseLeftBtnFlag"
          @click="handleOperateTabs('left')"
        >
          关闭左侧标签页
        </el-button>
      </li>
      <li class="context-menu-item">
        <el-button
          type="text"
          :disabled="isDisabledCloseRightBtnFlag"
          @click="handleOperateTabs('right')"
        >
          关闭右侧标签页
        </el-button>
      </li>
      <li class="context-menu-item">
        <el-button type="text" @click="handleOperateTabs('other')">
          关闭其他标签页
        </el-button>
      </li>
    </ul>
  </div>
</template>

<script>
  import portal from '@/api/portal'
  import { mapGetters } from 'vuex'
  import variables from '@/styles/variables.scss'
  export default {
    name: 'HtTabsBar',
    data() {
      return {
        affixtabs: [],
        tabActive: '',
        contextMenuVisible: false,
        isDisabledCloseLeftBtnFlag: true,
        isDisabledCloseRightBtnFlag: true,
        left: 0,
        top: 0,
        isNewLayout: false,
        isDragColumn: false,
        defaultMune: [
          {
            name: '/personal/message',
            store: 'settings/changeMessageColor',
          },
          {
            name: '/personal/mail',
            store: 'settings/changeEmailColor',
          },
        ],
        defaultPerMun: [
          '/personal/security',
          '/personal/information',
          '/personal/setting',
        ],
        winUrl: '',
        currentActiveName: '',
        clickTabIndex: -1,
      }
    },
    computed: {
      ...mapGetters({
        visitedMenus: 'app/visitedMenus',
        activeMenu: 'app/activeMenu',
        routes: 'routes/routes',
        style: 'app/style',
        layout: 'app/layout',
      }),
      variables() {
        return variables
      },
      isShowDefaultLayoutBtn() {
        const { path, meta } = this.$route
        return ['/index', '/index/', '/Index'].includes(path) || meta.index
      },
      isDisabled() {
        const index = this.routes.findIndex(
          (item) => ['/'].includes(item.path) && item.meta
        )
        const findCurrentLayoutIsNew = this.routes[index].children.find(
          (it) => it.meta.alias === this.$route.meta.alias
        )
        return !(findCurrentLayoutIsNew && findCurrentLayoutIsNew.isNew)
      },
      isCloseable() {
        return this.visitedMenus.length > 1
      },
    },
    watch: {
      activeMenu(val) {
        this.tabActive = val?.id
      },
      contextMenuVisible() {
        if (this.contextMenuVisible) {
          document.body.addEventListener('click', this.closeContextMenu)
        } else {
          document.body.removeEventListener('click', this.closeContextMenu)
        }
      },
    },
    mounted() {
      this.tabActive = this.activeMenu ? this.activeMenu.id : ''
      this.bindRightClickMenu()
      const layoutId = sessionStorage.getItem('layoutId')
      const localIsNewLayout = localStorage.getItem(`isNewLayout_${layoutId}`)
      const localIsDragColumn = localStorage.getItem(`isDragColumn_${layoutId}`)
      this.isNewLayout = localIsNewLayout ? JSON.parse(localIsNewLayout) : false
      this.isDragColumn = localIsDragColumn
        ? JSON.parse(localIsDragColumn)
        : false
      this.initListener()
    },
    destroyed() {
      window.removeEventListener('storage', () => {})
    },
    methods: {
      getDefaultLayout() {
        const layoutId = sessionStorage.getItem('layoutId')
        if (layoutId) {
          this.$confirm('确认获取最新门户布局吗?', '提示', {
            type: 'warning',
            closeOnClickModal: false,
          })
            .then(() => {
              const layouConfig = {
                layoutId,
                configContent: JSON.stringify({}),
                isReset: true,
              }
              portal.setLayoutConfig(layouConfig).then(() => {
                this.$message.success('获取最新布局成功')
                this.isNewLayout = false
                this.isDragColumn = false
                this.$baseEventBus.$emit('get-layout-config')
              })
            })
            .catch(() => {})
        } else {
          this.$message.error('当前布局id为空，无法获取最新布局！')
        }
      },
      handleAddColumn() {
        const layoutId = sessionStorage.getItem('layoutId')
        this.$baseEventBus.$emit('add-column', layoutId)
      },
      handleTabRemove(tabActive) {
        let view
        this.visitedMenus.forEach((item) => {
          if (tabActive === item.id) {
            view = item
          }
        })
        this.closeSelectedTab(view)
      },
      handleTabClick(tab) {
        this.selectTabById(tab.name)
        // let activeMenu = this.visitedMenus.find((item) => tab.name === item.id)
        // this.$store.dispatch('app/setActiveMenu', activeMenu)
      },
      selectTabById(id) {
        let activeMenu = this.visitedMenus.find((item) => id === item.id)
        this.$store.dispatch('app/setActiveMenu', activeMenu)
      },
      isActive(view) {
        return view.id === this.activeMenu.id
      },
      handleOperateTabs(type) {
        switch (type) {
          case 'other':
            this.closeOtherTabs()
            break
          case 'left':
            this.closeLeftTabs()
            break
          case 'right':
            this.closeRightTabs()
            break
          case 'all':
            this.closeAllTabs()
            break
        }
        this.contextMenuVisible = false
      },
      async closeSelectedTab(view) {
        await this.$store.dispatch('app/delVisitedMenus', view)
        if (this.isActive(view)) {
          this.toLastTag(this.visitedMenus, view)
        }
      },
      async closeOtherTabs() {
        let view = this.rightClickSelectedTab()
        await this.$store.dispatch('app/delOtherMenus', view)
        if (!this.isActive(view)) {
          this.$store.dispatch('app/setActiveMenu', view)
        }
      },
      async closeLeftTabs() {
        const view = this.rightClickSelectedTab()
        await this.$store.dispatch('app/delLeftMenus', this.clickTabIndex)
      },
      async closeRightTabs() {
        const view = this.rightClickSelectedTab()
        await this.$store.dispatch('app/delRightMenus', this.clickTabIndex)
      },
      async closeAllTabs() {
        const view = await this.toThisTag()
        await this.$store.dispatch('app/delAllVisitedMenus')
        this.toLastTag(this.visitedMenus, view)
      },
      toLastTag(visitedMenus, view) {
        const latestView = visitedMenus.slice(-1)[0]
        this.$store.dispatch('app/setActiveMenu', latestView)
      },
      async toThisTag() {
        return this.activeMenu
      },
      rightClickSelectedTab() {
        return this.visitedMenus.find(
          (menu) => menu.id === this.currentActiveName
        )
      },
      bindRightClickMenu() {
        const tabsDom = document.getElementById('tabs-bar-container')
        let tabsHeaderDom = tabsDom.getElementsByClassName(
          'el-tabs__header is-top'
        )
        tabsHeaderDom[0].oncontextmenu = this.handleClickContextMenu
      },
      handleClickContextMenu(e) {
        e.preventDefault()
        this.currentActiveName = e.target.id.split('-')[1]
        if (this.currentActiveName) {
          this.contextMenuVisible = true
          this.left = e.clientX - 24
          this.top = e.clientY - 10
          this.clickTabIndex = this.visitedMenus.findIndex(
            (item) => item.id === this.currentActiveName
          )
          if (this.clickTabIndex <= 0) {
            this.isDisabledCloseLeftBtnFlag = true
            this.isDisabledCloseRightBtnFlag = false
          } else if (this.clickTabIndex >= this.visitedMenus.length - 1) {
            this.isDisabledCloseLeftBtnFlag = false
            this.isDisabledCloseRightBtnFlag = true
          } else {
            this.isDisabledCloseLeftBtnFlag = false
            this.isDisabledCloseRightBtnFlag = false
          }
          this.contextMenuVisible = true
        }
      },
      closeContextMenu() {
        this.contextMenuVisible = false
      },
      initListener() {
        window.addEventListener('storage', (value) => {
          if (value.key === 'close-tab') {
            this.closeSelectedTab(this.activeMenu)
          }
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  $base-padding: 24px;
  @mixin tabs-item-bg {
    mask: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAANoAAAAkBAMAAAAdqzmBAAAAMFBMVEVHcEwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlTPQ5AAAAD3RSTlMAr3DvEM8wgCBA379gj5//tJBPAAAAnUlEQVRIx2NgAAM27fj/tAO/xBsYkIHyf9qCT8iWMf6nNQhAsk2f5rYheY7Dnua2/U+A28ZEe8v+F9Ax2v7/F4DbxkUH2wzgtvHTwbYPo7aN2jZq26hto7aN2jZq25Cy7Qvctnw62PYNbls9HWz7S8/G6//PsI6H4396gAUQy1je08W2jxDbpv6nD4gB2uWp+J9eYPsEhv/0BPS1DQBvoBLVZ3BppgAAAABJRU5ErkJggg==);
    mask-size: 100% 100%;
  }
  .tabs-bar-container {
    position: relative;
    box-sizing: border-box;
    display: flex;
    align-content: center;
    // align-items: center;
    justify-content: space-between;
    height: $base-tabs-bar-height;
    padding-right: $base-padding;
    padding-left: $base-padding;
    user-select: none;
    // border-top: 1px solid var(--borderColor);
    margin-top: 1px;

    ::v-deep {
      .fold-unfold {
        margin-right: $base-padding;
      }
    }

    .tabs-content {
      width: calc(100% - 150px);
      height: $base-tabs-item-height;
      margin-top: calc(#{$base-tabs-bar-height} - #{$base-tabs-item-height});
      ::v-deep {
        .el-tabs__nav-next,
        .el-tabs__nav-prev {
          height: $base-tabs-item-height;
          line-height: $base-tabs-item-height;
        }

        .el-tabs__header {
          border-bottom: 0;
          margin: 0;

          .el-tabs__nav {
            border: 0;
          }

          .el-tabs__item {
            box-sizing: border-box;
            height: $base-tabs-item-height;
            margin-right: 5px;
            line-height: $base-tabs-item-height;
            border: none;
            color: var(--color);
            border-radius: 4px 4px 0 0;
            transition: padding 0.3s cubic-bezier(0.645, 0.045, 0.355, 1) !important;

            &.is-active {
              border: none;
              color: var(--themeColor);
              @include tabs-item-bg;
            }
            &:hover {
              color: var(--themeColor);
              @include tabs-item-bg;
              background-color: $base-tabs-item-hover-bg;
            }
          }
        }
      }
    }

    .layout-content {
      height: $base-tabs-bar-height;
      display: flex;
      align-items: center;
      .new-layout {
        display: flex;
        align-items: center;
        font-size: $base-font-size-default;
        padding: 7px 14px 7px 28px;
        border: 1px solid #dcdee0;
        border-radius: $base-border-radius;
        // color: $base-font-color;
        .circle {
          display: inline-block;
          width: 6px;
          height: 6px;
          margin-right: 7px;
          border-radius: 50%;
          background: $base-color-red;
        }
        .text {
          color: $base-font-color;
          font-size: $base-font-size-default;
        }
        .btn-text {
          position: relative;
          &::before {
            position: absolute;
            content: '';
            width: 6px;
            height: 6px;
            border-radius: 50%;
            left: -14px;
            top: 5px;
            background: $base-color-red;
          }
        }
      }
      .add-column {
        padding-left: 14px;
      }
      ::v-deep {
        .el-button {
          color: $base-dark-title-color;
        }
        .is-disabled {
          color: #c0c4cc;
          padding: 7px 14px;
        }
      }
    }

    .context-menu {
      width: 122px;
      background: $base-color-white;
      position: fixed;
      z-index: 99;
      padding: 4px 0;
      border-radius: 2px;
      box-shadow: 0px 1px 6px rgba(91, 91, 91, 0.15);
      text-align: center;
      .context-menu-item {
        ::v-deep {
          .el-button--text {
            color: $base-color-second-color;
            font-size: 14px;
            padding: 6px 10px;
            &:hover {
              color: var(--themeColor);
              background: #f9f9f9;
            }
          }
          .is-disabled {
            color: #ccc;
            &:hover {
              color: #ccc;
              background: $base-color-white;
            }
          }
        }
      }
    }
    .more {
      display: flex;
      align-content: center;
      align-items: center;
      cursor: pointer;
    }
  }
  .is-horizontal {
    width: 92% !important;
    margin: auto;
  }
</style>
