<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form>
        <el-form-item>
          <el-input v-model="listQuery.roleName" placeholder="请输入角色名称" style="width: 260px" clearable @keyup.enter.native="handleFilter" />
          <el-button type="primary" icon="el-icon-search" @click="handleFilter">
            查询
          </el-button>
          <el-button type="primary" icon="el-icon-edit" @click="showCreate">
            添加
          </el-button>
          <el-button type="danger" icon="el-icon-delete" @click="deleteRole">
            删除
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table ref="list" :data="list" border fit highlight-current-row @row-click="onRowClick" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" />
      <el-table-column type="index" align="center" label="序号" width="80" />
      <el-table-column align="center" label="角色名称" prop="roleName" style="width: 60px;" />
      <el-table-column align="center" label="创建时间" prop="createTime" style="width: 60px;" />
      <el-table-column align="center" label="最近修改时间" prop="updateTime" style="width: 60px;" />
      <el-table-column align="center" label="管理" width="180">
        <template slot-scope="scope">
          <el-button :disabled="scope.row.id === 1" type="primary" icon="edit" @click="showUpdate(scope.$index)">
            修改
          </el-button>
          <el-button type="warning" icon="edit" @click="showUserAuth(scope.$index)">
            授权
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="totalCount>0" :total="totalCount" :page-num.sync="listQuery.pageNum" :page-row.sync="listQuery.pageSize" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="1100px">
      <el-form ref="tempRole" :model="tempRole" class="small-space" label-position="left" label-width="80px" style="margin-left:50px;height: 600px;overflow: auto;">
        <el-form-item label="角色名称" required>
          <el-input v-model="tempRole.roleName" type="text" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="角色代码" required>
          <el-input v-model="tempRole.roleCode" type="text" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="所属资源" required>
          <div>
            <el-row>
              <el-col :span="4">
                <div v-for="(menu, _index) in allPermission" :key="menu.permission.name">
                  <span style="display: inline-block;">
                    <el-button
                      :type="isMenuNone(menu.permission.id)?'':(isMenuAll(menu.permission.id)?'success':'primary')"
                      size="mini"
                      style="width:100px;"
                      @click="checkOneList(_index)"
                    >{{ menu.permission.title }}</el-button>
                  </span>
                </div>
              </el-col>
              <hr style="float: left;height: 780px;margin-top:10px;margin-bottom:10px;margin-right: 30px;border: 1px solid #00ffff;">
              <el-col :span="18">
                <div v-for="(menu2) in allPermissionVOList" :key="menu2.permission.name">
                  <span style="display: inline-block;">
                    <el-button
                      :type="isMenuNone(menu2.permission.pid,menu2.permission.id)?'':(isMenuAll(menu2.permission.pid,menu2.permission.id)?'success':'primary')"
                      size="mini"
                      @click="checkAll(menu2.permission.pid,menu2.permission.id)"
                    >{{ menu2.permission.title }}</el-button>
                  </span>
                  <div style="display: inline-block;margin-left:20px;">
                    <el-checkbox-group v-model="permissionList">
                      <el-checkbox v-for="perm in menu2.resourcePermissionList" :key="perm.id" :label="perm.id">
                        <span>{{ perm.permissionType }}</span>
                      </el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button v-if="dialogStatus==='create'" type="success" @click="createRole">
          创 建
        </el-button>
        <el-button v-else type="primary" @click="updateRole">
          修 改
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="1100px">
      <el-form ref="tempRole" :model="tempRole" class="small-space" label-position="left" label-width="100px" style="margin-left:50px;height: 600px;overflow: auto;">
        <el-form-item label="角色名称" required>
          <el-input v-model="tempRole.roleName" type="text" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="角色代码" required>
          <el-input v-model="tempRole.roleCode" type="text" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="功能权限：">
          <el-table
            ref="menuList"
            :data="allPermission"
            border
            fit
            highlight-current-row
            row-key="permission.id"
            :default-expand-all="true"
            :tree-props="{children: 'allPermissionVOList', hasChildren: 'hasChildren'}"
          >
            <el-table-column label="菜单名称" width="180">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.checked" @change="handleCheckAllChange(scope.row, $event)">
                  {{ scope.row.permission.title }}
                </el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="功能选项">
              <template slot-scope="scope">
                <el-checkbox
                  v-for="options in scope.row.resourcePermissionList"
                  :key="options.id"
                  v-model="options.permissionId"
                  :label="options.permissionType"
                  @change="handleCheckChange(scope.row)"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button v-if="dialogStatus==='create'" type="success" @click="createRole">
          创 建
        </el-button>
        <el-button v-else type="primary" @click="updateRole">
          修 改
        </el-button>
      </div>
    </el-dialog>
    <!-- 用户授权窗口 -->
    <el-dialog :title="'角色授权'" :visible.sync="authDialogFormVisible">
      <el-container>
        <el-header>
          <el-form>
            <el-form-item>
              <el-input v-model="userListQuery.nickname" placeholder="昵称" clearable style="width: 200px" @keyup.enter.native="userHandleFilter" />
              <el-input v-model="userListQuery.username" placeholder="用户名" clearable style="width: 100px" @keyup.enter.native="userHandleFilter" />
              <el-select v-model="userListQuery.departmentId" placeholder="请选择科室" clearable @keyup.enter.native="userHandleFilter">
                <el-option v-for="dept in depts" :key="dept.id" :label="dept.name" :value="dept.id" />
              </el-select>
              <el-switch v-model="userListQuery.isHasRole" active-color="#13ce66" inactive-color="#ff4949" active-text="已授权" inactive-text="全部" @change="userHandleFilter" />
              <el-button type="primary" icon="el-icon-search" @click="userHandleFilter">
                查询
              </el-button>
            </el-form-item>
          </el-form>
        </el-header>
        <el-main style="margin-top: -30px">
          <el-table :data="userList" height="500" border fit highlight-current-row>
            <el-table-column type="index" align="center" label="序号" width="80" />
            <el-table-column align="center" label="昵称" prop="nickname" style="width: 60px;" />
            <el-table-column align="center" label="用户名" prop="username" style="width: 60px;" />
            <el-table-column align="center" label="授权状态" prop="roleId" style="width: 60px;">
              <template slot-scope="scope">
                <span v-if="scope.row.roleIds.split(',').find(roleId => Number(roleId) === tempRole.id)" style="color: #333">已授权</span>
                <span v-else style="color: #FF6347">未授权</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="管理" width="220">
              <template slot-scope="scope">
                <el-button :disabled="!!scope.row.roleIds.split(',').filter(roleId => Number(roleId) === tempRole.id)[0] || scope.row.username === 'admin'" type="success" icon="el-icon-check" circle @click="authRole(scope.$index)" />
                <el-button :disabled="!scope.row.roleIds.split(',').filter(roleId => Number(roleId) === tempRole.id)[0] || scope.row.username === 'admin'" type="danger" icon="el-icon-close" circle @click="unAuthRole(scope.$index)" />
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="userTotalCount>0" :total="userTotalCount" :page-num.sync="userListQuery.pageNum" :page-row.sync="userListQuery.pageSize" @pagination="getUserList" />
        </el-main>
      </el-container>
    </el-dialog>
  </div>
</template>
<script>
import qs from 'qs'
import Pagination from '@/components/Pagination'
export default {
  name: 'RoleList',
  components: { Pagination },
  data() {
    return {
      list: [],
      totalCount: 0,
      dialogStatus: 'create',
      dialogFormVisible: false,
      userList: [],
      userTotalCount: 0,
      authDialogFormVisible: false,
      userListQuery: {
        pageNum: 1,
        pageSize: 20
      },
      listQuery: {
        pageNum: 1,
        pageSize: 20
      },
      textMap: {
        update: '编辑',
        create: '新建角色'
      },
      tempRole: {},
      allPermission: [],
      menuNameList: [],
      permissionList: [],
      depts: [],
      allPermissionVOList: [],
      checkedIds: new Set()
    }
  },
  created() {
    this.getList()
    this.getAllPermission()
    this.getDepartment()
  },
  methods: {
    getList() {
      // 查询列表
      this.api({
        url: '/role/list',
        method: 'get',
        params: this.listQuery
      }).then(data => {
        this.list = data.list
        this.totalCount = data.total
      })
    },
    getUserList() {
      // 查询列表
      this.api({
        url: '/user/list',
        method: 'get',
        params: this.userListQuery,
        paramsSerializer: function(params) {
          return qs.stringify(params, { indices: false })
        }
      }).then(data => {
        this.userList = data.list
        this.userTotalCount = data.total
      })
    },
    // 查询检验科室
    getDepartment() {
      this.api({
        url: '/department/all',
        method: 'get'
      }).then(data => {
        this.depts = data
      })
    },
    getAllPermission() {
      this.api({
        url: '/permission/getAllPermissionList',
        method: 'get'
      }).then(data => {
        this.allPermission = data
        if (this.allPermission.length > 0) {
          this.allPermissionVOList = this.allPermission[0].resourcePermissionList
        }
      })
    },
    onRowClick(row) {
      this.$refs.list.toggleRowSelection(row)
    },
    handleSelectionChange: function(val) {
      this.multipleSelection = val
    },
    showCreate() {
      this.tempRole = {}
      this.permissionList = []
      if (this.allPermission.length > 0) {
        this.allPermissionVOList = this.allPermission[0].allPermissionVOList
      }
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleFilter() {
      // 查询事件
      this.listQuery.pageNum = 1
      this.getList()
    },
    userHandleFilter() {
      this.userListQuery.pageNum = 1
      if (this.userListQuery.isHasRole) {
        this.userListQuery.roleIds = [this.tempRole.id]
      } else {
        delete this.userListQuery.roleIds
      }
      this.getUserList()
    },
    createRole() {
      if (!this.checkRoleNameUnique()) {
        return
      }
      if (!this.checkPermissionNum()) {
        return
      }
      this.tempRole.resourcePermissionIds = this.permissionList
      // 添加新角色
      this.api({
        url: '/role',
        method: 'post',
        data: this.tempRole
      }).then(() => {
        this.$message.success('添加成功。')
        this.getList()
        this.dialogFormVisible = false
      })
    },
    showUpdate($index) {
      this.tempRole = this.list[$index]
      this.getPermissionsByRoleId(this.tempRole.id)
      if (this.allPermission.length > 0) {
        this.allPermissionVOList = this.allPermission[0].allPermissionVOList
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    updateRole() {
      if (!this.tempRole.roleName) {
        this.$message.error('请填写角色名称')
        return false
      }
      if (!this.checkPermissionNum()) {
        return
      }
      this.tempRole.resourcePermissionIds = this.permissionList
      // 修改角色
      this.api({
        url: '/role',
        method: 'put',
        data: this.tempRole
      }).then(() => {
        this.$message.success('更新成功。')
        this.getList()
        this.dialogFormVisible = false
      })
    },
    getPermissionsByRoleId(id) {
      this.api({
        url: '/permission/getPermissionsByRoleId',
        method: 'get',
        params: {
          roleId: id
        }
      }).then(data => {
        if (data !== null && data.length > 0) {
          const checkedArray = []
          data.forEach(rolePermission => {
            checkedArray.push(rolePermission.resourcePermissionId)
          })
          this.permissionList = checkedArray
        } else {
          this.permissionList = []
        }
      })
    },
    showUserAuth($index) {
      this.authDialogFormVisible = true
      const role = this.list[$index]
      this.tempRole.id = role.id
      this.tempRole.roleName = role.roleName
      this.userListQuery = {}
      this.getUserList()
    },
    authRole($index) {
      const user = this.userList[$index]
      user.password = null
      user.signPassword = null
      const roleIds = []
      user.roleIds.split(',').forEach(roleId => roleIds.push(Number(roleId)))
      roleIds.push(this.tempRole.id)
      this.api({
        url: '/user',
        method: 'put',
        data: {
          user: user,
          roleIds: roleIds
        }
      }).then(() => {
        this.getUserList()
      })
    },
    unAuthRole($index) {
      const user = this.userList[$index]
      user.roleId = null
      const roleIds = []
      user.roleIds.split(',').forEach(roleIdStr => {
        const roleId = Number(roleIdStr)
        if (roleId !== this.tempRole.id) {
          roleIds.push(roleId)
        }
      })
      this.api({
        url: '/user',
        method: 'put',
        data: {
          user: user,
          roleIds: roleIds
        }
      }).then(() => {
        this.getUserList()
      })
    },
    deleteRole() {
      if (this.multipleSelection.length <= 0) {
        this.$message.warning('请选择要删除的数据。')
        return
      }
      const pks = []
      const qs = require('qs')
      this.multipleSelection.forEach(role => {
        pks.push(role.id)
      })
      this.$confirm('删除角色会清空该角色下用户的权限，确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        showCancelButton: '取消',
        type: 'warning'
      }).then(() => {
        this.api({
          url: '/role',
          method: 'delete',
          params: {
            pks: pks
          },
          paramsSerializer: function(params) {
            return qs.stringify(params, { indices: false })
          }
        }).then(() => {
          this.$message.success('删除成功。')
          this.getList()
        })
      })
    },
    getMenu(id, _index2) {
      const menu = []
      let allVoList = []
      if (id) {
        this.allPermission.forEach(data => {
          if (id === data.permission.id) {
            allVoList = data.allPermissionVOList
          }
        })
      }
      if (allVoList) {
        allVoList.forEach(data => {
          if (_index2) {
            if (_index2 === data.permission.id && data.resourcePermissionList.length > 0) {
              data.resourcePermissionList.forEach(ad => {
                menu.push(ad)
              })
            }
          } else {
            data.resourcePermissionList.forEach(ad => {
              menu.push(ad)
            })
          }
        })
      }
      return menu
    },
    // 判断本级菜单内的权限是否一个都没选
    isMenuNone(id, _index2) {
      const menu = this.getMenu(id, _index2)
      let result = true
      for (let j = 0; j < menu.length; j++) {
        if (this.permissionList.indexOf(menu[j].id) > -1) {
          result = false
          break
        }
      }
      return result
    },
    checkOneList(_index) {
      this.allPermissionVOList = this.allPermission[_index].allPermissionVOList
    },
    // 判断本级菜单内的权限是否全选了
    isMenuAll(id, _index2) {
      const menu = this.getMenu(id, _index2)
      let result = true
      for (let j = 0; j < menu.length; j++) {
        if (this.permissionList.indexOf(menu[j].id) < 0) {
          result = false
          break
        }
      }
      return result
    },
    checkAll(id, _index2) {
      // 点击菜单   相当于全选按钮
      const v = this
      if (v.isMenuAll(id, _index2)) {
        // 如果已经全选了,则全部取消
        v.noPerm(_index2)
      } else {
        // 如果尚未全选,则全选
        v.allPerm(_index2)
      }
    },
    getPerm(_index) {
      let menu = []
      if (_index) {
        this.allPermissionVOList.forEach(da => {
          if (_index === da.permission.id) {
            menu = da.resourcePermissionList
          }
        })
      }
      return menu
    },
    allPerm(_index) {
      const menu = this.getPerm(_index)
      // 全部选中
      for (let j = 0; j < menu.length; j++) {
        this.addUnique(menu[j].id, this.permissionList)
      }
    },
    noPerm(_index) {
      const menu = this.getPerm(_index)
      // 全部取消选中
      for (let j = 0; j < menu.length; j++) {
        const idIndex = this.permissionList.indexOf(menu[j].id)
        if (idIndex > -1) {
          this.permissionList.splice(idIndex, 1)
        }
      }
    },
    addUnique(val, arr) {
      // 数组内防重复地添加元素
      const _index = arr.indexOf(val)
      if (_index < 0) {
        arr.push(val)
      }
    },
    checkPermissionNum() {
      // 校验至少有一种权限
      if (this.permissionList.length === 0) {
        this.$message.error('请至少选择一种权限')
        return false
      }
      return true
    },
    checkRoleNameUnique(roleId) {
      // 校验名称重复
      const roleName = this.tempRole.roleName
      if (!roleName) {
        this.$message.error('请填写角色名称')
        return false
      }
      const roles = this.list
      let result = true
      for (let j = 0; j < roles.length; j++) {
        if (roles[j].roleName === roleName && (!roleId || roles[j].roleId !== roleId)) {
          this.$message.error('角色名称已存在')
          result = false
          break
        }
      }
      return result
    },
    handleCheckAllChange(val, checked) {
      console.log(val, '是啥')
      // 有下级去处理下级
      if (val.allPermissionVOList.length > 0) {
        if (checked) {
          this.checkedIds.add(val.resourcePermissionList[0].id)
        } else {
          this.checkedIds.delete(val.resourcePermissionList[0].id)
        }
        this.findChildren(val.allPermissionVOList, checked)
      } else {
        // 无下级处理本级
        val.resourcePermissionList.forEach(options => {
          options.checked = checked
          if (checked) {
            this.checkedIds.add(options.id)
          } else {
            this.checkedIds.delete(options.id)
          }
        })
      }
      // 处理上级
      if (val.permission.id !== 0) {
        this.findParent(this.allPermission, val.permission.parentId)
      }
      val.indeterminate = false
    },
    handleCheckChange(val) {
      const length = val.resourcePermissionList.length
      let checkedLength = 0
      val.resourcePermissionList.forEach(options => {
        if (options.checked) {
          this.checkedIds.add(options.id)
          checkedLength++
        } else {
          this.checkedIds.delete(options.id)
        }
      })
      val.checked = checkedLength === length
      val.indeterminate = checkedLength > 0 && checkedLength < length
      // 处理上级
      if (val.menu.parentId !== 0) {
        this.findParent(this.menuList, val.menu.parentId)
      }
    },
    findChildren(list, checked) {
      list.forEach(children => {
        children.checked = checked
        children.indeterminate = false
        children.resourcePermissionList.forEach(options => {
          options.checked = checked
          if (checked) {
            this.checkedIds.add(options.id)
          } else {
            this.checkedIds.delete(options.id)
          }
          if (children.children.length > 0) {
            this.findChildren(children.children, checked)
          }
        })
      })
    },
    findParent(list, parentId) {
      list.forEach(result => {
        let parentCheckedLength = 0
        let parentIndeterminateLength = 0
        // 对当前层级的上级操作
        if (result.menu.id === parentId) {
          // 判断下级的状态，用来为父级的状态做判断
          result.children.forEach(children => {
            if (children.indeterminate) {
              parentIndeterminateLength++
            } else if (children.checked) {
              parentCheckedLength++
            }
          })
          result.checked = parentCheckedLength === result.children.length
          result.indeterminate = (parentIndeterminateLength > 0 || parentCheckedLength > 0) && parentCheckedLength < result.children.length
          if (result.checked || result.indeterminate) {
            this.checkedIds.add(result.resourcePermissionList[0].id)
          } else {
            this.checkedIds.delete(result.resourcePermissionList[0].id)
          }
          // 如果还有上级，继续操作
          if (result.menu.parentId !== 0) {
            this.findParent(this.menuList, result.menu.parentId)
          }
        } else if (result.children.length > 0) {
          this.findParent(result.children, parentId)
        }
      })
    },
    echoChildren(list, optionsIds) {
      list.forEach(result => {
        if (result.children.length === 0) {
          this.settingChecked(result, optionsIds)
        } else {
          this.echoChildren(result.children, optionsIds)
        }
      })
    },
    settingChecked(result, optionsIds) {
      let matching = false
      result.resourcePermissionList.forEach(options => {
        optionsIds.forEach(optionsId => {
          if (options.id === optionsId) {
            options.checked = true
            matching = true
          }
        })
      })
      if (matching) {
        this.handleCheckChange(result)
      }
    },
    // 递归清空菜单和选项
    clearChecked(menuList) {
      menuList.forEach(menu => {
        menu.checked = false
        menu.indeterminate = false
        menu.resourcePermissionList.forEach(options => {
          options.checked = false
        })
        if (menu.children.length > 0) {
          this.clearChecked(menu.children)
        }
      })
    }
  }
}
</script>
