<template>
  <div :class="['aside-container', {'menu-hidden': !menuShow}]">
    <!-- <div class="logo_title" v-if="navMode !== 'topSideMenu-UD'">
      <img class="logo" :src="logoUrl" />
      <span :class="['title', {'title-hidden': !menuShow}]">{{
        companyName
      }}</span>
    </div> -->
    <div class="role-selector-wrap" v-if="roleList && roleList.length > 1">
      <span class="role-label">角色：</span>
      <el-select
        class="role-selector"
        v-model="roleCode"
        placeholder="请选择"
        size="small"
        @change="changeRole"
      >
        <el-option
          v-for="item in roleList"
          :key="item.roleCode"
          :label="item.roleName"
          :value="item.roleCode"
        >
        </el-option>
      </el-select>
    </div>
    <div
      :class="[
        'side-menu',
        {short: roleList && roleList.length > 1},
        {full: navMode == 'topSideMenu-UD'}
      ]"
    >
      <el-scrollbar class="editScroll">
        <el-menu
          ref="sidemenu"
          unique-opened
          class="el-menu-vertical"
          :default-active="activeIndex"
          @select="handleSelect"
          :collapse="!menuShow"
          :collapse-transition="false"
        >
          <template v-for="menu in currentMenu">
            <!-- + alias + '/'  -->
            <el-submenu
              :key="menu.alias"
              :index="'/platLayout/' + menu.alias"
              v-if="menu.children && menu.children.length > 0"
              :class="['firstLevel', {noArrow: !menuShow}]"
            >
              <template slot="title">
                <svgIcon
                  icon-style="icon header-icon"
                  :icon-class="menu.menuIcon ? menu.menuIcon : ''"
                />
                <span slot="title" class="firstLevelTitle">{{
                  menu.name
                }}</span>
              </template>
              <!-- menu.alias + '/' + -->
              <el-menu-item
                :index="'/platLayout/' + submMenu.alias"
                v-for="submMenu in menu.children"
                :key="submMenu.alias"
                class="subLevel"
              >
                <template slot="title">
                  <svgIcon
                    icon-style="icon header-icon"
                    :icon-class="submMenu.menuIcon ? submMenu.menuIcon : ''"
                  />
                  <span slot="title" class="subLevelTitle">{{
                    submMenu.name
                  }}</span>
                </template>
              </el-menu-item>
            </el-submenu>
            <el-menu-item
              v-else
              :key="menu.alias"
              :index="'/platLayout/' + menu.alias"
            >
              <svgIcon
                icon-style="icon header-icon"
                :icon-class="menu.menuIcon ? menu.menuIcon : ''"
              />
              <span slot="title" class="firstLevelTitle">{{ menu.name }}</span>
            </el-menu-item>
          </template>
        </el-menu>
      </el-scrollbar>
    </div>
  </div>
</template>

<script>
import {mapState} from 'vuex'
import menu from '@/api/menu.js'
export default {
  props: ['menuShow', 'navMode', 'bizMenuIndex', 'bizMenuAlias'],
  data() {
    return {
      logoUrl: '',
      companyName: '智采平台',
      currentMenu: [],
      activeIndex: '',
      hasAuthTobigScreen: false,
      roleList: [],
      roleCode: '',
      admin: false,
      menuAll: [],
      platReady: undefined
    }
  },
  mounted() {
    this.$bus.$on('menuPathReady', aliasPath => {
      let menuKey
      if (
        this.navMode == 'topSideMenu-LR' ||
        this.navMode == 'topSideMenu-UD'
      ) {
        // 根据获取到的全路径取得对应的侧边栏菜单
        menuKey = aliasPath[this.bizMenuIndex]
      } else {
        menuKey = this.bizMenuAlias // 非联动菜单则是固定的侧边栏别名，这个别名根据每个业务系统的配置来确定。
      }
      this.filterBizMenu(this.frontMenus, menuKey)
      // 没有子菜单则隐藏侧边栏
      let hasSideMenu = this.currentMenu.length ? true : false
      this.$emit('update:menuShow', hasSideMenu)
      // 设置菜单高亮
      this.getActiveIndex()
    })
  },
  computed: {
    ...mapState({
      frontMenus: state => {
        return state.menu.frontMenus
      },
      roleMenus: state => {
        return state.menu.roleMenus
      }
    })
  },
  created() {
    this.getSysInfo()
    // this.getRoleList()
  },
  beforeDestroy() {
    sessionStorage.removeItem('platReady')
  },
  methods: {
    // 页面刷新过滤出当前菜单
    getActiveIndex(to) {
      this.activeIndex = this.$route.path
    },
    // 筛选出业务菜单
    filterBizMenu(menus, aliasKey) {
      menus.forEach(item => {
        if (item.alias === aliasKey) {
          this.currentMenu = item.children
        } else if (item.children && item.children.length) {
          this.filterBizMenu(item.children, aliasKey)
        }
      })
    },
    // 获取系统名称、logo
    getSysInfo() {
      let url = '${uc}/uc/tenantManage/v1/getTenantByCode?code=platform'
      this.$http.get(url).then(resp => {
        if (resp.data) {
          let tenantManage = resp.data
          // this.companyName = tenantManage.nameFront
          if (tenantManage.frontLogo) {
            let frontLogo = JSON.parse(tenantManage.frontLogo)
            if (frontLogo && frontLogo.length > 0) {
              this.$http
                .get(
                  window.context.portal +
                    '/file/onlinePreviewController/v1/getFileById_' +
                    frontLogo[0].id,
                  'arraybuffer'
                )
                .then(response => {
                  let type = response.headers['content-type']
                  if (type) {
                    this.logoUrl = window.URL.createObjectURL(
                      new Blob([response.data], {
                        type: type
                      })
                    )
                  } else {
                    this.logoUrl = window.URL.createObjectURL(
                      new Blob([response.data])
                    )
                  }
                })
            }
          }
        }
      })
    },
    // 点击菜单跳转路由
    handleSelect(path, isJump) {
      let alias
      let _this = this
      if (path && path.indexOf('/platLayout/href') == -1) {
        let i = path.lastIndexOf('/')
        alias = path.slice(i + 1)
      } else {
        alias = path.replace('/platLayout/', '')
      }
      menu.getMenuByAlias(alias, m => {
        m && _this.$emit('menuChange', m)
        if (m && m.openType == '2' && isJump) {
          if (m.alias.indexOf('href/') == -1) {
            let openPath = '/platLayout/' + m.alias
            let routeUrl = this.$router.resolve({path: openPath})
            window.open(routeUrl.href, '_blank')
          } else {
            let tempwindow = window.open()
            tempwindow.location = m.href
          }
        } else if (m && m.parent) {
          this.$router.push(path)
          this.activeIndex = path
        }
      })
    },

    /**角色菜单相关  start*/
    changeRole(role) {
      this.roleCode = role
      sessionStorage.setItem('currentRoleCode', role)
      this.$store.dispatch('menu/actionsRoleMenu', this.roleCode).then(data => {
        this.menuAll = data
        this.filterBizMenu()
        this.toFirstMenu(data)
      })
    },
    toFirstMenu(data) {
      let fullDataMenus =
        data && data.filter(item => item.alias === 'bigscreen')
      let dataMenus = fullDataMenus.children[5].children[5].children
      console.log(dataMenus)
      if (dataMenus && dataMenus.length !== 0) {
        if (
          dataMenus[0].children.length !== 0 &&
          dataMenus[0].children[0].children.length
        ) {
          this.$router.push({
            path: `/platLayout/${dataMenus[0].children[0].children[0].alias}`
          })
          this.activeIndex = `/platLayout/${dataMenus[0].children[0].children[0].alias}`
        } else {
          this.$router.push({
            path: `/platLayout/${dataMenus[0].children[0].alias}`
          })
          this.activeIndex = `/platLayout/${dataMenus[0].children[0].alias}`
        }
      } else {
        this.$router.push({
          path: `/platLayout/empty`
        })
      }
    },
    getRoleList() {
      let UserDetail = JSON.parse(sessionStorage.getItem('currentUserDetail'))
      if (!UserDetail) {
        this.$store.dispatch('user/loadCurrentUserDetail').then(res => {
          UserDetail = res
          this.roleList = UserDetail.roleList || []
          sessionStorage.getItem('currentRoleCode', this.roleList[0].roleCode)
          this.currentRoleCode(UserDetail)
          this.getMenus()
        })
      } else {
        this.roleList = UserDetail.roleList
        this.currentRoleCode(UserDetail)
        this.getMenus()
      }
    },
    currentRoleCode(UserDetail) {
      let defaultRole = sessionStorage.getItem('currentRoleCode')
      if (!defaultRole) {
        defaultRole = this.roleList[0].roleCode
        sessionStorage.setItem('currentRoleCode', defaultRole)
      }
      this.roleCode = defaultRole
      let account = UserDetail.user.account
      // 系统管理员使用frontMenus
      if (this.roleCode == 'sysRole' && account == 'admin') {
        this.admin = true
      } else {
        this.admin = false
      }
    }
    /**角色菜单相关 end*/
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/element-variables.scss';
.aside-container {
  height: 100% !important;
  width: $--aside-width;
  position: relative;
  // background-color: $--menu-bg;
  background-color: #fff;
  box-shadow: 0 0 12px 0 rgba($color: #000000, $alpha: 0.1);
  box-sizing: border-box;
  transition: width 0.2s linear;
}
.aside-container.menu-hidden {
  width: $--aside-width-hidden;
}

// .logo_title {
//   height: 70px;
//   line-height: 70px;
//   width: 100%;
//   color: #fff;
//   text-align: center;
//   overflow: hidden;
//   .logo {
//     width: 50px;
//     vertical-align: middle;
//     margin-right: 6px;
//   }
//   .title {
//     font-size: 24px;
//     font-weight: bold;
//     opacity: 1;
//     transition: opacity 0.5s linear;
//   }
//   .title.title-hidden {
//     opacity: 0;
//   }
// }
.role-selector-wrap {
  width: 100%;
  display: flex;
  width: 100% !important;
  justify-content: center;
  align-items: center;
  margin: 10px 0;
  height: 30px;
}
.role-label {
  font-size: 12px;
  color: $--menu-text;
}
.role-selector {
  width: 160px;
  /deep/ .el-input__inner {
    background-color: #616166;
    border-color: #616166;
    color: $--menu-text;
  }
  /deep/ .el-input.is-focus .el-input__inner,
  .el-input__inner:focus {
    border-color: #fff;
  }
}
/deep/.el-select .el-input__inner:focus {
  border-color: #fff;
}
// 如果有角色选择器
.side-menu.short {
  height: calc(100% - 120px);
}
.side-menu.full {
  height: 100%;
}
.side-menu {
  width: 100%;
  height: calc(100% - 70px);
}
.editScroll {
  height: 100%;
  overflow-x: hidden;
}

.el-menu-vertical {
  height: 100% !important;
  .header-icon {
    margin-right: 10px;
    font-size: 16px;
    vertical-align: middle;
    margin-top: -1px;
  }
}
/deep/ .el-menu {
  border-right: none;
  // background-color: $--menu-bg;
  background-color: #fff;
}
/deep/ .el-menu-item {
  padding: 0 20px !important;
  height: 48px;
  line-height: 48px;
  span,
  svg {
    font-size: 16px !important;
    // color: $--menu-text;
    color: black;
  }
}

/deep/ .el-submenu__title {
  padding: 0 20px !important;
  height: 48px;
  line-height: 48px;
  // color: $--menu-text;
  color: black;
}

/deep/ .el-submenu .el-menu-item {
  padding: 0 40px !important;
  box-sizing: border-box;
}

/deep/ .el-menu--inline {
  // background-color: $--menu-hover !important;
  background-color: #fff !important;
}
/deep/ .el-submenu__title .firstLevelTitle {
  transition: all 0.1s linear;
  font-size: 16px !important;
  // color: $--menu-text;
  color: black;
}
.firstLevel .header-icon {
  font-size: 16px;
  margin-top: -4px;
}
.subLevel .header-icon {
  font-size: 16px;
  margin-top: -4px;
}
.el-submenu__title *,
.el-menu-item * {
  vertical-align: baseline;
}
.aside-container /deep/ .el-submenu__title:hover,
.aside-container /deep/ .el-submenu__title.is-active {
  // background-color: $--menu-bg !important;
  background-color: #d9e4ea !important;
  span,
  i,
  svg {
    // color: $--menu-text-active !important;
    color: black !important;
  }
}

.aside-container /deep/ .el-menu-item.is-active {
  position: relative;
  // background-color: $--menu-active !important;
  background-color: #d9e4ea !important;
  span,
  i,
  svg {
    // color: $--menu-text-active !important;
    color: black !important;
  }
}
.aside-container /deep/ .el-menu-item.is-active:hover {
  // background-color: $--menu-active !important;
  background-color: #ccc !important;
}
.aside-container /deep/ .el-menu-item.is-active::after {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 4px;
  height: 100%;
  background-color: $--menu-active-side;
}
.aside-container /deep/ .el-menu-item:hover {
  // background-color: $--menu-hover !important;
  background-color: #ccc !important;
  // color: $--menu-text-active;
  color: black;
}

.aside-container /deep/ .subLevel:hover {
  // background-color: $--menu-hover !important;
  background-color: #ccc !important;
  span,
  i,
  svg {
    color: $--menu-text-active !important;
  }
}
/deep/ .el-scrollbar__wrap {
  width: calc(100% + 10px) !important;
  height: calc(100% + 10px) !important;
}
/deep/ .el-menu-item span {
  // color: $--menu-text;
  color: black;
}
/deep/ .is-active {
  > .subLevelTitle {
    // color: $--menu-text-active;
    color: black;
  }
}
/deep/ .is-opened {
  .firstLevelTitle {
    // color: $--menu-text-active;
    color: black;
  }
}
</style>
