<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 visitedRoutes"
        :key="item.path"
        :label="item.meta.title"
        :name="item.path"
        :closable="!isAffix(item)"
      ></el-tab-pane>
    </el-tabs>


    <!-- 获取系统最新布局 -->
    <div  class="layout-content">
      <el-button class="new-layout add-column" @click="handleAddOrder">
        <i class="icon-f-plus"></i>
        添加订单
      </el-button>
    </div>

<!--    &lt;!&ndash; 获取系统最新布局 &ndash;&gt;-->
<!--    <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>
      <li
        v-if="tabActive == currentActiveName"
        class="context-menu-item copy-btn"
        :data-clipboard-text="winUrl"
        @click="copyCurrentUrl()"
      >
        <el-button type="text">复制当前链接</el-button>
      </li>
    </ul>
  </div>
</template>

<script>
  import Clipboard from 'clipboard'
  import path from 'path'
  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: '',
      }
    },
    computed: {
      ...mapGetters({
        visitedRoutes: 'tabsBar/visitedRoutes',
        routes: 'routes/routes',
        style: 'settings/style',
        layout: 'settings/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
          ? false
          : true
      },
    },
    watch: {
      $route: {
        handler(route) {
          this.inittabs()
          this.addtabs()
          let tabActive = ''
          this.visitedRoutes.forEach((item, index) => {
            if (item.path === this.$route.path) {
              tabActive = item.path
            }
          })
          this.tabActive = tabActive
          if(this.$route.path == '/' && tabActive == '' && this.visitedRoutes.length > 0){
            //登录后跳转到第一个菜单页
            let itemActive = this.visitedRoutes[this.visitedRoutes.length - 1]
            this.tabActive = itemActive.path
            this.$router.push({
              path: itemActive.path,
              query: itemActive.query,
              fullPath: itemActive.fullPath,
            })
            this.$store.dispatch('tabsBar/delOthersVisitedRouteAll', itemActive)
          }
        },
        immediate: true,
      },
      contextMenuVisible() {
        if (this.contextMenuVisible) {
          document.body.addEventListener('click', this.closeContextMenu)
        } else {
          document.body.removeEventListener('click', this.closeContextMenu)
        }
      },
      tabActive: {
        handler(val) {
          //点亮图标
          this.defaultMune.forEach((item) => {
            if (item.name == val) {
              this.$store.commit(item.store, true)
            } else {
              this.$store.commit(item.store, false)
            }
          })
          //个人信息菜单
          this.defaultPerMun.includes(val)
            ? this.$store.commit('settings/changeshowAllRoutes', false)
            : this.$store.commit('settings/changeshowAllRoutes', true)
        },
        immediate: true,
      },
    },
    mounted() {
      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.$baseEventBus.$on('change-layout', (data) => {
        this.isNewLayout = data.isNewLayout
        this.isDragColumn = data.isDragColumn || false
      })
    },
    methods: {
      handleAddOrder(){
        this.$router.push('/addOrder')
      },
      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)
      },
      async handleTabRemove(tabActive) {
        let view
        this.visitedRoutes.forEach((item, index) => {
          if (tabActive == item.path) {
            view = item
          }
        })
        const { visitedRoutes } = await this.$store.dispatch(
          'tabsBar/delRoute',
          view
        )
        if (this.isActive(view)) {
          this.toLastTag(visitedRoutes, view)
        }
        //当是关闭邮箱时 取消高亮
        if ((tabActive = '/personal/mail')) {
          this.$store.commit('settings/changeEmailColor', false)
        }
      },
      handleTabClick(tab) {
        const route = this.visitedRoutes.filter((item, index) => {
          if (tab.index == index) return item
        })[0]
        if (this.$route.path !== route.path) {
          this.$router.push({
            path: route.path,
            query: route.query,
            fullPath: route.fullPath,
          })
        } else {
          return false
        }
      },
      isActive(route) {
        return route.path === this.$route.path
      },
      isAffix(tag) {
        return tag.meta && tag.meta.affix
      },
      filterAffixtabs(routes, basePath = '/') {
        let tabs = []
        routes.forEach((route) => {
          if (route.meta && route.meta.affix) {
            const tagPath = path.resolve(basePath, route.path)
            tabs.push({
              fullPath: tagPath,
              path: tagPath,
              name: route.name,
              meta: { ...route.meta },
            })
          }
          if (route.children) {
            const temptabs = this.filterAffixtabs(route.children, route.path)
            if (temptabs.length >= 1) {
              tabs = [...tabs, ...temptabs]
            }
          }
        })
        return tabs
      },
      inittabs() {
        const affixtabs = (this.affixtabs = this.filterAffixtabs(this.routes))
        for (const tag of affixtabs) {
          if (tag.name) {
            this.$store.dispatch('tabsBar/addVisitedRoute', tag)
          }
        }
      },
      addtabs() {
        const { name } = this.$route
        if (name) {
          this.$store.dispatch('tabsBar/addVisitedRoute', this.$route)
        }
        return false
      },
      handleOperateTabs(type) {
        switch (type) {
          case 'refreshRoute':
            this.refreshRoute()
            break
          case 'other':
            this.closeOtherstabs()
            break
          case 'left':
            this.closeLefttabs()
            break
          case 'right':
            this.closeRighttabs()
            break
          case 'all':
            this.closeAlltabs()
            break
        }
        this.contextMenuVisible = false
      },
      async refreshRoute() {
        this.$baseEventBus.$emit('reload-router-view')
      },
      async closeSelectedTag(view) {
        const { visitedRoutes } = await this.$store.dispatch(
          'tabsBar/delRoute',
          view
        )
        if (this.isActive(view)) {
          this.toLastTag(visitedRoutes, view)
        }
      },
      async closeOtherstabs() {
        const view = await this.toThisTag()
        await this.$store.dispatch('tabsBar/delOthersRoutes', view)
      },
      async closeLefttabs() {
        const view = await this.toThisTag()
        await this.$store.dispatch('tabsBar/delLeftRoutes', view)
      },
      async closeRighttabs() {
        const view = await this.toThisTag()
        await this.$store.dispatch('tabsBar/delRightRoutes', view)
      },
      async closeAlltabs() {
        const view = await this.toThisTag()
        const { visitedRoutes } = await this.$store.dispatch(
          'tabsBar/delAllRoutes'
        )
        if (this.affixtabs.some((tag) => tag.path === view.path)) {
          return
        }
        this.toLastTag(visitedRoutes, view)
      },
      toLastTag(visitedRoutes, view) {
        const latestView = visitedRoutes.slice(-1)[0]
        if (latestView) {
          this.$router.push({ path: latestView.fullPath })
        } else {
          this.$router.push('/')
        }
      },
      async toThisTag() {
        const view = this.visitedRoutes.filter((item, index) => {
          if (
            item.path === this.$route.fullPath ||
            item.fullPath === this.$route.fullPath
          ) {
            return item
          }
        })[0]
        if (this.$route.path !== view.path) this.$router.push(view)
        return view
      },
      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 (e.srcElement.id) {
          const currentContextTabId = e.srcElement.id.split('-')[1]
          this.contextMenuVisible = true
          this.left = e.clientX - 24
          this.top = e.clientY - 10
          const clickTabIndex = this.visitedRoutes.findIndex(
            (item) => item.path === currentContextTabId
          )
          if (clickTabIndex <= 0) {
            this.isDisabledCloseLeftBtnFlag = true
            this.isDisabledCloseRightBtnFlag = true
          } else if (clickTabIndex >= this.visitedRoutes.length - 1) {
            this.isDisabledCloseLeftBtnFlag = false
            this.isDisabledCloseRightBtnFlag = true
          } else {
            this.isDisabledCloseLeftBtnFlag = false
            this.isDisabledCloseRightBtnFlag = false
          }
          this.contextMenuVisible = true
        }
      },
      closeContextMenu() {
        this.contextMenuVisible = false
      },
      copyCurrentUrl() {
        this.handlerWinUrl()
        let clipboard = new Clipboard('.copy-btn')
        clipboard.on('success', (e) => {
          clipboard.destroy()
        })
        clipboard.on('error', () => {
          clipboard.destroy()
        })
      },
      handlerWinUrl() {
        let url = window.location.href
        if (url.includes('?')) {
          url = `${url}&__isFull__=true`
        } else {
          url = `${url}?__isFull__=true`
        }
        this.winUrl = url
      },
    },
  }
</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>
