<template>
  <div class="functionManagement">
    <bread-crumb :bread-crumb-list="breadCrumbList"></bread-crumb>
    <div class="tableCon">
      <!-- 搜索 -->
      <div class="tableTop">
        <el-form :inline="true" class="searchForms searchCommon">
          <el-form-item label="角色类型">
            <el-select class="typeSelect" v-model="typeValue" @change="selectChange" placeholder="请选择角色类型" style="width: 160px;">
              <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角色名称">
            <el-input v-model="logName" placeholder="请输入角色名称" style="width: 140px;" @keyup.enter.native="handelEnter"></el-input>
          </el-form-item>
          <el-form-item style="margin-right:0;">
            <el-button type="primary" icon="search" :loading="isQuery" @click="searchHandler">查询</el-button>
          </el-form-item>
        </el-form>
        <div class="btnHandle">
          <el-button type="info" size="small" @click="handleAddPart">添加角色</el-button>
          <!-- <el-button type="primary" style="background: #41b883;" @click="addEditPart('edit')">修改角色</el-button> -->
          <el-button type="danger" size="small" @click="deletePart">批量删除</el-button>
          <!-- <el-button type="primary" style="background: rgb(104, 179, 200);margin-left: 40px;" @click="editTree" :disabled="typeValue === '1'"><i class="el-icon-edit el-icon--left" style="margin-right: 8px;"></i>编辑权限树</el-button> -->
        </div>
      </div>
      <!-- 表格 -->
      <table-form
        v-loading.body="isLoadingTableData" 
        :colData="colData" :data="tableData" 
        :colWidth="120" 
        :row-key="rowKey" 
        :max-height="height" 
        :submiting="submiting" 
        :isShowOper="isShowOper" 
        border 
        :sortable="sortable" 
        @selection-change="handleSelectChange" 
        :row-class-name="tableRowClassName"
        >
        <el-table-column 
          v-if="reserveSelection" 
          :reserve-selection="reserveSelection" 
          type="selection" 
          width="55"
        >
        </el-table-column>
        <el-table-column 
          v-for="item in colData" 
          :key="item.prop" 
          :prop="item.prop" 
          :label="item.label" 
          :width="item.width" 
          :align="item.align" 
          :sortable="item.sortable || sortable"
        >
        </el-table-column>
        <el-table-column slot="fixedColumn" label="操作" fixed="right" width="300" align="center">
          <template slot-scope="scope">
            <el-button style="display:inline-block;margin-left:4px;"
              size="mini"
              plain
              @click="handleEdit($event, scope.row)">
              修改
            </el-button>
            <el-popover style="display:inline-block;margin-left:2px;"
              ref="popover"
              trigger="click"
              placement="top"
              width="160"
              v-model="scope.row.visible">
              <p style="font-size:14px;padding: 6px 0;">确定删除吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" @click="scope.row.visible = false">取消</el-button>
                <el-button type="primary" size="mini" :loading="submiting" @click="handleDelete(scope.row, scope.$index)">确定</el-button>
              </div>
        
              <div slot="reference">
                <el-button
                  size="mini"
                  type="danger"
                  plain
                  @click.stop.prevent="scope.row.visible = true">
                  删除
                </el-button>
              </div>
            </el-popover>
            <el-button
              type="info"
              plain
              style="display:inline-block;margin-left:8px;"
              size="mini"
              @click="handleEditTree($event, scope)">
              编辑权限树
            </el-button>
          </template>
        </el-table-column>
      </table-form>
      <!-- 分页 -->
      <el-row type="flex" justify="end" class="tableBottom">
        <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange" 
          :current-page="currentPage" 
          :page-sizes="pageSizes" 
          :page-size="pageSize" 
          layout="total, sizes, prev, pager, next, jumper" 
          :total="total">
        </el-pagination>
      </el-row>
    </div>
    <!-- 添加角色 或 编辑角色 -->
    <el-dialog v-loading.body="dialogLoading" element-loading-text="拼命加载中" class="addPartDialog addParts" :title="addEditTitle" top="10%" width="400px" v-if="partDialogVisible" :visible.sync="partDialogVisible">
      <el-form :model="partForm">
        <el-form-item label="角色名称">
          <el-input v-model="partForm.partName"></el-input>
        </el-form-item>
        <el-form-item label="角色说明">
          <el-input v-model="partForm.partExplain"></el-input>
        </el-form-item>
        <el-form-item label="角色类型">
          <el-input v-model="partForm.partType" readonly></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="partDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureAddEditPart">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 删除用户 -->
    <el-dialog title="删除角色" v-if="deleteDialogVisible" :visible.sync="deleteDialogVisible" top="15%" width="400px">
      <span>是否删除所选中的角色</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureDeleteRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 判断是否选择了数据 -->
    <el-dialog title="信息" v-if="isUserDialogVisible" :visible.sync="isUserDialogVisible" top="15%" width="400px">
      <span>请选择需要删除的角色</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="isUserDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 权限树 -->
    <el-dialog class="permissionTree" title="编辑权限树" v-if="permissionTreeVisible" :visible.sync="permissionTreeVisible" top="10%" width="400px">
      <multiselect-tree :node-key="moduleguid" :tree-data="treeData" :default-props="defaultProps" :default-expanded-keys="defaultExpandedKeys" :default-checked-keys="defaultCheckedKeys" :default-expand-all='defaultExpandAll' :edit-onoff="editOnoff" v-on:select-node="selectNode" v-loading.body="isLoadingTree" style="float: none;margin: auto">
      </multiselect-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="permissionTreeVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveTree">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import BreadCrumb from '@/components/BreadCrumb.vue'
import TableForm from '@/components/Table.vue'
import MultiselectTree from '@/components/MultiselectTree.vue'

import Api from '@/api/index.js'

export default {
  name: 'UserManagement',
  components: {
    BreadCrumb,
    TableForm,
    MultiselectTree
  },
  data () {
    return {
      dialogLoading: false,
      breadCrumbList: [], // 面包屑
      /* -- 表格数据 -- */
      isQuery: false,
      colData: [], // 表格信息
      tableData: [],
      rowKey: 'id',
      submiting: false,
      sortable: true,
      isShowOper: false,
      selectionData: [], // 已勾选数据列表
      /* --- 分页 -- */
      reserveSelection: true,
      currentPage: 1,
      pageSize: 15,
      pageSizes: [15, 30, 50, 100],
      total: null,
      height: '400',

      checkAll: true,

      /* ---头部查询数据--- */
      typeValue: '0', // 所选角色值
      typeOptions: [{ // 类型选择列表
        value: '0',
        label: '功能角色'
      } /* , {
        value: '1',
        label: '数据角色'
      } */],
      logName: '', // 登录名称

      loginduserguid: '', // 用户id
      organGuid: '', // 区域id
      isLoadingTableData: false,

      // 添加用户
      partForm: {
        partName: '',
        partExplain: '',
        partType: '功能角色'
      },
      formLabelWidth: '120px',
      addOrEdit: 'add', // 是添加还是修改
      partDialogVisible: false, // 添加角色 
      partDialogOnoff: true,
      deleteDialogVisible: false, // 删除角色
      deleteDialogOnoff: true,
      isUserDialogVisible: false, // 是否已选中数据
      isUserDialogOnoff: true,
      permissionTreeVisible: false, // 权限树
      permissionTreeOnoff: true,
      addEditTitle: '新增角色', // 

      // 权限树
      isLoadingTree: false,
      moduleguid: 'moduleguid',
      treeData: [],
      treeData1: [], // 功能角色
      treeData2: [], // 数据角色
      funcRoleId: [], // 功能角色树id
      dataRoleId: [], // 数据角色树id
      defaultProps: {
        children: 'childModuleinfos',
        label: 'modulename',
        isLeaf: 'nlevel'
      },
      defaultExpandedKeys: [], // 默认展开的树节点
      defaultCheckedKeys: [], // 默认勾选的树节点
      defaultExpandAll: true, // 默认展开所有
      roleId: '',
      editOnoff: false, // 编辑
      toDel: '', // 删除
      toIns: '', // 增加
      index: null // 当前行
    }
  },
  computed: {
    gisopUserInfo() {
      return this.$store.state.gisopUserInfo
    }
  },
  mounted() {
    this.breadCrumbList = [
      { title: '系统安全' },
      { title: '角色管理' }
    ]
    this.colData = [
      { prop: 'rolename', label: '角色名称', sortable: true, align: 'center' },
      { prop: 'roledescription', label: '角色描述', sortable: true, align: 'center' }
      /* { prop: 'userName', label: '创建用户', sortable: true, align: 'center'},
      { prop: 'lasttime', label: '创建日期', sortable: true, align: 'center'} */
    ]
    this.loginduserguid = this.gisopUserInfo.userguid
    if (this.loginduserguid === undefined) {
      return false
    } else {
      this.loginduserguid = this.loginduserguid.trim()
    }

    this.getPartList()
    this.getAllMotree()
  },
  watch: {
    gisopUserInfo (val) {
      if (val.userguid === undefined) {
        return false
      } else {
        this.loginduserguid = val.userguid.trim()
      }
    }
  },
  methods: {
    tableRowClassName (row, index) {
      if (index === this.index) {
        return 'info-row'
      }
      return ''
    },
    // 获取角色列表
    getPartList () {
      let userType = this.gisopUserInfo.type === '0' ? '' : '1'
      Api.getRoleViewList(this.currentPage, this.pageSize, this.logName, this.typeValue, userType)
        .then(data => {
          let datas = data.data
          if (data.status === 0) {
            if (datas.total > 0) {
              this.tableData = datas.result
              this.total = datas.total
            } else {
              this.tableData = []
              this.total = null
              this.$message({
                type: 'warning',
                message: '获取数据为空'
              })
            }
          } else {
            this.$message({
              type: 'error',
              message: '获取数据失败'
            })
          }
        }).catch(res => {
          this.$message({
            type: 'error',
            message: '获取数据失败'
          })
        })
    },
    // 当选项发生
    handleSelectChange (selection) {
      this.selectionData = []
      this.selectionData = selection
    },
    // 角色选择
    selectChange (val) {
      this.typeValue = val
      if (val === '0') {
        this.partForm.partType = '功能角色'
        this.treeData = this.treeData1
      } else {
        this.partForm.partType = '数据角色'
        this.treeData = this.treeData2
      }
      this.getPartList()
      this.index = null
    },
    // 查询
    searchHandler () {
      this.getPartList()
    },
    handelEnter () {
      this.searchHandler()
    },
    // 添加角色---弹窗
    handleAddPart () {
      this.addEditTitle = '新增角色'
      this.addOrEdit = 'add'
      this.partForm.partName = ''
      this.partForm.partExplain = ''
      this.partDialogVisible = true
    },
    // 确定添加或修改角色
    sureAddEditPart () {
      if (this.addOrEdit === 'add') { // 添加角色
        this.saveRole()
      } else if (this.addOrEdit === 'edit') { // 修改角色
        this.editRole()
      }
      this.partDialogVisible = false
      // this.getPartList()
    },
    // 修改
    handleEdit (e, scope) { 
      e.preventDefault()
      e.stopPropagation()

      this.addEditTitle = '修改角色'

      this.partForm.partName = scope.rolename
      this.partForm.partExplain = scope.roledescription
      this.roleId = scope.roleguid
      this.addOrEdit = 'edit'

      this.partDialogVisible = true
    },
    // 添加角色Api
    saveRole () {
      this.dialogLoading = true

      var formData = new FormData()
      formData.append('rolename', this.partForm.partName)
      formData.append('roledescription', this.partForm.partExplain)
      formData.append('type', this.typeValue)

      // this.loginduserguid,this.partForm.partName,this.partForm.partExplain,this.typeValue 
      Api.saveRole(formData)
        .then(data => {
          this.dialogLoading = false
          if (data.status === 0) {
            this.getPartList()
            this.$message({
              type: 'success',
              message: '添加角色成功'
            })
          } else {
            this.$message({
              type: 'error',
              message: '添加角色失败'
            })
          }
        }).catch(res => {
          this.$message({
            type: 'error',
            message: '添加角色失败'
          })
        })
    },
    // 修改角色Api
    editRole() {
      this.dialogLoading = true

      var formData = new FormData()
      formData.append('rolename', this.partForm.partName)
      formData.append('roledescription', this.partForm.partExplain)
      formData.append('type', this.typeValue)
      formData.append('roleguid', this.roleId)
      // this.loginduserguid,this.selectionData[0].roleGuid,this.partForm.partName,this.partForm.partExplain
      Api.editRole(formData)
        .then(data => {
          this.dialogLoading = false
          if (data.status === 0) {
            this.getPartList()
            this.$message({
              type: 'success',
              message: '修改角色成功'
            })
          } else {
            this.$message({
              type: 'error',
              message: '修改角色失败'
            })
          }
        }).catch(res => {
          this.$message({
            type: 'error',
            message: '获取数据失败'
          })
        })
    },
    // 删除角色Api
    deleteRole(id) {
      Api.deleteRole(id)
        .then(data => {
          if (data.status === 0) {
            this.getPartList()
            this.$message({
              type: 'success',
              message: '删除角色成功'
            })
          } else {
            this.$message({
              type: 'error',
              message: '删除角色失败'
            })
          }
        }).catch(res => {
          this.$message({
            type: 'error',
            message: '获取数据失败'
          })
        })
    },
    // 批量删除用户——弹窗
    deletePart() {
      if (this.selectionData.length > 0) {
        this.deleteDialogVisible = true
      } else {
        this.isUserDialogVisible = true
      }
    },
    // 确定批量删除删除角色
    sureDeleteRole() {
      let roleIdArr = []
      for (let i = 0; i < this.selectionData.length; i++) {
        roleIdArr.push(this.selectionData[i].roleguid)
      }
      this.deleteRole(roleIdArr.join(','))
      this.deleteDialogVisible = false
      this.getPartList()
    },
    // 确定删除
    handleDelete(scope, index) {
      this.deleteRole(scope.roleguid)
    },
    // 编辑权限树
    handleEditTree(e, scope) { 
      e.preventDefault()
      e.stopPropagation()
      this.roleId = scope.row.roleguid
      this.index = scope.$index
      this.permissionTreeVisible = true
      this.getAllRoleMoudle(scope.row.roleguid, this.typeValue)
    },
    // 功能角色权限树Api
    getAllMotree () {
      let yObj = localStorage.getItem('gisopUserInfo')
      let yId = JSON.parse(yObj).info.userguid.trim()
      Api.getAllCatalog(yId, 0).then(data => {
        if (data.status === 0) {
          this.treeData = data.data
          this.treeData1 = data.data
        } else {
          this.$message({
            type: 'error',
            message: '请求失败'
          })
        }
      })
    },
    // 数据角色权限树Api
    /* getAllDatatree () {
      Api.getAllDatatree(this.loginduserguid)
        .then(data => {
          if (data.status === 0) {
            this.treeData2 = data.results
          } else {
            this.$message({
              type: 'error',
              message: '删除角色失败'
            })
          }
        }).catch(res => {
          this.$message({
            type: 'error',
            message: '获取数据失败'
          })
        })
    }, */
    // 选中功能角色权限
    getAllRoleMoudle (roleId, roleType) {
      Api.getAllRoleMoudle(roleId, roleType)
        .then(data => {
          let datas = data.data
          if (data.status === 0) {
            if (datas.result !== null) {
              var dataArr = datas.split(',')
              this.funcRoleId = dataArr
              this.defaultCheckedKeys = dataArr
              // this.defaultExpandedKeys = data.results

              this.editOnoff = !this.editOnoff
            }
          }
        }).catch(res => {
          this.$message({
            type: 'error',
            message: '获取数据失败'
          })
        })
    },
    // 选中数据角色权限
    getAllRoleLayer (roleId) {
      Api.getAllRoleLayer(roleId)
        .then(data => {
          if (data.status === 0) {
            this.dataRoleId = data.data.result
            this.defaultCheckedKeys = data.data.result
            // this.defaultExpandedKeys = data.results

            this.editOnoff = !this.editOnoff
          } else {
            this.$message({
              type: 'error',
              message: '请求有误'
            })
            return false
          }
        }).catch(res => {
          this.$message({
            type: 'error',
            message: '获取数据失败'
          })
        })
    },
    // 保存选中功能角色权限
    savePermiss () {
      var moduleid = this.allSelectedNode.join()
      Api.savePermiss(this.roleId, moduleid)
        .then(data => {
          this.isLoadingTree = false
          this.permissionTreeVisible = false
          if (data.status === 0) {
            this.$message({
              type: 'success',
              message: '保存当前权限树成功'
            })
          }
        }).catch(res => {
          this.$message({
            type: 'error',
            message: '获取数据失败'
          })
        })
    },
    // 保存选中数据角色权限
    saveLayerInfo () {
      Api.saveLayerInfo(this.loginduserguid, this.roleId, this.toDel, this.toIns)
        .then(data => {
          if (data.status === 0) {
            this.$message({
              type: 'success',
              message: '保存当前权限树成功'
            })
          }
        }).catch(res => {
          this.$message({
            type: 'error',
            message: '获取数据失败'
          })
        })
    },

    // 分组
    grouping (dom) {
      var toDelArr = [],
        toInsArr = []
      for (var i = 0; i < this.allSelectedNode.length; i++) { // 增加
        if (dom.indexOf(this.allSelectedNode[i]) === -1) {
          toInsArr.push(this.allSelectedNode[i])
        }
      }
      for (var j = 0; j < dom.length; j++) { // 减少
        if (this.allSelectedNode.indexOf(dom[j]) === -1) {
          toDelArr.push(dom[j])
        }
      }
      this.toIns = toInsArr.join(',')
      this.toDel = toDelArr.join(',')
      console.log('增加/' + this.toIns)
      console.log('减少/' + this.toDel)
    },
    // 保存当前权限树
    saveTree() {
      this.isLoadingTree = true
      if (this.typeValue === '0') { // 功能
        // this.grouping(this.funcRoleId)
        this.savePermiss()
      } else {
        // this.grouping(this.dataRoleId) //数据
        this.saveLayerInfo()
      }
    },
    // 选择节点
    selectNode(allNodes) {
      this.allSelectedNode = allNodes
      // console.log(allNodes)
    },

    // 分页操作
    handleSizeChange(val) {
      this.pageSize = val
      if (this.tableData !== null) {
        this.getPartList()
      }
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      if (this.tableData !== null) {
        this.getPartList()
      }
    }
  }
}

</script>
<style lang="scss">
.functionManagement {
  width: 100%;
  position: relative;
  overflow: hidden;

  .tableCon {
    width: 100%;

    .tableTop {
      height: 60px;
      line-height: 38px;
      padding: 10px 10px;
      overflow: hidden;

      .searchForms {
        float: left;
      }
      .btnHandle {
        float: right;
      }
    }
    .tableBottom {
      padding: 15px 10px 0;
    }
  }
}

.addPartDialog {
  .el-dialog--small {
    width: 40%;
  }
  .el-dialog__header {
    padding: 20px 20px 0 20px;
    .el-dialog__title {
      color: #666;
    }
  }
  .el-dialog__body {
    padding: 20px 30px 10px 15px;
  }
  .el-form-item__label {
    width: 80px;
    float: left;
  }
  .el-form-item__content {
    width: 250px;
    float: left;
  }
  .el-form-item {
    margin-bottom: 18px;
  }
}

.permissionTree {
  .el-dialog__body {
    padding: 20px;
  }
}
</style>
