<template>
  <div class="layout-main-container">
    <slot name="top"></slot>
    <!-- 内容区域 -->
    <div
      class="menu-box"
      id="mainTab"
      v-if="isTab"
    >
      <el-tabs
        class="menu"
        :value="mainMenu"
        :before-leave="beforeChange"
        @tab-click="onClickSkip"
      >
        <el-tab-pane
          v-for="(item, index) in menuList"
          :key="index"
          :label="item.name"
          :name="index + ''"
        ></el-tab-pane>
      </el-tabs>

      <div
        class="menu-right-box"
        v-if="options.length"
      >
        <slot name="right"></slot>
        <div class="button-box">
          <el-button
            class="add-button"
            v-if="optionsCurrent && optionsCurrent.rightButton && optionsCurrent.rightButton.add"
            type="primary"
            size="mini"
            round
            @click="onClickAdd"
          >
            新增
          </el-button>
          <template v-if="optionsCurrent && optionsCurrent.rightButtons && optionsCurrent.rightButtons.length">
            <template v-for="(item, index) of optionsCurrent.rightButtons">
              <el-button
                v-if="(!item.code || (item.code && $verifyPerms && $verifyPerms(item.code)))"
                :key="index"
                :icon="item.icon"
                :type="item.type"
                size="mini"
                round
                @click="onClickRightButton(item.methodName)"
              >
                {{ item.name }}
              </el-button>
            </template>
          </template>
        </div>
      </div>
    </div>

    <div
      class="main"
      :class="{ 'main-no-tab': !isTab }"
    >
      <div class="container">
        <slot name="containerTop"></slot>
        <keep-alive v-if="isRouterAlive">
          <router-view
            v-if="$route.meta.keepAlive"
            ref="child"
          ></router-view>
        </keep-alive>
        <router-view
          v-if="!$route.meta.keepAlive"
          ref="child"
        ></router-view>
        <slot name="container"></slot>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'containerTabs',
  provide() {
    return {
      reload: this.reload
    }
  },
  data() {
    return {
      isRouterAlive: true,
      mainMenu: '0',
      isChangeMenu: false
    }
  },
  props: {
    isTab: {
      type: Boolean,
      default: true,
    },
    options: {
      type: Array,
      default() {
        return []
      }
    },
    menuList: {
      type: Array,
      default() {
        return []
      }
    },
    // 如果路由不一样隐藏tab按钮，默认不隐藏
    isPathHideTab: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    optionsCurrent() {
      if (!this.menuList.length) {
        return null
      }
      let urlPath = this.getUrlPath(this.menuList[Number(this.mainMenu)].menuUrl, false)
      let path = this.$route.path
      if(this.isPathHideTab){
        if(path!=urlPath){
          return null
        }
      }
      return this.options.find(item => item.path === urlPath);
    },
  },
  watch: {
    menuList: {
      handler() {
        if (this.menuList.length) {
          if (this.$route.query.TAB) {
            let num = Number(this.$route.query.TAB)
            this.mainMenu = num < this.menuList.length ? this.$route.query.TAB : '0';
          } else if (this.$route.query.tabId) {
            for (let i = 0; i < this.menuList.length; i++) {
              if (this.$route.query.tabId === this.menuList[i].primaryKey) {
                this.mainMenu = i + ''
                console.log(i, 'i')
                break
              }
            }

            this.mainMenu = this.mainMenu || '0'
          }

          this.$router.replace({
            path: this.getMenuUrl(this.menuList[Number(this.mainMenu)]),
          }).catch(err => { err })
        }
      },
      immediate: true,
      deep: true
    },
    options: {
      handler() {
        if (this.options.length) {
          setTimeout(() => {
            this.options.forEach((item) => {
              if (item.rightTopNum !== undefined) {
                for (let i = 0; i < this.menuList.length; i++) {
                  let urlPath = this.getUrlPath(this.menuList[i].menuUrl, false)

                  if (item.path === urlPath) {
                    // console.log('item', item)
                    if (item.rightTopNum) {
                      document.querySelector('#mainTab').querySelector('#tab-' + i).innerHTML = this.menuList[i].name + `<span>${item.rightTopNum}</span>`
                    } else {
                      document.querySelector('#mainTab').querySelector('#tab-' + i).innerHTML = this.menuList[i].name
                    }
                  }
                }
              }
            })
          }, 500)
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    reload() {
      this.isRouterAlive = false;
      this.$nextTick(() => {
        this.isRouterAlive = true;
      })

    },
    getUrlPath(url, isQuery = true) {
      if (isQuery) {
        url = url.replace(/^(?:[^\/]|\/\/)*/, '')
      } else {
        url = url.replace(/^(?:[^\/]|\/\/)*/, '').split('?')[0]
      }

      return url
    },
    getMenuUrl(menuInfo) {
      let menuUrl = menuInfo.menuUrl
      let separator = menuUrl.indexOf('?') > -1 ? '&' : '?'

      let menuParamS = menuInfo.menuUrl.split('?')[1]

      let menuParamData = {
        TAB: this.mainMenu,
        tabId: menuInfo.primaryKey
      }
      if (menuParamS) {
        menuParamS.split('&').forEach((item) => {
          let paramItemArr = item.split('=')
          menuParamData[paramItemArr[0]] = paramItemArr[1]
        })
      }

      let paramData = []
      let queryData = Object.assign(this.$route.query, menuParamData)
      for (let key in queryData) {
        paramData.push(key + '=' + queryData[key])
      }
      console.log(menuUrl + separator + paramData.join('&'), 'menuUrl')
      return menuUrl + separator + paramData.join('&')
    },
    onClickAdd() {
      if (this.$refs.child.onClickMenuRightButtonAdd) {
        this.$refs.child.onClickMenuRightButtonAdd()
      } else {
        this.$notification({
          type: 'error',
          title: '函数调用错误',
          message: '页面未定义onClickAdd事件处理函数',
        })
      }
    },
    onClickRightButton(methodName) {
      if (this.$refs.child[methodName]) {
        this.$refs.child[methodName]()
      } else {
        this.$notification({
          type: 'error',
          title: '函数调用错误',
          message: `页面未定义${methodName}事件处理函数`,
        })
      }
    },
    beforeChange (activeName, oldActiveName) {
      let item = this.menuList[Number(activeName)]

      // 外链
      if (item.type == 'redirect') {
        this.$emit('redirect', item)
        this.isChangeMenu = false
        return false
      }

      this.isChangeMenu = true
      return true
    },
    async onClickSkip(item) {
      if (!this.isChangeMenu) {
        return
      }

      this.mainMenu = item.name

      this.$router.replace({
        path: this.getMenuUrl(this.menuList[Number(item.name)]),
      }).catch(err => { err })
    },
  },
};
</script>
<style lang="scss" scoped>
.layout-main-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

::v-deep .menu-box {
  position: sticky;
  z-index: 100;
  display: flex;
  align-items: center;
  height: 44px;
  padding: 0 30px;
  border-bottom: 1px solid #e5e5e5;

  .menu {
    flex: 1;
    border-bottom: unset !important;
    height: 44px;
    box-sizing: border-box;
    margin-top: 6px;
    overflow: hidden;
    .el-tabs__item {
      border-bottom: unset !important;
      position: relative;
      line-height: 44px;
      color: $color-999999;

      span {
        position: absolute;
        display: inline-block;
        text-align: center;
        right: 3px;
        top: 5px;
        min-width: 18px;
        height: 18px;
        border-radius: 9px;
        color: #ffffff;
        background: #ff3535;
        font-size: 12px;
        line-height: 18px;
        padding: 0 5px;
      }

      &:hover,
      &:focus {
        color: $primary-color;
      }
    }

    .is-active {
      position: relative;
      color: $primary-color;
    }
  }

  .menu-right-box {
    display: flex;
    align-items: center;
    height: 44px;
    .button-box {
      .el-button {
        margin-left: 10px;
      }

      .is-round {
        padding: 10px 16px;
        border-radius: 17px;
        min-width: 80px;
        font-size: 14px;
      }
    }
  }
}

.show-border-bottom {
  border-bottom: 1px solid #e5e5e5;
}

.main {
  position: relative;
  width: 100%;
  box-sizing: border-box;
  overflow-y: auto;
  flex: 1;
  .container{
    height: 100%;
  }
}

::v-deep .el-tabs .el-tabs__nav-wrap::after {
  display: none;
}
</style>
