<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close">
    <el-form ref="form" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="form.roleName" />
      </el-form-item>
      <el-form-item label="权限字符" prop="roleKey">
        <el-input v-model="form.roleKey" />
      </el-form-item>
      <el-form-item label="角色顺序" prop="sort">
        <el-input-number
          v-model="form.sort"
          controls-position="right"
          :min="0" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio label="10">正常</el-radio>
          <el-radio label="20">停用</el-radio>
          <!--          <el-radio-->
          <!--            v-for="dict in dict.type.sys_normal_disable"-->
          <!--            :key="dict.value"-->
          <!--            :label="dict.value"-->
          <!--          >{{dict.label}}</el-radio>-->
        </el-radio-group>
      </el-form-item>
      <el-form-item label="菜单权限">
        <el-checkbox
          v-model="menuExpand"
          @change="handleCheckedTreeExpand($event, 'menu')">
          展开/折叠
        </el-checkbox>
        <el-checkbox
          v-model="menuNodeAll"
          @change="handleCheckedTreeNodeAll($event, 'menu')">
          全选/全不选
        </el-checkbox>
        <el-checkbox
          v-model="form.menuCheckStrictly"
          @change="handleCheckedTreeConnect($event, 'menu')">
          父子联动
        </el-checkbox>
        <div class="vab-tree-border">
          <el-tree
            ref="menu"
            :check-strictly="!form.menuCheckStrictly"
            :data="treeList"
            node-key="id"
            show-checkbox>
            <template #default="{ data }">
              <span>{{ data.meta.title }}</span>
            </template>
          </el-tree>
        </div>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          placeholder="请输入内容"
          type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import roleApi from '@/api/system/role'
  import menuApi from '@/api/system/menu'

  export default {
    name: 'RoleEdit',
    data() {
      return {
        form: {
          sort: 0,
          status: '10',
        },
        rules: {
          roleName: [
            { required: true, trigger: 'blur', message: '请输入角色名称' },
          ],
          roleKey: [
            { required: true, trigger: 'blur', message: '请输入权限字符' },
          ],
          status: [{ required: true, trigger: 'blur', message: '请输入状态' }],
        },
        title: '',
        dialogFormVisible: false,
        treeList: [],
        menuExpand: false,
        menuNodeAll: false,
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      showEdit(row) {
        if (!row) {
          this.title = '添加'
        } else {
          this.title = '编辑'
          this.getEntityById(row.id)
        }
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
      },
      async fetchData() {
        const { data: data } = await menuApi.getTree({ isAll: 'all' })
        this.treeList = data
      },
      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'
        this.$nextTick(() => {
          this.$refs.menu.setCheckedKeys(this.form.menuIds)
        })
      },
      save() {
        // 具体业务请自行调整
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            if (this.form.menuCheckStrictly) {
              this.form.menuCheckStrictly = '10'
            } else {
              this.form.menuCheckStrictly = '20'
            }
            if (this.form.deptCheckStrictly) {
              this.form.deptCheckStrictly = '10'
            } else {
              this.form.deptCheckStrictly = '20'
            }
            this.form.menuIds = this.getMenuAllCheckedKeys()
            if (this.form.id) {
              const { msg } = await roleApi.doEdit(this.form)
              this.$baseMessage(msg, 'success', 'vab-hey-message-success')
            } else {
              const { msg } = await roleApi.doAdd(this.form)
              this.$baseMessage(msg, 'success', 'vab-hey-message-success')
            }

            this.$emit('fetch-data')
            this.close()
          }
        })
      },
      // 所有菜单节点数据
      getMenuAllCheckedKeys() {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.menu.getHalfCheckedKeys()
        // 半选中的菜单节点
        let halfCheckedKeys = this.$refs.menu.getCheckedKeys()
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
        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>
