<script>
// vue2中script setup无法监听router，需要使用optionalAPI
import transferDom from '@jinglun/view-design/src/directives/transfer-dom'
import { Menu, MenuItem, Submenu } from '@jinglun/view-design'
import vueScroll from 'vuescroll/dist/vuescroll-native'
import { ref, set } from 'vue-demi'
import { useStyleTag } from '@vueuse/core'
import clickOutside from '@jinglun/view-design/src/directives/clickoutside'
import Tool from './tool.vue'
import { useTabStore } from '@/store/tab-store'
import Dialog from '@/components/dialog.vue'
import { getRoute, getRouter } from '@/utils/router'

const props = {
  menuList: { type: Array },
}

export default {
  directives: { transferDom, clickOutside },
  components: {
    Menu,
    MenuItem,
    Submenu,
    VueScroll: vueScroll,
    Dialog,
    Tool,
  },
  props,
  setup(props) {
    const router = getRouter()
    const route = getRoute()
    const tabStore = useTabStore()
    const isDialogShow = ref(false)
    const themeShow = ref(false)
    const theme = ref(false)
    const showNav = ref(true)
    const submenuRef = ref()

    const currentPath = ref('')
    const activeName = ref(route.fullPath)
    const tabChangeSure = ref(
      !!sessionStorage.getItem('tabChangeSure'),
    )
    const newMenuList = ref(
      props.menuList.map(item => {
        item.childrenShow = false
        return item
      }),
    )
    watch(
      () => [props.menuList],
      ([newValue]) => {
        newMenuList.value = newValue.map(item => {
          item.childrenShow = false
          return item
        })
      },
      { deep: true },
    )

    const onDialogOK = name => {
      router.push(name)
      tabChangeSure.value = true
      sessionStorage.setItem('tabChangeSure', 'true')
    }

    const routeChange = name => {
      // console.log(name)
      // console.log(getRoute())
      if (name === getRoute().path) {
        return
      }
      const existTabIndex = tabStore.tabList.findIndex(tab => {
        return tab.path === name
      })
      if (
        existTabIndex === -1 &&
        tabStore.tabList.length >= 10 &&
        !tabChangeSure
      ) {
        isDialogShow.value = true
        currentPath.value = name
      } else {
        router.push(name)
      }
    }
    const bottomImageUrl = getImageUrl('nav/左侧菜单底纹.png')

    const changeTheme = value => {
      theme.value = value
      if (value) {
        useStyleTag(
          props.menuList
            .map((menu, index) => {
              return `.menu-item${index} .menu-icon { background:url(${menu.activeImg}) center  no-repeat; }
                .menu-item${index}:hover .menu-icon { background:url(${menu.activeImg}) center  no-repeat;  }   
               .ivu-menu-item-active.menu-item${index} .menu-icon { background:url(${menu.activeImg}) center  no-repeat;  }
               .menu-item${index} .ivu-menu-submenu-title .menu-icon { background:url(${menu.activeImg}) center  no-repeat !important;  }
               .menu-item${index} .ivu-menu-submenu-title:hover .menu-icon { background:url(${menu.activeImg}) center  no-repeat !important;  }
               .submenu-small-active .ivu-menu-submenu-title  .menu-icon { background:url(${menu.activeImg}) center  no-repeat !important;  }
               .submenu-small-active:hover .ivu-menu-submenu-title  .menu-icon { background:url(${menu.activeImg}) center  no-repeat !important;  }
               `
            })
            .join(''),
        )
        useStyleTag(
          '.menu-item:hover {background: rgb(255 255 255 / 20%) !important;}',
        )
        useStyleTag(
          '.ivu-menu-submenu-title:hover {background: rgb(255 255 255 / 20%) !important;}',
        )
        useStyleTag(
          '.ivu-menu-submenu-title > i {color: #fff !important;}',
        )
        useStyleTag(
          `.menu {background-image: url("${bottomImageUrl}") !important;}`,
        )
      } else {
        useStyleTag(
          props.menuList
            .map((menu, index) => {
              return `.menu-item${index} .menu-icon { background:url(${menu.img}) center  no-repeat; }
                .menu-item${index}:hover .menu-icon { background:url(${menu.img}) center  no-repeat;  }   
               .ivu-menu-item-active.menu-item${index} .menu-icon { background:url(${menu.activeImg}) center  no-repeat;  }
               .menu-item${index} .ivu-menu-submenu-title .menu-icon { background:url(${menu.img}) center  no-repeat !important;  }
               .menu-item${index} .ivu-menu-submenu-title:hover .menu-icon { background:url(${menu.img}) center  no-repeat !important;  }
               .submenu-small-active .ivu-menu-submenu-title  .menu-icon { background:url(${menu.activeImg}) center  no-repeat !important;  }
               .submenu-small-active:hover .ivu-menu-submenu-title  .menu-icon { background:url(${menu.activeImg}) center  no-repeat !important;  }
               `
            })
            .join(''),
        )
        useStyleTag(
          '.menu-item:hover {background: linear-gradient(270deg, rgb(33 159 255 / 12%) 0%, rgb(2 144 253 / 12%) 100%) !important;}',
        )
        useStyleTag(
          '.ivu-menu-submenu-title:hover {background: linear-gradient(270deg, rgb(33 159 255 / 12%) 0%, rgb(2 144 253 / 12%) 100%) !important;}',
        )
        useStyleTag(
          '.ivu-menu-submenu-title > i {color: #333 !important;}',
        )
        useStyleTag('.menu {background-image: none !important;}')
      }
    }
    const changeNav = v => {
      showNav.value = v
      if (v) {
        useStyleTag(
          `.menu {background-image: url("${bottomImageUrl}") !important;}`,
        )
      } else {
        useStyleTag('.menu {background-image: none !important;}')
      }
    }
    changeTheme(false)
    const jumpRouter = routeObj => {
      router.push(routeObj)
    }

    const setChildrenShow = (menu, event) => {
      if (showNav.value) {
        return
      }
      set(menu, 'childrenShow', true)
      event.stopPropagation()
    }

    const handleClickOutSide = menu => {
      if (menu.childrenShow) {
        set(menu, 'childrenShow', false)
      }
    }

    const openName = computed(() => {
      const existMenu = props.menuList?.find(item => {
        const exist = item?.children?.find(child => {
          return child.path === activeName.value
        })
        if (exist) {
          return item.path
        }
      })
      return existMenu?.path
    })

    return {
      tabStore,
      isDialogShow,
      themeShow,
      theme,
      showNav,
      currentPath,
      activeName,
      submenuRef,
      onDialogOK,
      routeChange,
      changeTheme,
      changeNav,
      jumpRouter,
      newMenuList,
      setChildrenShow,
      handleClickOutSide,
      openName,
    }
  },
  watch: {
    $route: {
      handler(to) {
        this.activeName = to.meta.modulePath || to.path
      },
      immediate: true,
    },
    menuList() {
      this.$nextTick(() => {
        this.$refs.menu.updateOpened()
        this.$refs.menu.updateActiveName()
      })
    },
  },
}
</script>

<template>
  <Menu
    ref="menu"
    :active-name="activeName"
    :open-names="['/teacher/mymoral', openName]"
    accordion
    :width="showNav ? '200' : '56'"
    class="menu relative !z-0 menu-border"
    :class="[
      theme ? 'bg-[#2e3e4e]' : 'bg-[#e5f1ff]',
      showNav ? 'min-w-200px show-nav' : 'min-w-56px not-show-nav',
    ]"
    @on-select="routeChange"
  >
    <VueScroll
      class="nav-scroll"
      :ops="{
        bar: { /*background: '#3FD3FE',*/ keepShow: true },
      }"
    >
      <template v-for="(menu, index) in newMenuList">
        <Submenu
          v-if="menu.children && menu.show"
          ref="submenuRef"
          :key="`submenu${index}`"
          class="relative"
          :name="menu.path"
          :class="[
            `menu-item${index}`,
            menu.children.some(item => item.path.includes(activeName))
              ? !showNav
                ? 'submenu-small-active'
                : 'submenu-active'
              : 'submenu-small-not-active',
          ]"
        >
          <template #title>
            <Tooltip
              class="block"
              placement="right"
              transfer
              :disabled="showNav"
              theme="light"
              transfer-class-name="suspendWrap-tooltip"
            >
              <div
                class="align-center relative !pl-12px"
                @click="e => setChildrenShow(menu, e)"
              >
                <div class="menu-icon inline-block"></div>
                <span
                  v-if="showNav"
                  :class="theme ? '!text-[#fff]' : ''"
                  >{{ menu.title }}</span
                >
              </div>

              <div
                v-show="!showNav"
                slot="content"
                v-click-outside="() => handleClickOutSide(menu)"
                class="suspendWrap"
              >
                <div
                  v-for="(child, childIndex) in menu.children"
                  :key="childIndex"
                  class="suspendItem"
                  @click="jumpRouter(child)"
                >
                  <span
                    :style="{
                      color:
                        activeName == child.path ? '#0290fd' : '#000',
                    }"
                    >{{ child.title }}</span
                  >
                  <Icon
                    v-if="activeName == child.path"
                    style="color: #0290fd"
                    type="md-checkmark"
                  />
                </div>
              </div>
            </Tooltip>
          </template>

          <MenuItem
            v-for="(child, childIndex) in menu.children"
            v-if="child.show && showNav"
            :key="childIndex"
            class="menu-item !text-[#555]"
            :name="child.path"
          >
            <span
              class="point"
              :class="theme ? 'bg-[#fff]' : ''"
            ></span>
            <span
              v-if="showNav"
              :class="theme ? '!text-[#fff]' : ''"
              >{{ child.title }}</span
            >
          </MenuItem>
        </Submenu>

        <Tooltip
          class="block"
          placement="right"
          transfer
          :content="menu.title"
          :disabled="showNav && !menu.children"
          theme="black"
        >
          <MenuItem
            v-if="!menu.children && menu.show"
            :key="`menu-item${index}`"
            :name="menu.path"
            class="menu-item"
            :class="[`menu-item${index}`]"
          >
            <div class="menu-icon"></div>
            <span
              v-if="showNav"
              :class="theme ? '!text-[#fff]' : ''"
              >{{ menu.title }}</span
            >
          </MenuItem>
        </Tooltip>
      </template>
    </VueScroll>

    <Dialog
      v-model="isDialogShow"
      content="已达到浏览的选项卡上限，继续则会关闭最开始的部分选项卡，确认继续?"
      @onOk="onDialogOK"
    />
    <Tool
      class="absolute z-1000 left-0 bottom-0 right-0 h-40px leading-40px bg-[#0072ff] bg-opacity-3"
      @change-theme="changeTheme"
      @change-nav="changeNav"
    />
  </Menu>
</template>

<style lang="scss" scoped>
.align-center {
  display: flex;
  align-items: center;
  padding: 8px 0;
}

.menu-border {
  border-right: 1px solid #c2ddff;
}

.shadow-box {
  background-color: #fff;
  border: solid 1px #e5e5e5;
  border-radius: 5px;
  box-shadow: 0 0 6px 0 rgb(0 0 0 / 16%);
}

.menu {
  height: 100%;
  color: #333;

  // /* 背景图不平铺 */
  background-repeat: no-repeat;

  // /* 背景图垂直、水平均居中 */
  background-position: bottom right;

  // /* 当内容高度大于图片高度时，背景图像的位置相对于viewport固定 */
  // /* 让背景图基于容器大小伸缩 */
  background-size: unset;

  &::after {
    width: 0 !important;
  }

  .menu-item {
    display: flex;
    align-items: center;
    height: 36px;
    margin: 10px 8px;
    color: #333;
    border-radius: 5px;

    span {
      padding-top: 3px;
    }

    &:hover {
      color: #333 !important;
      background: linear-gradient(
        270deg,
        rgb(33 159 255 / 12%) 0%,
        rgb(2 144 253 / 12%) 100%
      );
      background-repeat: no-repeat;
    }

    // > &:first-child {
    //   border-top: 1px solid #064575;
    // }
  }

  .menu-icon {
    width: 16px;
    height: 16px;
    margin-right: 12px;
  }

  ::v-deep .ivu-menu {
    z-index: 9 !important;
    color: white !important;
  }

  .menu-item.ivu-menu-item-active {
    font-weight: bold;
    color: white !important;

    // background: hsla(0, 0%, 100%, 0.2) !important;
    background: linear-gradient(
      270deg,
      #219fff 0%,
      #0290fd 100%
    ) !important;

    &:hover {
      background: linear-gradient(270deg, #219fff 0%, #0290fd 100%);
    }

    &::after {
      background: transparent !important;
    }
  }

  ::v-deep .ivu-menu-submenu {
    margin: 10px 15px !important;
  }

  // 子菜单颜色选中
  // ::v-deep .ivu-menu-submenu .menu-item.ivu-menu-item-active {
  //   background: #066aeb !important;
  //   font-weight: bold !important;

  //   &::after {
  //     background: transparent !important;
  //   }
  // }
  ::v-deep .ivu-menu-item-selected {
    padding: 14px 0 14px 12px !important;
  }

  ::v-deep .ivu-menu-item {
    padding: 14px 0 14px 12px !important;
  }

  ::v-deep .ivu-menu-submenu {
    margin: 10px 8px !important;

    .ivu-menu-submenu-title {
      padding: 0 !important;
      border-radius: 5px !important;
    }

    .menu-item,
    .ivu-menu-item {
      padding-left: 37px !important;
      margin: 4px 0 !important;
    }
  }

  ::v-deep .ivu-menu-opened {
    // .ivu-menu-submenu-title {
    //   font-weight: bold;
    // }

    .menu-item.ivu-menu-item-active {
      font-weight: normal;
    }
  }

  ::v-deep .ivu-menu-submenu-title:hover {
    color: #333;
    background: linear-gradient(
      270deg,
      rgb(33 159 255 / 12%) 0%,
      rgb(2 144 253 / 12%) 100%
    );
    border-radius: 5px;

    --tw-bg-opacity: 0.12 !important;
  }

  .menu-item.ivu-menu-item-active > .point {
    background: white;
  }

  .menu-item.ivu-menu-item-active:hover .point {
    background: #fff !important;
  }

  ::v-deep .ivu-menu-item:hover .point {
    background: #999 !important;
  }

  ::v-deep .ivu-menu-submenu-title > i {
    margin-right: 0 !important;
    color: #999 !important;
  }

  ::v-deep .ivu-menu-opened .ivu-menu-submenu-title-icon {
    transform: translateY(-50%) rotate(90deg) !important;
  }

  ::v-deep .ivu-menu-submenu-title-icon {
    right: 15px !important;
  }
}

.point {
  display: inline-block;
  width: 4px;
  height: 4px;
  margin-right: 8px;
  margin-left: 7px;
  background: #999;
  border-radius: 50%;
}

.show-nav {
  .menu-item.ivu-menu-item-active {
    background: url('@/assets/images/nav/选中背景.svg') no-repeat
      center right !important;
  }
}

.not-show-nav {
  ::v-deep .ivu-icon-ios-arrow-forward {
    display: none;
  }

  ::v-deep .menu-item {
    margin: 10px 8px !important;
  }

  ::v-deep .ivu-menu-submenu {
    margin: 10px 8px !important;
  }
}

// 去除左侧导航滚动条
::v-deep .__view {
  min-height: calc(100% - 20px) !important;
}

/* stylelint-disable selector-class-pattern */
::v-deep .nav-scroll {
  .__bar-is-vertical {
    // background: #7bbeff !important;
    background: white !important;
    opacity: 0.35 !important;
  }

  .vBarDragging {
    .__bar-is-vertical {
      // background: #7bbeff !important;
      background: white !important;
      opacity: 0.45 !important;
    }
  }

  .__rail-is-vertical {
    z-index: 9 !important;

    .__bar-is-vertical {
      &:hover {
        // background: #7bbeff !important;
        background: white !important;
        opacity: 0.45 !important;
      }
    }
  }
}

.suspendWrap {
  // position: fixed;
  // left: 70px;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 150px;
  padding: 10px 8px;
  color: #000;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 0 3px 3px #eee;

  .suspendItem {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 30px;
    padding-top: 10px;
    padding-right: 8px;
    padding-bottom: 10px;
    padding-left: 8px;
    line-height: 30px;
    text-align: center;
    cursor: pointer;

    &:hover {
      background-color: #e5f1ff;
      border-radius: 5px;
      opacity: 0.75;
    }
  }
}

.submenu-small-active {
  background-image: linear-gradient(270deg, #219fff 0%, #0290fd 100%);
  border-radius: 5px;
}

.submenu-active {
  :deep(.ivu-menu-submenu-title) {
    font-weight: bold;
  }
}

:deep(.ivu-tooltip-rel) {
  display: block;
}
</style>

<style lang="scss">
.suspendWrap-tooltip {
  .ivu-tooltip-arrow {
    display: none !important;
  }

  .ivu-tooltip-inner {
    box-shadow: unset !important;
  }
}
</style>
