<template>
  <div class="side-menu-wrapper">
    <div
      style="height:40px;width: calc(100% - 50px);position:absolute;bottom: 20px;margin-left:23px;display: flex;align-items: center"
      :style="{justifyContent:collapsed?'center':'start',flexDirection:collapsed?'column':'row'}">
      <Tooltip :content="collapsed?'展开菜单':'收起菜单'" placement="top-start" :offset="-7" transfer>
      <Icon @click="changeCollapsed" :style="{transform:collapsed?'rotate(90deg)':'rotate(0deg)'}"
            style="margin-left: 1px;transition:.3s;font-size: 24px;color:#fff;cursor: pointer;" type="md-menu"/>
      </Tooltip>
      <Tooltip :content="$t('refreshBasicData')" placement="right" transfer>
        <Icon @click="refreshBasicData"
              style="margin-left: 1px;transition:.3s;font-size: 22px;color:#fff;cursor: pointer;" type="md-refresh"/>
      </Tooltip>
    </div>
    <slot></slot>
    <div style="display: flex;justify-content: center;margin-top: 20px">
      <img v-if="collapsed" src="@/assets/images/new-logo-small.png" width="40px">
      <img v-else src="@/assets/images/new-logo.png" width="120px">
    </div>
    <div v-if="!collapsed" style="width: 100%;text-align: center;margin-bottom: 20px;margin-top: 20px;display: flex;justify-content: center;">
      <Input prefix="ios-search" v-model="menuName" clearable @on-enter="selectRoute" @on-clear="selectRoute" ref="search"
             class="search-menu" :placeholder="$t('inputWords', {'search-name': $t('functionName')})"/>
    </div>
    <Menu ref="menu" v-show="!collapsed" :active-name="activeName" :open-names="openedNames" :accordion="accordion"
          :theme="theme" width="auto" @on-select="handleSelect">
      <template v-for="item in menuListData">
        <template v-if="item.children && item.children.length === 1">
          <side-menu-item v-if="showChildren(item)" :key="`menu-${item.name}`" :parent-item="item"
                          @enter="enter" @out="out" :search-text="menuName"></side-menu-item>
          <menu-item v-else :name="getNameOrHref(item, true)" :key="`menu-${item.children[0].name}`">
            <common-icon :type="item.children[0].icon || ''"/>
            <span>{{ showTitle(item.children[0]) }}</span></menu-item>
        </template>
        <template v-else>
          <side-menu-item v-if="showChildren(item)" :key="`menu-${item.name}`" :parent-item="item"
                          @enter="enter" @out="out" :search-text="menuName"></side-menu-item>
          <menu-item v-else :name="getNameOrHref(item)" :key="`menu-${item.name}`">
            <common-icon :type="item.icon || ''"/>
            <span>{{ showTitle(item) }}</span></menu-item>
        </template>
      </template>
    </Menu>
    <div class="menu-collapsed" v-show="collapsed" :list="menuListData" style="width: 60px;text-align: center;">
      <template v-for="item in menuListData">
        <collapsed-menu v-if="item.children && item.children.length > 0" @on-click="handleSelect" hide-title
                        :root-icon-size="rootIconSize" :icon-size="iconSize" :theme="theme" :parent-item="item"
                        :key="`drop-menu-${item.name}`"></collapsed-menu>
        <Tooltip transfer v-else :content="showTitle(item.children && item.children[0] ? item.children[0] : item)"
                 placement="right" :key="`drop-menu-${item.name}`">
          <a @click="handleSelect(getNameOrHref(item, true))" class="drop-menu-a" :style="{textAlign: 'center'}">
            <i class="iconfont" :class="item.icon  || (item.children && item.children[0].icon)" style="color:#fff;"/>
          </a>
        </Tooltip>
      </template>
    </div>

    <div v-if="menuListData.length<=0"
         style="text-align: center;height: 100px;padding-top: 125px;color: #B3B9BF;font-size: 12px;">
      <Icon type="logo-dropbox" style="font-size: 28px;"/>
      <p>{{ $t('noMatchFunction') }}</p>
    </div>

    <Drawer :mask="false" placement="top" v-model="showCard" id="menu-drawer"
            :closable=false :transfer=false>
      <div class="drawer" id="side-menu-drawer">
        <div v-for="item in children">
          <p class="drawer-title"> {{ showTitle(item) }}</p>
          <div class="drawer-item">
            <p class="drawer-content" v-for="it  in item.children" @mouseenter="mouseenter(it)"
               @mouseleave="mouseleave(it)" v-if="it.meta.title && it.meta.menuType != 2">
            <span :style="'cursor:pointer;' + (menuName && it.meta.title.includes(menuName) ? 'color: orange;':'')"
                  @click="returnSpecificPage(item,it,false)" class="drawer-meta-title">{{ it.meta.title }}</span>
              <Button size="small" type="primary" v-show="it.meta.hover" @click="returnSpecificPage(item,it,true)" class="add-button">
                <Icon :type="item.icon?item.icon: 'md-add'"/>
              </Button>
            </p>
          </div>
        </div>
      </div>
    </Drawer>
  </div>
</template>
<script>
import SideMenuItem from './side-menu-item.vue'
import CollapsedMenu from './collapsed-menu.vue'
import mixin from './mixin'
import {convertToChildrenMain, handleMenu} from '@/libs/tools/user-tools'
import {mapActions} from "vuex";

export default {
  name: 'SideMenu',
  mixins: [mixin],
  components: {
    SideMenuItem,
    CollapsedMenu
  },
  inject: ['dkMain'],
  props: {
    menuList: {
      type: Array,
      default() {
        return []
      }
    },
    mousePosition: {
      type: Array,
      default() {
        return []
      }
    },
    // collapsed: {
    //   type: Boolean
    // },
    theme: {
      type: String,
      default: 'dark'
    },
    rootIconSize: {
      type: Number,
      default: 20
    },
    iconSize: {
      type: Number,
      default: 16
    },
    accordion: Boolean,
    activeName: {
      type: String,
      default: ''
    },
    openNames: {
      type: Array,
      default: () => []
    },
    // 是否可以操作菜单
    enableFlag:{
      type:Boolean,
      default:true
    }
  },
  data() {
    return {
      showCard: false,
      children: [],
      openedNames: [],
      menuName: '',
      menuListData: [],
      collapsed: false,
      overTimer: null,
      functionList: JSON.parse(sessionStorage.getItem('menu')),//获取初始路由
    }
  },
  methods: {
    ...mapActions([
      'setUserTableSettingAfter', 'setMenuListAfter'
    ]),
    /**
     * @desc   : 点击收缩和展开左边菜单
     * @author : 周兴
     * @date   : 2022/6/18 18:07
     */
    changeCollapsed() {
      this.collapsed = !this.collapsed
      this.$emit('on-collapsed-change', this.collapsed)
    },
    /**
     * @desc   : 刷新基础数据
     * @author : 周兴
     * @date   : 2023/5/11 10:26
     */
    refreshBasicData() {
      this.excute(this.$service.commonService, this.$service.commonService.refreshBasicData,
        {appCode: this.$config.appCode.WEB}, true, this.$t('refresh')).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          if (res.data) {
            let menu = res.data.menu;
            let menuCopy = menu.copy();
            menuCopy = menuCopy.filter(it =>  it.objectCode !== 'home')
            sessionStorage.setItem('menu', JSON.stringify(menuCopy))
            // 功能权限
            if (res.data.function) {
              sessionStorage.setItem('function', JSON.stringify(res.data.function))
            }
            // 用户隐藏列
            this.setUserTableSettingAfter(res.data.userTableSetting);
            menu = handleMenu(menu);
            let arr = convertToChildrenMain(menu);
            sessionStorage.setItem('route', JSON.stringify(arr))
            this.setMenuListAfter(arr)
            // 关闭所有的窗体
            if (this.dkMain) {
              this.dkMain.handleAllClose();
            }
            // 刷新页面
            location.reload();
          }
        }
      })
    },
    /**
     *   @author : 寇珊珊
     *   @date   : 2022/4/21 9:16
     *   @desc   : 鼠标进入菜单行
     */
    mouseenter(it) {
      //查询是否有权限设置hover属性
      let functionList = JSON.parse(sessionStorage.getItem('menu'));
      if (!functionList) return;
      let name = it.name + '-add';
      let filterList = functionList.filter(it => it.flgMenu && it.objectCode === name);
      // console.log('rrr',filterList,name,it,JSON.parse(sessionStorage.getItem('menu')))
      if (filterList && filterList.length > 0) {
        this.$set(it.meta, 'hover', true)
      } else {
        this.$set(it.meta, 'hover', false)
      }
    },
    /**
     *   @author : 寇珊珊
     *   @date   : 2022/4/21 9:16
     *   @desc   : 鼠标离开菜单行
     */
    mouseleave(it) {
      this.$set(it.meta, 'hover', false)
    },

    /**
     * @desc   : 鼠标移入menu事件
     * @author : 张潇木
     * @date   : 2022-5-18 14:18
     */
    enter(e, children) {
      if(!this.enableFlag)return;
      // 关闭tableselect下拉
      this.$refs.search.$el.click();
      // 关闭table的右键
      if (document.getElementsByClassName('vxe-table--context-menu-wrapper').length) {
        document.getElementsByClassName('vxe-table--context-menu-wrapper')[0].style.display = 'none'
      }
      this.overTimer ? clearTimeout(this.overTimer) : ''
      this.overTimer = setTimeout(() => {
        this.showDrawer(e, children)
      }, 300)
      // setTimeout(() => {
      //   // console.log(this.mousePosition)
      //   if (!this.mousePosition.map(it => it.id).includes("side-menu-drawer")
      //     && !this.mousePosition.map(it => it.className).includes("side-menu-wrapper")
      //     && !this.mousePosition.map(it => it.className).includes("left-sider")) {
      //     this.showCard = false
      //   }
      // }, 4000)
    },

    /**
     * @desc   :鼠标移出menu事件
     * @author : 张潇木
     * @date   : 2022-5-18 14:18
     */
    out(e, children) {
      //移出时判断一下，如果抽屉显示了，那就不用再切换菜单了
      // if (this.showCard) {
      //   clearTimeout(this.overTimer)
      // }
      clearTimeout(this.overTimer)
    },
    /**
     * @desc   : 抽屉展示事件
     * @author : 张潇木
     * @date   : 2022-5-18 14:20
     */
    showDrawer(e, children) {
      this.showCard = true
      this.children = children
      let target = e.target
      if (target.tagName == 'SPAN') {
        target = e.target.parentNode
      }
      document.getElementById('menu-drawer').children[0].children[0].style.left = '200px'
      document.getElementById('menu-drawer').children[0].children[0].style.width = children.length * 135 + 30 + 'px'
      document.getElementById('menu-drawer').children[0].children[0].style.transition = 'top 0.5s';
      let top = target.getBoundingClientRect().top
      if (top > 190 && top < 260) {
        top = top - 100
      }
      if (top >= 260) {
        top = top - 200
      }
      document.getElementById('menu-drawer').children[0].children[0].style.top = top + 'px'
      // document.getElementById('menu-drawer').children[0].children[0].style
      this.$nextTick(() => {
        //自适应高度
        //32 padding
        //10 margin-bottom
        let height = document.getElementById('side-menu-drawer').getBoundingClientRect().height;
        // console.log('t4',height)
        document.getElementById('menu-drawer').children[0].children[0].children[0].children[0].style.height = height + 32 + 10 + 'px'
        // 最小值256px
        document.getElementById('menu-drawer').children[0].children[0].children[0].children[0].style.minHeight = '256px';
        document.getElementById('menu-drawer').children[0].children[0].style.height = height + 32 + 10 + 'px'
        // console.log('3333',window.innerHeight,document.getElementById('side-menu-drawer').getBoundingClientRect().top)
      })
      clearTimeout(this.overTimer)
    },
    /**
     * @desc   : 隐藏抽屉
     * @author : 周兴
     * @date   : 2023/1/30 14:20
     */
    hiddenDrawer(e, children) {
      this.showCard = false
      this.children = []
    },
    /**
     *   @author : 寇珊珊
     *   @date   : 2022/4/21 9:38
     *   @desc   : 跳转页面
     *   flag： 是否跳转到页
     */
    returnSpecificPage(name, val, flag) {
      if (val && val.name) {
        //有新建
        if (val.meta.hover) {
          // flag=true 是点击按钮
          this.$router.push({name: val.name + (flag ? '-add' : ''),params:{menuClick:flag,parentPath:val.path}})
        } else {
          this.$router.push({name: val.name})
          // this.$router.push(val.path)
        }
        // 点击后不关闭，移开才会关闭
        // this.showCard = false
      }
    },
    /**
     * @desc   : 查询菜单
     * @author : 周兴
     * @date   : 2022/4/26 14:59
     */
    doSearchMenu(obj) {
      let returnObj = {...obj}
      if (!this.menuName) {
        this.openedNames = []
        this.openedNames = this.openedNames.union(this.getOpenedNamesByActiveName(this.$route.name))
        /* 改参数不可取  */
        // this.$emit('on-select', this.$route.name)
        return returnObj
      }
      let openedNames = []
      this.$set(returnObj, 'children', [])
      obj.children.forEach(it => {
        let t = {...it}
        if (it.meta.title.indexOf(this.menuName) !== -1) {
          t.searchFlag = true
        }
        if (it.children && it.children.length > 0) {
          t.children = [...(this.doSearchMenu(t).children)]
          if (t.children && t.children.length > 0) {
            returnObj.children.push({...t})
            openedNames.push(t.name)
          } else {
            if (t.searchFlag) {
              let tt = {...it}
              tt.searchFlag = true
              returnObj.children.push({...tt})
            }
          }
        } else {
          if (t.searchFlag) {
            returnObj.children.push({...t})
          }
        }
      })
      this.openedNames = this.openedNames.concat(openedNames)
      return returnObj;
    },
    handleSelect(name) {
      if (name) {
        this.$emit('on-select', name)
      }
    },
    getOpenedNamesByActiveName(name) {
      return this.$route.matched.map(item => item.name).filter(item => item !== name)
    },
    updateOpenName(name) {
      if (name === this.$config.homeName) this.openedNames = []
      else this.openedNames = this.getOpenedNamesByActiveName(name)
    },
    /**
     *   @desc   : 父级路由赋值
     *   @date   : 2023/4/12 15:58
     *   @author : 寇珊珊
     */
    setParentMenu(value) {
      //父级
      let middleRankList = this.functionList.filter(it => it.id === value.parentId)
      let topLevelList = []
      for (let item of middleRankList) {
        //父级的父级
        topLevelList = this.functionList.filter(it => it.id === item.parentId)
      }
      let parentList = middleRankList.concat(topLevelList)
      return parentList
    },
    /**
     *   @desc   : 判断是否存在子级
     *   @date   : 2023/4/12 17:07
     *   @author : 寇珊珊
     */
    checkChildren(value) {
      let list = this.functionList.filter(it => it.parentId === value.id)
      let arr = []
      for (let i of list) {
        //没有找到返回-1
        if (i.name.indexOf(this.menuName) == -1) {
          arr.push(i)
        }
      }
      return arr
    },
    /**
     *   @desc   : 查询路由
     *   @date   : 2023/4/12 15:26
     *   @author : 寇珊珊
     */
    selectRoute() {
      this.showCard = false;  // 关闭打开的菜单抽屉
      if (this.menuName) {
        let functionList = JSON.parse(sessionStorage.getItem('menu'))
        if (!functionList) return
        // console.log('444', this.menuName, functionList)
        // 如果查出导航，那么就要查出所有的子级 TODO
        let list = []
        for (let i of functionList) {
          //没有找到返回-1
          if (i.menuName.indexOf(this.menuName) != -1) {
            //判断是否存在子级
            let checkChildrenList = this.checkChildren(i)
            // if (checkChildrenList.length == 0) {
            //   list.push(i)
            // }
            list.push(i)
            //父级赋值
            let arr = this.setParentMenu(i)
            for (let i of arr) {
              if (list.filter(it => it.id == i.id).length == 0) {
                list.push(i)
              }
            }
            // console.log('b', checkChildrenList, arr, list,i)
          }
        }
        if (list && list.length > 0) {
          list = handleMenu(list);
          let arr = [...convertToChildrenMain(list)]
          // console.log('arr', arr)
          // 过滤掉没有子级的
          for (let item of arr) {
            item.children = item.children?.filter(it => it.children && it.children.length > 0)
          }
          arr = arr.filter(it => it.children && it.children.length > 0);
          // 过滤掉没有子级的
          this.menuListData = arr.filter(it => it.children && it.children.length > 0);

          //默认展开第一个搜索项
          if (this.menuListData[0].objectCode && this.menuListData[0].children[0].objectCode && this.menuListData[0].children[0].children[0].objectCode) {
            this.openedNames = [this.menuListData[0].objectCode, this.menuListData[0].children[0].objectCode, this.menuListData[0].children[0]?.children[0].objectCode]
          }

        } else {
          this.menuListData = []
        }
      } else {
        this.menuListData = [...this.menuList]
      }
    },
  },
  computed: {
    textColor() {
      return this.theme === 'dark' ? '#fff' : '#495060'
    }
  },
  watch: {
    activeName(name) {
      if (this.accordion) this.openedNames = this.getOpenedNamesByActiveName(name)
      else this.openedNames = this.openedNames.union(this.getOpenedNamesByActiveName(name))
    },
    openNames(newNames) {
      this.openedNames = newNames
    },
    openedNames() {
      this.$nextTick(() => {
        this.$refs.menu.updateOpened()
      })
    }
  },
  beforeDestroy() {
    clearTimeout(this.overTimer)
    this.overTimer = null;
  },
  mounted() {
    this.menuListData = [...this.menuList]
    // console.log('openedNames',this.openedNames)
    // console.log(this.menuListData)
  }
}
</script>
<style lang="less" scoped>
@import './side-menu.less';

@side-menu-drawer: #2b2c53;
@side-menu-background: #2E406B;

/deep/.ivu-input-prefix{
  margin-top: 4px!important;
}
.add-button{
  border-radius: 8px;
  height: 24px;
  width: 24px;
  font-size: 18px!important;
  display: flex;
  justify-content: center;
  align-items: center;
}
.add-button > span > i{
  margin-top: 1px;
}

::-webkit-scrollbar { //滑块部分
  width: 6px;
  height: 2px;
}

::-webkit-scrollbar-thumb { //滑块部分
  background-color: #fff !important;
  border-radius: 4px 4px 4px 4px;
}

::-webkit-scrollbar-track { //轨道部分
  //background-color: #fff !important;
  //margin-left: 30px ;
  padding-left: 20px;
  margin-top: 16px;

}

/deep/ .ivu-drawer-body {
  border-radius: 8px;
  background-color: @side-menu-drawer !important;
  max-height: 550px !important;
  overflow-y: hidden !important;
  max-width: 700px !important;
}

/deep/ .ivu-drawer-wrap {
  z-index: 5000 !important;
}

/deep/ .ivu-drawer {
  /*height: 500px !important;*/
  max-width: 700px !important;
}


/deep/ .menu-collapsed .ivu-dropdown {
  padding-top: 10px !important;
}
//
///deep/ .ivu-tooltip-popper{
//  z-index: 1000;
//}
</style>

