<template>
  <!-- 分配角色数据权限对话框 -->
  <el-dialog append-to-body :close-on-click-modal="false" :title="title" :visible.sync="openDataScope" width="500px">
    <el-form ref="form" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="角色名称">
        <el-input v-model="form.roleName" :disabled="true" />
      </el-form-item>
      <el-form-item label="权限字符">
        <el-input v-model="form.roleKey" :disabled="true" />
      </el-form-item>

      <el-form-item label="权限范围">
        <el-select v-model="form.dataScope">
          <el-option v-for="item in dataScopeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item v-show="form.dataScope == 2" label="数据权限">
        <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
        <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选</el-checkbox>
        <el-checkbox v-model="form.deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">
          父子联动
        </el-checkbox>
        <el-tree
          ref="dept"
          :check-strictly="!form.deptCheckStrictly"
          class="tree-border"
          :data="treeList"
          default-expand-all
          empty-text="加载中，请稍后"
          node-key="id"
          :props="deptProps"
          show-checkbox />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitDataScope">确 定</el-button>
      <el-button @click="close">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import roleApi from '@/api/system/role'
  import deptApi from '@/api/system/dept'

  export default {
    name: 'RoleEdit',
    data() {
      return {
        form: {},
        rules: {},
        title: '',
        dialogFormVisible: false,
        treeList: [],
        // 是否显示弹出层（数据权限）
        openDataScope: false,
        deptExpand: true,
        deptNodeAll: false,
        deptProps: {
          children: 'children',
          label: 'deptName',
        },
        // 数据范围选项
        dataScopeOptions: [
          {
            value: '10',
            label: '全部数据权限',
          },
          {
            value: '20',
            label: '自定数据权限',
          },
          {
            value: '30',
            label: '本部门数据权限',
          },
          {
            value: '40',
            label: '本部门及以下数据权限',
          },
          {
            value: '50',
            label: '仅本人数据权限',
          },
        ],
      }
    },
    created() {
      this.getDeptTreeselect()
    },
    methods: {
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.openDataScope = false
      },
      /** 获取详情 */
      async getEntityById(id) {
        const { data: data } = await roleApi.getEntityById({ id: id })
        this.form = data
        this.form.menuCheckStrictly = this.form.menuCheckStrictly === '10'
        this.form.deptCheckStrictly = this.form.deptCheckStrictly === '10'
      },
      /** 查询部门树结构 */
      getDeptTreeselect() {
        deptApi.getTree().then((response) => {
          this.treeList = response.data
        })
      },
      /** 查询角色部门树结构 */
      getRoleDeptTreeselect(id) {
        roleApi.getRoleDeptTreeselect({ id: id }).then((response) => {
          if (this.$refs.dept) {
            this.$refs.dept.setCheckedKeys(response.data, true)
          }
        })
      },
      /** 分配数据权限操作 */
      handleDataScope(row) {
        const _this = this
        _this.title = '分配数据权限'
        _this.getEntityById(row.id)
        _this.$nextTick(() => {
          _this.getRoleDeptTreeselect(row.id)
        })
        _this.openDataScope = true
      },
      /** 提交按钮（数据权限） */
      submitDataScope: function () {
        if (this.form.id != undefined) {
          this.form.deptIds = this.getDeptAllCheckedKeys()
          let data = {
            roleId: this.form.id,
            dataScope: Number(this.form.dataScope),
            deptIds: this.form.deptIds,
          }
          roleApi.updateRoleDataScope(data).then((response) => {
            if (response.code === 200) {
              this.$baseMessage(response.msg, 'success', 'vab-hey-message-success')
              this.openDataScope = false
              this.getList()
            } else {
              this.$baseMessage(response.msg, 'error', 'vab-hey-message-success')
            }
          })
        }
      },
      // 所有部门节点数据
      getDeptAllCheckedKeys() {
        // 目前被选中的部门节点
        let checkedKeys = this.$refs.dept.getCheckedKeys()
        return checkedKeys
      },
      // 树权限（展开/折叠）
      handleCheckedTreeExpand(value, type) {
        if (type == 'menu') {
          let treeList = this.treeList
          for (let i = 0; i < treeList.length; i++) {
            this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
          }
        } else if (type == 'dept') {
          let treeList = this.treeList
          for (let i = 0; i < treeList.length; i++) {
            this.$refs.dept.store.nodesMap[treeList[i].deptId].expanded = value
          }
        }
      },
      // 树权限（全选/全不选）
      handleCheckedTreeNodeAll(value, type) {
        if (type == 'menu') {
          this.$refs.menu.setCheckedNodes(value ? this.treeList : [])
        } else if (type == 'dept') {
          this.$refs.dept.setCheckedNodes(value ? this.treeList : [])
        }
      },
      // 树权限（父子联动）
      handleCheckedTreeConnect(value, type) {
        if (type == 'menu') {
          this.form.menuCheckStrictly = value ? true : false
        } else if (type == 'dept') {
          this.form.deptCheckStrictly = value ? true : false
        }
      },
    },
  }
</script>

<style lang="scss" scoped>
  .vab-tree-border {
    height: 200px;
    padding: $base-padding;
    overflow-y: auto;
    border: 1px solid #dcdfe6;
    border-radius: $base-border-radius;
  }
</style>
