<template>
  <div class="fullheight">
    <el-aside
      :class="{'menu-manage': isShowBtn}"
      class="fullheight"
      :width="width"
      v-show="asideShow"
    >
      <ht-menu-tree
        highlight-current
        ref="htMenuTree"
        :node-key="nodeKey"
        :show-checkbox="showCheckbox"
        :support-filter="supportFilter"
        :default-expand-all="isExpand"
        :default-checked-keys="defaultCheckedKeys"
        :defaultIsOpenKeys="defaultIsOpenKeys"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
        @load="loadData"
        :data="treeData"
      >
        <span class="custom-tree-node" slot-scope="{node, data}">
          <span class="show-ellipsis" :title="node.label">{{
            node.label
          }}</span>
          <span
            v-if="isShowBtn && data.id !== '-1'"
            class="text-btn__wrap"
            :class="data.isOpen ? 'isOpen' : ''"
          >
            <el-button
              type="text"
              class="btn-item"
              @click="handleTextBtn(node)"
              v-if="!data.isOpen"
              :disabled="data.disabledBtn"
              >本级及下级</el-button
            >
            <el-button
              type="text"
              class="btn-item theme-color"
              @click="handleTextBtn1(node)"
              :disabled="data.disabledBtn"
              v-if="data.isOpen == 1"
              >本级及下级</el-button
            >
          </span>

          <el-dropdown @command="handleCommand" v-if="!hideMenu">
            <span>
              <i class="icon-more" title="更多操作" />
            </span>
            <el-dropdown-menu slot="dropdown" v-show="!hideMenu">
              <template
                v-if="data.parentId != '' && data.alias != 'front_menu'"
              >
                <el-dropdown-item
                  icon="el-icon-circle-plus-outline"
                  v-if="
                    (!isFrontMenu(data) || isShowOperatBtn(data)) &&
                      !data.href &&
                      getMenuLevel(data) < 3
                  "
                  :command="{node: node, data, action: 'addHref'}"
                  >添加Url菜单</el-dropdown-item
                >
                <el-dropdown-item
                  icon="el-icon-plus"
                  v-if="!isFrontMenu(data) && getMenuLevel(data) < 3 && !data.href"
                  :command="{node: node, data, action: 'add'}"
                  >添加下级菜单</el-dropdown-item
                >
              </template>
              <template v-if="data.parentId != '' && isShowOperatBtn(data)">
                <el-dropdown-item
                  icon="el-icon-plus"
                  :command="{node: node, data, action: 'add', type: 'catalog'}"
                  >添加下级目录</el-dropdown-item
                >
                <!--前端的顶级菜单不允许添加1级菜单直接作为页面 -->
                <el-dropdown-item
                  v-if="data.parentId != ''"
                  icon="el-icon-plus"
                  :command="{node: node, data, action: 'add', type: 'page'}"
                  >添加下级页面</el-dropdown-item
                >
              </template>
              <el-dropdown-item
                icon="icon-autocomplete"
                v-if="data.children && data.children.length > 0"
                :command="{node: node, data, action: 'batchSort'}"
                >下级批量排序</el-dropdown-item
              >
              <template v-if="getMenuLevel(data) < 3">
                <el-dropdown-item
                  icon="el-icon-upload2"
                  v-if="!isFrontMenu(data) || isShowOperatBtn(data)"
                  :command="{node: node, data, action: 'import'}"
                  >导入</el-dropdown-item
                >
              </template>
              <el-dropdown-item
                icon="el-icon-download"
                v-if="data.parentId != '0'"
                :command="{node: node, data, action: 'export'}"
                >导出</el-dropdown-item
              >
              <el-dropdown-item
                icon="el-icon-edit"
                v-if="showEdit"
                :command="{node: node, data, action: 'edit'}"
                >编辑</el-dropdown-item
              >
              <el-dropdown-item
                icon="el-icon-delete"
                v-if="
                  data.parentId != '' &&
                    ((currentUser.userAttrs &&
                      currentUser.userAttrs.tenantId == data.tenantId) ||
                      data.tenantId == null)
                "
                :command="{node: node, data, action: 'delete'}"
                >删除</el-dropdown-item
              >
              <!-- <el-dropdown-item
                icon="el-icon-s-unfold"
                v-if="data.parentId!='0' && data.parentId!=''"
                divided
                :command="{node:node,data,action:'moveto'}"
              >移动至</el-dropdown-item> -->
            </el-dropdown-menu>
          </el-dropdown>
        </span>
      </ht-menu-tree>
    </el-aside>
  </div>
</template>

<script>
import styles from '@/assets/css/element-variables.scss'
const htMenuTree = () => import('@/components/system/HtMenuTree.vue')
import portalApi from '@/api/portal.js'
import {mapState} from 'vuex'
import utils from '@/hotent-ui-util.js'
export default {
  name: 'ht-menu-manager',
  components: {
    htMenuTree
  },
  props: {
    width: {
      type: String,
      default: styles.aside_width
    },
    supportFilter: {
      type: Boolean,
      default: true
    },
    showCheckbox: {
      type: Boolean,
      default: false
    },
    hideMenu: {
      type: Boolean,
      default: false
    },
    defaultCheckedKeys: {
      type: Array
    },
    defaultIsOpenKeys: {
      type: Array
    },
    nodeKey: {
      type: String,
      default: 'alias'
    },
    showEdit: {
      type: Boolean,
      default: true
    },
    isShowBtn: {
      type: Boolean,
      default: false
    },
    isExpandTree: {
      type: Boolean,
      default: true
    },
    filter: {
      type: Function,
      default(item) {
        return item.id !== '2' && item.id !== '4'
      }
    }
  },
  data() {
    return {
      asideShow: true,
      isExpand: this.isExpandTree, //树展开或折叠
      dialogVisible: false,
      parentSysType: {
        name: ''
      },
      treeData: [],
      currentKey: ''
      // btnMap: {
      //   current: '本级',
      //   currentAndSub: '本级及下级'
      // }
    }
  },
  computed: {
    ...mapState('login', ['currentUser']),
    navbarCollapseStyle: function() {
      if (this.asideShow) {
        return {left: parseInt(this.width) + 'px'}
      }
      return {left: '0px'}
    },
    isFrontMenu() {
      return data => {
        return data.path.startsWith('-1.3.')
      }
    },
    isPageMenu() {
      return data => {
        return data.type && data.type === 'page'
      }
    },
    getMenuLevel() {
      return data => {
        return data.path.split('.').length - 3
      }
    },
    isShowOperatBtn() {
      return data => {
        return this.isFrontMenu(data) && !this.isPageMenu(data) && !data.href
      }
    }
  },
  methods: {
    handleTextBtn(node) {
      this.$set(node.data, 'isOpen', 1)
      this.$set(node, 'expanded', false)
      this.$set(node, 'checked', true)
      this.$set(node, 'indeterminate', false)
      this.$set(node.data, 'disabled', true)
      if (node.data.children) {
        this.disabledElement(node.data.children, true)
      }
    },
    handleTextBtn1(node) {
      this.$set(node.data, 'isOpen', 0)
      this.$set(node, 'expanded', true)
      this.$set(node.data, 'disabled', false)
      if (node.data.children) {
        this.disabledElement(node.data.children, false)
      }
    },
    handleNodeClick(data, node) {
      this.$emit('node-click', data, node)
    },
    syncTree() {
      this.$refs.htMenuTree.loadData()
    },
    handleExpand() {
      this.isExpand = !this.isExpand
      let elTree = this.$refs.htMenuTree.$refs.htMenuTree.$refs.elTree
      for (var i = 0; i < elTree.store._getAllNodes().length; i++) {
        elTree.store._getAllNodes()[i].expanded = this.isExpand
      }
    },
    handleCommand(command) {
      let root = this.getParent(command.node)
      if (
        root.alias == 'manage_menu' &&
        command.node.level == 5 &&
        ['add', 'import'].includes(command.action)
      ) {
        return this.$message.warning('管理端不允许添加4级菜单')
      }
      if (
        root.alias == 'front_menu' &&
        command.node.level == 5 &&
        ['add', 'import', 'addHref'].includes(command.action)
      ) {
        return this.$message.warning('应用端不允许添加4级菜单')
      }
      this.$emit('menu-action', command)
    },
    getParent(data) {
      let res = true
      let _menus = data
      while (res) {
        if (
          _menus.parent &&
          _menus.data.alias != 'manage_menu' &&
          _menus.data.alias != 'front_menu'
        ) {
          _menus = _menus.parent
        } else {
          _menus = _menus.data
          res = false
        }
      }
      return _menus
    },
    handleClose() {
      this.dialogVisible = false
    },
    addAttribute(data) {
      // tree结构递归添加属性
      for (var i = 0; i < data.length; i++) {
        if (this.defaultIsOpenKeys) {
          for (var j = 0; j < this.defaultIsOpenKeys.length; j++) {
            if (this.defaultIsOpenKeys[j].alias == data[i].alias) {
              data[i].isOpen = 1
              data[i].expanded = false
              data[i].disabled = true
              if (data[i].children) {
                this.disabledElement(data[i].children, true)
              }
            }
          }
        } else {
          data[i].isOpen = 0
        }
        if (data[i].children && data[i].children.length > 0) {
          this.addAttribute(data[i].children)
        }
      }
      return data
    },
    disabledElement(value, isDisabled) {
      // tree结构递归添加属性
      for (var i = 0; i < value.length; i++) {
        // value[i].disabled = isDisabled
        this.$set(value[i], 'disabled', isDisabled)
        this.$set(value[i], 'disabledBtn', isDisabled)
        this.$set(value[i], 'checked', isDisabled)
        if (value[i].children && value[i].children.length > 0) {
          this.disabledElement(value[i].children, isDisabled)
        }
      }
      return value
    },
    loadData(cb) {
      portalApi
        .getMenuTree()
        .then(data => {
          let temp = utils.nestFilter(data, 'children', this.filter)
          this.treeData = this.addAttribute(temp) //递归给树添加isOpen属性
          this.$emit('meunTreeDataList', this.treeData)
        })
        .finally(() => {
          cb && cb()
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.menu-manage {
  padding: 24px;
}
>>> .navbar-collapse {
  position: relative;
  top: -60%;
  cursor: pointer;
  width: 20px;
}

>>> .el-dropdown {
  display: none;
}

>>> .el-tree-node__content:hover .el-dropdown {
  display: inline-block;
}
::v-deep {
  .menu-manage {
    .el-tree {
      background: #fff !important;
      border: 1px solid #e6e6e6;
      padding-bottom: 40px;
      width: calc(100% - 2px);
    }
  }

  .custom-tree-node {
    width: calc(100% - 40px);
    // flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
    .text-btn__wrap {
      .btn-item {
        padding-right: 6px;
        color: #999999;
        font-size: 12px;
      }
      .theme-color {
        color: $--color-primary;
      }
    }
  }
}

.custom-tree-node i {
  visibility: hidden;
  font-weight: bold;
}

.custom-tree-node:hover i {
  visibility: visible;
}
.isOpen {
  color: $--color-primary;
}
</style>
