<template>
  <div class="top-bar-container">
    <div
      class="top-bar-main"
      :style="{ background: variables[`${style}-menu-background`] }"
    >
      <el-row class="top-bar-row">
        <el-col
          :xl="3"
          :lg="6"
          :md="6"
          :sm="6"
          :xs="6"
          class="top-bar-row-logo"
        >
          <ht-logo class="logo-padding" />
        </el-col>
        <el-col
          :xl="16"
          :lg="13"
          :md="13"
          :sm="13"
          :xs="13"
          class="top-bar-center"
        >
          <!-- <div v-show="menuLeft < 0" class="menu-left" @click="leftClick">
            <i class="el-icon-arrow-left"></i>
          </div> -->
          <div ref="menuScroll" class="menu-scroll menu-wrap">
            <el-menu
              id="menuContentRef"
              :background-color="variables[`${style}-menu-background`]"
              :text-color="variables[`${style}-menu-color`]"
              :active-text-color="themeColor"
              :style="{
                '--menuBgColor': variables[`${style}-menu-background`],
                left: menuLeft + 'px',
              }"
              :default-active="activeMenu"
              mode="horizontal"
              menu-trigger="hover"
            >
              <template v-for="route in currentShowMenu">
                <ht-side-bar-item
                  v-if="!route.hidden"
                  :key="route.id"
                  :full-path="route.path"
                  :item="route"
                />
              </template>
            </el-menu>
          </div>

          <!-- <div v-show="showRightIcon" class="menu-right" @click="rightClick">
            <i class="el-icon-arrow-right"></i>
          </div> -->
        </el-col>
        <el-col :xl="5" :lg="5" :md="5" :sm="5" :xs="5" class="top-bar-right">
          <div
            class="right-panel"
            :style="{
              '--topRightColor': variables[`${style}-top-right-color`],
            }"
          >
            <i v-if="showPortalApp" @click="meunClick">
              <img
                :src="`data:image/svg+xml;base64,${src}`"
                alt=""
                width="18"
                height="18"
              />
            </i>
            <ht-message
              :message-count="messageCount"
              @msg-click="linkToMessage"
            ></ht-message>
            <ht-full-screen-bar @refresh="refreshRoute" />
            <!-- <ht-apps /> -->
            <!-- <ht-error-log /> -->
            <ht-theme-bar class="hidden-md-and-down" />
            <i
              :style="{
                color: $store.state.settings.emailColor
                  ? 'var(--themeColor)'
                  : '',
              }"
              class="icon-mail-unread header-btn-icon iconEmail"
              @click="emailClick"
            ></i>
            <el-divider direction="vertical"></el-divider>
            <ht-avatar />
          </div>
        </el-col>
      </el-row>
    </div>

    <el-dialog
      append-to-body
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="1200px"
      top="45px"
      class="elDialog"
      custom-class="batch-box"
    >
      <AppSelector></AppSelector>
    </el-dialog>
  </div>
</template>

<script>
  import variables from '@/styles/variables.scss'
  import { mapGetters, mapState } from 'vuex'
  import setMenuMark from '@/mixins/setMenuMark'
  import { yyzx } from '@/icon/index.js'
  import { portalApp } from '@/api/portal.js'
  import AppSelector from '@/views/app/center/AppSelector.vue'
  export default {
    name: 'HtTopBar',
    components: { AppSelector },
    mixins: [setMenuMark],
    data() {
      return {
        menuTrigger: 'hover',
        menuLeft: 0,
        showRightIcon: true,
        showPortalApp: false,
        MessageIcon: false,
        showEmailCenter: false,
        defFirMun: ['//appCenter', '//personal', '/personal', '/appCenter'],
        src: yyzx,
        dialogVisible: false,
        perList: [],
      }
    },

    computed: {
      ...mapGetters({
        messageCount: 'navHeader/getUnreadMsgCount',
        style: 'settings/style',
        routes: 'routes/routes',
        themeColor: 'settings/themeColor',
        visitedRoutes: 'tabsBar/visitedRoutes',
      }),
      ...mapState('routes', ['menus']),
      activeMenu() {
        const route = this.$route
        const { meta, path } = route
        if (meta.activeMenu) {
          return meta.activeMenu
        }
        return path
      },
      variables() {
        return variables
      },
      newRoutesChange() {
        return _.cloneDeep(
          this.newRoutes.filter((item) => {
            return !this.defFirMun.includes(item.path)
          })
        )
      },
      getMenuShowNumIndex() {
        let index = 6
        if (window.screen.width < 1512) {
          index = 3
        } else if (window.screen.width >= 1512 && window.screen.width < 1920) {
          index = 4
        } else {
          index = 6
        }
        return index
      },
      currentShowMenu() {
        //过滤应用中心和个人中心
        let filtermenu = this.menus.filter((item) => {
          let routeExtend = item && item.routeExtend && JSON.parse(item.routeExtend) && JSON.parse(item.routeExtend).path
          return !this.defFirMun.includes(routeExtend)
        })
        const menu = filtermenu.find(
          (item, index) => index === this.getMenuShowNumIndex
        )
        let newRoutes = this.newRoutes.filter((item) => {
          return !this.defFirMun.includes(item.path)
        })
        if (!menu) return newRoutes
        const menuIndex = newRoutes.findIndex((it) => {
          return menu && menu.alias === it.alias
        })
        const currentMenuList = newRoutes.filter(
          (menu, index) => index <= menuIndex
        )
        const otherMenus = newRoutes.filter((menu, index) => index > menuIndex)
        if (otherMenus && otherMenus.length > 0) {
          currentMenuList.push({
            alwaysShow: true,
            children: otherMenus,
            name: 'moreMenu',
            meta: {
              icon: 'icon-gengduo2',
              title: 'moreMenu',
              menuLevel: 'first',
            },
            path: '/more',
            type: 'catalog',
          })
        }
        return currentMenuList
      },
    },
    mounted() {
      this.$store.dispatch('navHeader/setUnreadMsgCount')
      portalApp().then((res) => {
        if (res && res.length > 0) {
          res.forEach((item) => {
            if (item.alias == 'Message') {
              this.MessageIcon = true
            }
            if (item.alias == 'AppCenter') {
              this.showPortalApp = true
            }
            if (item.alias == 'EmailCenter') {
              this.showEmailCenter = true
            }
          })
        }
      })
      // this.$root.$on('resize', () => {
      //   this.$nextTick(() => {
      //     this.initMenuScroll()
      //   })
      // })
      // this.initMenuScroll()
    },
    methods: {
      emailClick() {
        this.$router.push('/personal/mail')
      },
      meunClick() {
        this.dialogVisible = true
      },
      async refreshRoute() {
        this.$baseEventBus.$emit('reload-router-view')
      },
      async initMenuScroll() {
        if (!this.$refs.menuScroll) {
          await this.awaitOneSecond()
        }
        const lookWidth = this.$refs.menuScroll.clientWidth
        const totalWidth = document.getElementById('menuContentRef').scrollWidth
        let rightSurplus = totalWidth - Math.abs(this.menuLeft) - lookWidth
        this.showRightIcon = rightSurplus > 0
      },
      awaitOneSecond() {
        return new Promise((resolve) => {
          setTimeout(() => {
            resolve()
          }, 1000)
        })
      },
      // 点击右箭头（左侧滚动）
      rightClick() {
        // 获取可视区域宽度
        const lookWidth = this.$refs.menuScroll.clientWidth
        const totalWidth = document.getElementById('menuContentRef').scrollWidth
        let rightSurplus = totalWidth - Math.abs(this.menuLeft) - lookWidth
        let percentOffest = lookWidth * 0.5
        if (rightSurplus > 0) {
          this.menuLeft -=
            rightSurplus >= percentOffest ? percentOffest : rightSurplus
          if (totalWidth - Math.abs(this.menuLeft) - lookWidth <= 0) {
            this.showRightIcon = false
          }
        } else {
          this.showRightIcon = false
        }
      },
      // 点击左箭头（右侧滚动）
      leftClick() {
        // 获取可视区域宽度
        const lookWidth = this.$refs.menuScroll.clientWidth
        const totalWidth = document.getElementById('menuContentRef').scrollWidth
        let percentOffest = lookWidth * 0.5
        let rightSurplus = totalWidth - Math.abs(this.menuLeft) - lookWidth
        if (Math.abs(this.menuLeft) > 0) {
          this.menuLeft +=
            Math.abs(this.menuLeft) >= percentOffest
              ? percentOffest
              : Math.abs(this.menuLeft)
          this.showRightIcon = true
        }
        if (rightSurplus > 0) {
          this.showRightIcon = true
        }
      },
      linkToMessage() {
        this.$router.push('/personal/message')
      },
    },
  }
</script>
<style lang="scss" scoped>
  @mixin dot-border-color {
    border-color: var(--themeColor);
  }
  @mixin more-submenu-style($color) {
    .sub-menu-title,
    .ht-fa-icon,
    .el-submenu__icon-arrow {
      color: var($color) !important;
    }
  }
  @mixin menu-arrow($degree) {
    .el-submenu__icon-arrow {
      transform: rotateZ($degree);
    }
  }
  .top-bar-container {
    display: flex;
    align-items: center;
    justify-items: flex-end;
    height: $base-top-bar-height;

    .top-bar-main {
      width: $base-full-width;

      .top-bar-row {
        width: 92% !important;
        margin: auto;
        display: flex;
        .top-bar-row-logo {
          width: 180px;
        }
        .top-bar-right {
          width: 380px;
        }
        .top-bar-center {
          flex: 1;
          display: flex;
          justify-content: flex-start;
          position: relative;
          padding: 0 0 0 60px;
          .menu-scroll {
            width: 100%;
            overflow: hidden;
          }

          .menu-wrap {
            ::v-deep {
              .is-active {
                .el-submenu__title {
                  .more-menu {
                    color: var(--themeColor);
                  }
                }
              }
              .el-menu--horizontal {
                .first-menu {
                  .sub-menu-title {
                    display: inline-block;
                    max-width: 96px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                  }
                }
              }
            }
          }
          .menu-left {
            width: 32px;
            height: 32px;
            position: absolute;
            left: 14px;
            top: 14px;
            background: #f5f5f5;
            color: #999;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            cursor: pointer;
            &:hover {
              color: var(--themeColor);
            }
          }

          .menu-right {
            width: 32px;
            height: 32px;
            position: absolute;
            right: 14px;
            top: 14px;
            background: #f5f5f5;
            color: #999;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            cursor: pointer;
            &:hover {
              color: var(--themeColor);
            }
          }
        }
      }
      .logo-padding {
        padding-left: $base-logo-padding-left;
      }

      ::v-deep {
        .el-menu {
          &.el-menu--horizontal {
            // width: 100%;
            height: $base-top-bar-height;
            // display: flex;
            flex-shrink: 0;
            // overflow-x: auto;
            // overflow-y: hidden;
            // overflow: hidden;
            border-bottom: 0 solid transparent !important;
            background-color: var(--menuBgColor) !important;
            display: flex;

            // &::before {
            //   content: '';
            //   flex: 1;
            // }

            &::-webkit-scrollbar {
              width: 6px;
              height: 6px;
              background: transparent;
            }

            &::-webkit-scrollbar-thumb {
              background-color: rgba(144, 147, 153, 0.3);
              border-radius: 10px;
            }

            &::-webkit-scrollbar-thumb:hover {
              background-color: rgba(144, 147, 153, 0.3);
            }
            .el-submenu.is-active.first-menu > .el-submenu__title {
              background-color: rgba(var(--themeColorRgb), 0.2) !important;
            }
            .el-submenu.is-active.second-menu > .el-submenu__title {
              background-color: rgba(var(--themeColorRgb), 0.2) !important;
            }
            .el-submenu.is-active.three-menu > .el-submenu__title {
              background-color: rgba(var(--themeColorRgb), 0.2) !important;
            }
            .is-active.more-menu__submenu {
              .el-menu--horizontal {
                .el-submenu.is-active {
                  .el-submenu__title {
                    @include more-submenu-style(--themeColor);
                  }
                }
                .el-submenu .el-submenu__title {
                  background-color: var(--menuBgColor) !important;
                  &:hover {
                    @include more-submenu-style(--themeColor);
                    @include menu-arrow(90deg);
                  }
                  @include more-submenu-style(--menuColor);
                  @include menu-arrow(0deg);
                }
              }
            }
            .el-menu-item,
            .el-submenu__title {
              // padding: 0 15px;
              // background-color: var(--menuBgColor) !important;
              &:hover {
                .ht-fa-icon {
                  color: var(--themeColor);
                }
              }
            }
            @media only screen and (max-width: 767px) {
              .el-menu-item,
              .el-submenu__title {
                padding: 0 8px;
              }

              li:nth-child(4),
              li:nth-child(5) {
                display: none !important;
              }
            }

            > .el-menu-item {
              flex-shrink: 0;
              height: $base-top-bar-height;
              line-height: unset;
              display: flex;
              align-items: center;
              // &:hover {
              //   background-color: rgba(var(--themeColorRgb), 0.2) !important;
              // }
            }

            > .el-submenu {
              .el-submenu__title {
                height: $base-top-bar-height;
                line-height: unset;
                display: flex;
                align-items: center;
              }
            }
            .el-submenu {
              .el-menu-item {
                margin: 0 8px;
              }
              .el-icon-arrow-down {
                display: none;
              }
              // &:hover {
              //   .el-icon-arrow-down {
              //     display: none;
              //     color: var(--themeColor);
              //   }
              // }
              .el-menu-item.is-active.first-menu {
                background-color: rgba(var(--themeColorRgb), 0.2) !important;
              }
              .el-menu-item.is-active.second-menu {
                background-color: rgba(var(--themeColorRgb), 0.2) !important;
              }
              .el-menu-item.is-active.three-menu {
                background-color: rgba(var(--themeColorRgb), 0.2) !important;
              }
              .is-active {
                /*  background-color: rgba(var(--themeColorRgb), 0.2) !important; */
                border-radius: $base-radius;
                .sub-menu-child__title {
                  &::before {
                    background: transparent;
                    @include dot-border-color;
                  }
                }
              }
              .sub-menu-child__title {
                &::before {
                  border-color: $base-color-second-color;
                }
              }
              .el-menu-item {
                &:hover {
                  .sub-menu-child__title {
                    &::before {
                      @include dot-border-color;
                    }
                  }
                }
              }
            }
            .el-submenu.is-active {
              // .el-submenu__title {
              //   background-color: rgba(var(--themeColorRgb), 0.2) !important;
              // }
              .ht-fa-icon {
                color: var(--themeColor);
              }
            }
            .el-submenu.is-opened > .el-submenu__title .el-submenu__icon-arrow {
              transform: rotateZ(90deg);
            }
            .el-menu-item.first-menu {
              margin: 0;
              .second-menu {
                .menu-title,
                .sub-menu-title {
                  font-size: 14px;
                  padding-left: 10px;
                }
                .three-menu {
                  .menu-title,
                  .sub-menu-title {
                    font-size: 14px;
                    padding-left: 20px;
                    width: 100%;
                    display: inline-block;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    box-sizing: border-box;
                  }
                  .el-menu--horizontal {
                    .el-menu {
                      display: none;
                    }
                  }
                }
              }
            }
            .el-submenu.catalog-menu {
              .el-menu--horizontal {
                .el-menu {
                  &:empty {
                    display: none;
                  }
                }
              }
            }
          }

          svg {
            width: 1rem;
            margin-right: 3px;
          }

          &--horizontal {
            .el-menu {
              .el-menu-item,
              .el-submenu__title {
                height: $base-menu-item-height;
                line-height: $base-menu-item-height;
              }
            }

            .el-submenu,
            .el-menu-item {
              &.is-active {
                // background-color: $base-color-blue !important;
                border-bottom: 0 solid transparent !important;
                .el-icon-arrow-down {
                  color: var(--themeColor);
                }
                .el-submenu__title {
                  border-bottom: 0 solid transparent !important;
                }
              }
            }

            > .el-menu-item {
              .el-tag {
                margin-top: calc(#{$base-top-bar-height} / 2 - 7.5px);
                margin-left: 5px;
              }

              @media only screen and (max-width: 1199px) {
                .el-tag {
                  display: none;
                }
              }

              &.is-active {
                //background-color: transparent !important;
              }
            }
          }
        }
        .el-menu--horizontal.el-menu {
        }
      }
      .menu-more-wrap {
        height: $base-top-bar-height;
        width: 68px;
        display: flex;
        align-items: center;
        .more-menu {
          position: fixed;
          top: 60px;
          z-index: 99;
        }
      }
      ::v-deep {
        .more-menu__submenu {
          .second-menu.is-active.catalog-menu {
            /* background-color: #fff !important; */
          }
          .catalog-menu {
            .el-submenu__title {
              i {
                color: var(--menuColor);
              }
              &:hover {
                i {
                  color: var(--themeColor);
                }
              }
            }
          }
          .el-menu--horizontal {
            .first-menu {
              .el-submenu__title {
                padding: 0 16px;
              }
            }
            .first-menu.page-menu {
              padding-left: 16px;
            }
            .el-submenu {
              .page-menu {
                margin: 0 8px;
                padding-left: 16px;
              }
              .catalog-menu {
                .el-submenu__title {
                  /* margin: 0 8px; */
                }
              }
            }
          }
        }
      }
    }

    .right-panel {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      height: $base-top-bar-height;

      div:not(.el-divider--vertical),
      span {
        padding: 0 8px;
      }

      ::v-deep {
        .el-divider--vertical {
          margin: 0 20px;
          background-color: var(--topRightColor);
        }

        svg {
          width: 18px;
          height: 18px;
          font-size: $base-font-size-big;
          color: rgba($base-color-white, 0.9);
          cursor: pointer;
          fill: var(--topRightColor);
        }

        button {
          svg {
            margin-right: 0;
            color: rgba($base-color-white, 0.9);
            cursor: pointer;
            fill: rgba($base-color-white, 0.9);
          }
        }

        .el-badge {
          margin-right: 15px;
        }
        .message-title {
          color: var(--topRightColor);
        }
      }
    }
  }
  .iconEmail {
    margin-left: 8px;
  }

  .perListTitle {
    ::v-deep .el-submenu__title {
      display: none !important;
    }
  }
</style>
