<template>
  <div class="app-container role_setup">
    <div class="filter-container">
      <el-input v-model="keyword" placeholder="请输入角色代码" class="filter-item"/>
      <el-button type="primary" class="filter-item" icon="el-icon-search" @click="btn_search">搜索</el-button>
      <el-button v-permission="'HY_add'" type="primary" class="filter-item" icon="el-icon-plus" @click="btn_add">添加</el-button>
      <el-button v-permission="'HY_edit'" type="primary" class="filter-item" icon="el-icon-edit" @click="btn_edit">编辑</el-button>
      <el-button v-permission="'HY_delete'" type="primary" class="filter-item" icon="el-icon-delete" @click="btn_delete">删除</el-button>
      <el-button v-permission="'HY_save'" type="primary" class="filter-item" @click="btn_save"><svg-icon icon-class="baocun" />保存角色权限</el-button>
    </div>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-alert
          :closable="false"
          title="角色列表"
          type="success"/>
        <el-table
          v-loading="loading"
          :data="roleLists"
          border
          stripe
          highlight-current-row
          @row-click="handleTableClick">
          <el-table-column type="index" label="编号" align="center" fixed width="80"/>
          <el-table-column prop="F_RoleName" label="用户角色" align="center" min-width=""/>
          <el-table-column prop="F_RoleCode" label="角色代码" align="center" min-width=""/>
          <el-table-column prop="F_CreateOn" label="创建时间" align="center" min-width=""/>
          <el-table-column prop="F_LastModifyOn" label="最后修改时间" align="center" min-width=""/>
          <el-table-column prop="F_Remark" label="备注" align="center" min-width=""/>
        </el-table>
        <pagination
          v-show="pageParams.total > 0"
          :total="pageParams.total"
          :pageindex.sync="pageParams.pageindex"
          :pagesize.sync="pageParams.pagesize"
          class="pagination"
          @pagination="getList" />
      </el-col>
      <el-col :span="12">
        <el-alert
          :closable="false"
          title="权限树"
          type="success"/>
        <el-tree
          ref="treeRef"
          :data="treelists"
          show-checkbox
          node-key="id"
          check-strictly
          highlight-current/>
      </el-col>
    </el-row>
  </div>
</template>

<script>

import { getRoleLists, deleteRole, saveRoleList, getRoleTree } from '@/api/systemSetup/roleSetting/roleSetup'
import addOrEditRole from './addOrEditRole'
import { pickerOptions } from '@/utils'
import Pagination from '@/components/Pagination' // 对el-pagination 二次封装

export default {
  name: 'RoleSetup',
  components: {
    Pagination
  },
  data() {
    return {
      loading: false,
      searchDate: '',
      keyword: '',
      pageParams: {
        pageindex: 1, // 当前第几页
        pagesize: Number(this.$store.getters.serverConfig.PAGESIZE), // 每页几条数据
        total: 0 // 总共多少数据
      },
      pickerOptions, // 日期选择器快捷选项
      roleLists: [], // 角色列表数据
      treelists: [], // 菜单树数据
      role_id: '' // 角色id
    }
  },
  created() {
    this.getList().then(() => {
      this.getTreeList()
    })
    document.onkeyup = (e) => {
      if (e.keyCode === 13) {
        this.getList()
      }
    }
  },
  methods: {
    getList() {
      this.loading = true
      return new Promise(resolve => {
        const params = {
          pageindex: this.pageParams.pageindex, // 第几页
          pagesize: this.pageParams.pagesize, // 每页几条信息
          keyword: this.keyword.replace(/\s+/g, ''), //	项目名称，项目类型，项目负责人
          stime: this.searchDate && this.searchDate[0],
          etime: this.searchDate && this.searchDate[1]
        }
        getRoleLists(params).then(response => {
          this.loading = false
          if (response.state.toLowerCase() === 'success') {
            this.pageParams.total = response.data.Totals
            this.roleLists = response.data.Rows
            this.$refs.treeRef.setCheckedKeys([])// 清空权限树的选中状态
            this.role_id = ''
          }
        })
        resolve()
      })
    },
    // 点击某一行的table
    handleTableClick(row, event, column) {
      this.role_id = row.F_RoleId
      this.getTreeList()
    },
    btn_search() {
      this.pageParams.pageindex = 1
      this.getList()
    },
    btn_add() {
      this.$layer.iframe({
        content: {
          content: addOrEditRole, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: { 'rowid': '' }// props//该方法会自动添加一个key为layerid的值， 该值为创建层的id， 可以直接使用
        },
        area: ['40%', '400px'],
        shadeClose: false,
        title: '添加用户角色'
      })
    },
    btn_edit() {
      if (!this.role_id) {
        this.$message.warning('请先选择要编辑的用户角色!')
        return
      }
      this.$layer.iframe({
        content: {
          content: addOrEditRole, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: { 'rowid': this.role_id }// props//该方法会自动添加一个key为layerid的值， 该值为创建层的id， 可以直接使用
        },
        area: ['40%', '400px'],
        shadeClose: false,
        title: '编辑用户角色'
      })
    },
    btn_delete() {
      if (!this.role_id) {
        this.$message.warning('请先选择要删除的用户角色!')
        return
      }
      if (this.role_id === '5aaa5a54b9c1893cb015df26') {
        this.$message.warning('系统维护不能删除!')
        return
      }
      this.$confirm('此操作将永久删除当前角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole(this.role_id).then(response => {
          if (response.state.toLowerCase() === 'success') {
            this.getList()
            this.$message.success('删除成功!')
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    btn_save() {
      if (!this.role_id) {
        this.$message.warning('请先选择用户角色!')
        return
      }
      if (this.$refs.treeRef.getCheckedKeys().length === 0) {
        this.$message.warning('请选择权限!')
        return
      }
      // console.log(this.$refs.treeRef.getCheckedKeys())//返回目前被选中的节点的 key 所组成的数组
      saveRoleList({
        role_id: this.role_id, // 角色id
        ids: this.$refs.treeRef.getCheckedKeys()//	选中权限树的id值,
      }).then(response => {
        if (response.state.toLowerCase() === 'success') {
          this.$message.success('恭喜你，角色权限保存成功!')
        }
      })
    },
    // 权限树
    getTreeList() {
      return new Promise(resolve => {
        getRoleTree(this.role_id).then(response => {
          if (response.state.toLowerCase() === 'success') {
            this.treelists = this.buildTree(response.data)
            if (this.role_id) {
              // 获取ischecked数组 设置选中
              const checkedKeys = this.getIsChecked(response.data)
              this.$refs.treeRef.setCheckedKeys(checkedKeys)
            }
          }
        })
        resolve()
      })
    },
    // 获取ischecked数组 设置选中
    getIsChecked(checkeds) {
      const checkedArr = []
      for (let i = 0, len = checkeds.length; i < len; i++) {
        if (checkeds[i].ischecked === true) {
          checkedArr.push(checkeds[i].id)
        }
      }
      return checkedArr
    },
    /**
		* 将一维的扁平数组转换为多层级对象
		* @param  {[type]} list 一维数组，数组中每一个元素需包含id和pid两个属性
		* @return {[type]} tree 多层级树状结构
		*/
    buildTree(list) {
      const temp = {}
      const tree = {}
      const arr = []
      for (const j in list) {
        temp[list[j].id] = list[j]
      }
      for (const i in temp) {
        // if (temp[i].pid !== 'Moudle_000000000000000000000000') {
        if (temp[i].pid !== 'Moudle_0') {
          if (!temp[temp[i].pid].children) {
            temp[temp[i].pid].children = []
          }
          temp[temp[i].pid].children[temp[i].id] = temp[i]
        } else {
          tree[temp[i].id] = temp[i]
        }
      }
      return this.filterTreeDatas(tree)
    },
    // 处理数据格式
    filterTreeDatas(treeDatas) {
      const accessedRouters = []
      let j = -1
      for (const i in treeDatas) {
        j++
        accessedRouters.push({
          id: treeDatas[i].id,
          label: treeDatas[i].name,
          children: []
        })
        if (treeDatas[i].children) {
          accessedRouters[j].children = this.filterTreeDatas(treeDatas[i].children)
        }
      }

      return accessedRouters
    }
  }
}
</script>

<!-- 需要注意的是，修改elementUI的默认样式的css不能使用scoped. -->
<style rel="stylesheet/scss" lang="scss">
	.role_setup{
		.el-table tr{
			cursor: pointer;
		}
		.el-table__body tr.current-row>td {
			background: rgba(185, 221, 249, .75);
		}
	}
</style>
<style rel="stylesheet/scss" lang="scss" scoped>

</style>
