<template lang="pug">
    el-container(style="height:77.6vh")
        el-aside( width="18vw" v-loading="leftLoading" style="z-index:1000;box-shadow: 2px 0 8px 0 rgba(0, 0, 0, 0.2);")
            div.tree_warp
                div.title_warp
                    span.title-bold(style='padding-right:150px;margin-left:20px;z-index:1001;') 角色列表
                    el-button(type='primary' v-if="isAuth('sys:role:save')" size='mini' icon='el-icon-plus' @click="addOrUpdateHandle('')") 新增
                div.tree_content(v-for='item in tableData' :key='item.roleId' @click='chooseRole(item)' :class="{'isActive': ids == item.roleId}" )
                    el-tooltip(v-if="item.roleName.replace(/[\u0391-\uFFE5]/g,'aa').length>14" :content="item.roleName" effect="light" placement="top")
                        div.role_name {{item.roleName | ellipsis}}
                    div.role_name(v-else) {{item.roleName | ellipsis}}
                    div(style="width:50%;text-align:right;padding-right:20px")
                      el-button(v-if="isAuth('sys:role:update')" plain type='primary' size='mini'  @click="addOrUpdateHandle(item)") 编辑
                      el-button(v-if="isAuth('sys:role:delete')" plain type='primary' size='mini' style="margin-left:10px;" @click="delRole(item.roleId)") 删除
        el-container(style="height:77vh")
            el-header(style='height:42px;line-height:42px;background: #f4f4f4;z-index:1001;border:1px solid rgba(196, 196, 196, 1);')
                template()
                    span.title-bold.title-left-color  {{roleName ? roleName : '权限详情'}}&emsp;
                    el-checkbox(v-model="checked" @change="checkAll") 全选
            el-main().box_main
                el-card.tableCard( style='overflow:auto;box-sizing:border-box;' v-loading.fullscreen.lock="rightLoading")
                    div(v-loading="rightLoading1" class='div_tree')
                        el-tree(ref="tree"   @check-change="handleNodeClick" :render-content="renderContent"  @node-expand="handleNodeExpand" :default-expanded-keys="expandedKeys" :props="defaultProps" :data="videoData" show-checkbox node-key="menu_id")
                    div(style="margin-top:20px;")
                        el-button(type='primary' size='medium' v-if="isAuth('sys:role:update')" @click="saveRoleMenu" v-prevent-re-click) 保存
        add-or-update( v-if="addOrUpdateVisible" ref="addOrUpdate" @reFreshDataList="reFreshDataList")
</template>

<script>
import AddOrUpdate from './role-add-or-update'
// import Vue from 'vue'
export default {
  data() {
    return {
      rightLoading: false,
      clickFlag: false,
      ids: '',
      leftLoading: false,
      rightLoading1: false,
      selection: '',
      expandedKeys: [],
      addOrUpdateVisible: false,
      tableData: [],
      checked: false,
      isIndeterminate: true,
      roleName: '',
      activeNames: ['1'], //手风琴
      videoData: [],
      totalCount: 0,
      checkTotalCount: 0,
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  filters: {
    ellipsis(value) {
      // console.log(value)
      if (!value) return ''
      let len = value.length
      let realLength = 0
      for (var i = 0; i < len; i++) {
        let charCode = value.charCodeAt(i)
        if (charCode >= 0 && charCode <= 128) {
          realLength += 1
        } else {
          realLength += 2
        }
        if (realLength > 14) {
          return value.slice(0, i) + '...'
        }
      }
      return value
    }
  },
  components: {
    AddOrUpdate
  },
  watch: {
    checkTotalCount() {
      // console.log('全部:', this.totalCount, '选中:', this.checkTotalCount)
      if (this.checkTotalCount === this.totalCount) {
        this.checked = true
      } else {
        this.checked = false
      }
    }
  },
  created() {
    //查询角色信息
    this.getAllRole()
    this.getMenu()
  },
  mounted() {
     var legLast = document.querySelectorAll('.is-leaf')
         console.log('====log:', document)
      for (let i = 0; i < legLast.length; i++) {
        console.log('====log:===', legLast[i].html)
      }
  },
  methods: {
    reFreshDataList() {
      this.getAllRole()
      this.getMenu()
    },
    // 新增或修改
    addOrUpdateHandle(item) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(item)
      })
    },
    saveRoleMenu() {
      let checkedKeys = this.$refs.tree
        .getCheckedKeys()
        .concat(this.$refs.tree.getHalfCheckedKeys())
      // console.log(checkedKeys)
      let checkedRow = this.selection
      if (!checkedRow) {
        this.$message({
          type: 'warning',
          message: '请先选择角色！',
          duration: 1000
        })
        return
      }
      this.clickFlag = true
      this.rightLoading = true
      // console.log("checkedKeys", checkedKeys);
      // console.log("checkedRow", checkedRow);
      this.$http({
        url: this.$http.adornUrl(`/sys/menu/updateRoleMenu`),
        method: 'post',
        data: {
          roleId: checkedRow,
          menuIds: checkedKeys
        }
      }).then((data) => {
        if (data && data.code === 0) {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500
          })
        } else {
          this.$message.error(data.msg)
        }
        this.reFreshDataList()
        this.clickFlag = false
        this.rightLoading = false
      })
    },
    checkAll() {
      if (!this.checked) {
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys([])
        })
        this.checkTotalCount = 0
      } else {
        this.$nextTick(() => {
          if (this.videoData) {
            this.expandedKeys = this.videoData.map((item) => {
              return item.menu_id
            })
            this.$refs.tree.setCheckedKeys(this.expandedKeys)
          }
        })
        this.checkTotalCount = this.expandedKeys.length
      }
    },
    handleNodeClick() {
      this.checkTotalCount = this.$refs.tree.getCheckedKeys().length
    },
    handleNodeExpand(data) {
      for (let m = 0; m < data.children.length; m++) {
            this.$refs.tree.store.nodesMap[data.children[m].menu_id].expanded = true
      }
    },
    renderContent(h, { node, data }) {
     let nodeName = data.name
     if (node.level == 3) {
       return (<span class='lastLevel' style='font-size:11px;font-weight:100'>{nodeName}</span>)
     } else {
      return (<span style='font-size:14px;font-weight:600'>{nodeName}</span>)
     }
    },
    chooseRole(res) {
      this.clickFlag = false
      this.ids = res.roleId
      this.selection = res.roleId
      this.roleName = res.roleName
      this.$http({
        url: this.$http.adornUrl(`/sys/menu/getRoleMenu`),
        method: 'get',
        params: this.$http.adornParams({
          roleId: res.roleId
        })
      }).then((data) => {
        if (data && data.code === 0) {
          let list = data.list.map((item) => {
            return item.menu_id
          })
          this.$nextTick(() => {
            this.$refs.tree.setCheckedKeys(list)

            if (this.videoData) {
              this.expandedKeys = this.videoData.map((item) => {
                return item.menu_id
              })
            }
          })
          //this.checkTotalCount = data.count
        }
      })
    },
    getAllRole() {
      this.leftLoading = true
      this.$http({
        url: this.$http.adornUrl(`/sys/role/getRoleList`),
        method: 'get',
        params: this.$http.adornParams()
      }).then((data) => {
        if (data && data.code === 0) {
          this.tableData = data.list
          // let row = this.$refs.roleTable.data[0]
          // this.$refs.roleTable.setCurrentRow(row)
          // this.chooseRole(row)
        }
        this.leftLoading = false
      }).then(() => {
        this.$nextTick(() => {
          this.chooseRole(this.tableData[0])
        })
      })
    },
    getMenu() {
      this.rightLoading1 = true
      this.$http({
        url: this.$http.adornUrl(`/sys/menu/getMenu`),
        method: 'get',
        params: this.$http.adornParams()
      }).then((data) => {
        if (data && data.code === 0) {
          this.videoData = data.result
          // console.log(data.size, 'size')
          this.totalCount = data.size
          // this.totalCount = this.videoData.length
          // this.videoData.forEach(e => {
          //     if (e.children != null && e.children.length > 0) {
          //         this.totalCount += e.children.length
          //         e.children.forEach(j => {
          //             if (j.children != null && j.children.length > 0) {
          //                 this.totalCount += j.children.length
          //             }
          //         })
          //     }
          // })
        }
        this.rightLoading1 = false
      })
    },
    delRole(roleId) {
      this.$confirm('确认删除此角色?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.leftLoading = true
        let roleIds = [roleId]
        this.$http({
          url: this.$http.adornUrl(`/sys/role/delete`),
          method: 'POST',
          data: roleIds
        }).then((data) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500
            })
          } else {
            this.$message.error(data.msg)
          }
          this.getMenu()
          this.getAllRole()
          this.leftLoading = false
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.item {
  margin-bottom: 18px;
}
.is-leaf > span:nth-child(0){
  font-size:11px;
  font-weight: 100;
}
.tree_warp {
  overflow: auto;
  height: 100%;
  box-sizing: border-box;
  background: #f4f4f4;
  /*border-right: 1px solid rgba(195, 195, 195, 1);*/
  /*box-shadow: 2px 0 8px 0 rgba(0, 0, 0, 0.2);*/
  /*box-shadow: 2px 0 8px 0 red;*/

  .title_warp {
    height: 42px;
    line-height: 42px;
    background: #eef8ff;
    color: #333333;
  }

  .tree_content {
    display: flex;
    height: 40px;
    line-height: 40px;
    background: #fff;
    border-top-left-radius: 20px;
    border-bottom-left-radius: 20px;
    margin: 10px 10px 0 20px;
    // float: right;

    .role_name {
      margin-left: 20px;
      width: 50%;
      margin-left: 20px;
      font-size: 14px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      display: inline-block;
    }
  }
}

.isActive {
  background: #eef8ff !important;
}

.el-tree-node__content {
  height: 40px;

  .el-tree-node__expand-icon {
    position: relative;
    left: 126px;
  }
}
</style>
<style lang="scss">
.div_tree {
   background: #F6F7FB;
   border: 1px solid #EDEEF1;
   .el-tree-node__expand-icon.el-icon-caret-right:before{
     //position:absolute;
     //top:1x;
     //margin-left:120px;
      //display: none;
  }
   .el-tree-node__expand-icon.el-icon-caret-right:after{

     //display: inline-block;
  }
  .el-tree-node .el-tree-node__content  {

    // .el-tree-node__label {
    //   font-size: 14px;
    // }
     height: 40px;
     border-bottom:1px solid #EDEEF1;

    span.el-tree-node__label {
      font-size: 14px;
      font-family: Microsoft YaHei;
      height: 17px;
      font-weight: bold;
    }
  }
  .el-tree-node__children .el-tree-node__children .el-tree-node__content {
    float: left;
  }
  .el-tree-node__children{
    //margin-top: -40px;
    //margin-left: 10%;
  }
}
</style>
