<template>
  <vab-dialog v-model="dialogFormVisible" append-to-body :title="title" width="500px" @close="close">
    <el-form ref="formRef" label-width="100px" :model="form">
      <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" @change="dataScopeSelectChange">
          <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)">展开/折叠</el-checkbox>
        <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
        <el-checkbox v-model="form.deptCheckStrictly" @change="handleCheckedTreeConnect($event)">父子联动</el-checkbox>
        <el-tree
          ref="deptRef"
          :check-strictly="!form.deptCheckStrictly"
          class="tree-border"
          :data="deptOptions"
          default-expand-all
          empty-text="加载中，请稍候"
          node-key="id"
          :props="{ label: 'label', children: 'children' }"
          show-checkbox
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="save">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </template>
  </vab-dialog>
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { dataScope, deptTreeSelect, getRole } from '/@/api/roleManagement'

defineOptions({
  name: 'RoleManagementAuth',
})

const { proxy } = getCurrentInstance() as any

const emit = defineEmits(['fetch-data'])

const menuRef = ref<any>(null)
const menuExpand = ref(false)
const menuNodeAll = ref(false)
const deptRef = ref<any>(null)
const deptExpand = ref(true)
const deptNodeAll = ref(false)
const deptOptions = ref<any>([])

/** 数据范围选项*/
const dataScopeOptions = ref([
  { value: '1', label: '全部数据权限' },
  { value: '2', label: '自定数据权限' },
  { value: '3', label: '本部门数据权限' },
  { value: '4', label: '本部门及以下数据权限' },
  { value: '5', label: '仅本人数据权限' },
])

const formRef = ref<FormInstance>()
const form = ref<any>({
  roleId: undefined,
  roleName: undefined,
  roleKey: undefined,
  roleSort: 0,
  status: '0',
  menuIds: [],
  deptIds: [],
  menuCheckStrictly: true,
  deptCheckStrictly: true,
  remark: undefined,
})

const title = ref<string>('')
const dialogFormVisible = ref<boolean>(false)

const showEdit = (row?: any) => {
  reset()
  title.value = '分配数据权限'
  const deptTreeSelect = getDeptTree(row.roleId)
  getRole(row.roleId).then((response) => {
    form.value = response.data
    dialogFormVisible.value = true
    nextTick(() => {
      deptTreeSelect.then((res: any) => {
        nextTick(() => {
          if (deptRef.value) {
            deptRef.value.setCheckedKeys(res.checkedKeys)
          }
        })
      })
    })
  })
}

/** 根据角色ID查询部门树结构 */
function getDeptTree(roleId: any) {
  return deptTreeSelect(roleId).then((response: any) => {
    deptOptions.value = response.depts
    return response
  })
}

/** 选择角色权限范围触发 */
function dataScopeSelectChange(value: any) {
  if (value !== '2') {
    deptRef.value.setCheckedKeys([])
  }
}

/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value: any) {
  let treeList = deptOptions.value
  for (const treeItem of treeList) {
    deptRef.value.store.nodesMap[treeItem.id].expanded = value
  }
}

/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value: any) {
  deptRef.value.setCheckedNodes(value ? deptOptions.value : [])
}

/** 树权限（父子联动） */
function handleCheckedTreeConnect(value: any) {
  form.value.deptCheckStrictly = value ? true : false
}

/** 所有部门节点数据 */
function getDeptAllCheckedKeys() {
  // 目前被选中的部门节点
  let checkedKeys = deptRef.value.getCheckedKeys()
  // 半选中的部门节点
  let halfCheckedKeys = deptRef.value.getHalfCheckedKeys()
  checkedKeys.unshift(...halfCheckedKeys)
  return checkedKeys
}

/** 重置新增的表单以及其他数据  */
function reset() {
  if (menuRef.value != undefined) {
    menuRef.value.setCheckedKeys([])
  }
  menuExpand.value = false
  menuNodeAll.value = false
  deptExpand.value = true
  deptNodeAll.value = false
  form.value = {
    roleId: undefined,
    roleName: undefined,
    roleKey: undefined,
    roleSort: 0,
    status: '0',
    menuIds: [],
    deptIds: [],
    menuCheckStrictly: true,
    deptCheckStrictly: true,
    remark: undefined,
  }
  proxy.resetForm('formRef')
}

const close = () => {
  formRef.value?.clearValidate()
  formRef.value?.resetFields()
  emit('fetch-data')
}

const cancel = () => {
  close()
  dialogFormVisible.value = false
}

const save = () => {
  formRef.value?.validate(async (valid: any) => {
    if (valid) {
      form.value.deptIds = getDeptAllCheckedKeys()
      dataScope(form.value)
      await $baseMessage('修改成功', 'success', 'hey')
      cancel()
    }
  })
}

onBeforeMount(() => {})

defineExpose({
  showEdit,
})
</script>

<style lang="scss" scoped>
.vab-tree-border {
  width: 100%;
  height: 250px;
  padding: var(--el-padding);
  overflow-y: auto;
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-base);
}
</style>
