<template>
  <el-dialog
      v-model="props.visible"
      title="权限设置"
      width="500"
      :close-on-click-modal="false"
      modal-class="roleMenuDialog"
      :before-close="dialogClose"
  >
    <el-form
        class="ls-form"
        ref="formRef"
        label-width="60px"
    >
      <el-form-item label="权限" prop="menus">
        <div>
          <el-checkbox label="展开/折叠" @change="handleExpand"/>
          <el-checkbox label="全选/不全选" @change="handleSelectAll"/>
          <div>
            <el-tree
                ref="treeRef"
                :data="menuTree"
                :props="{
                    label: 'name',
                    children: 'children',
                  }"
                node-key="id"
                :default-expand-all="isExpand"
                show-checkbox
            />
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogClose">取消</el-button>
        <el-button :loading="subLoading" type="primary" @click="submit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import type {CheckboxValueType, ElTree, FormInstance} from "element-plus";
import {getRoleMenuList,roleMenuSave} from "@/api/system/role";
import {message,buildTree} from "@/utils/auth";
import {nextTick, onMounted, ref, shallowRef} from "vue";
import {useLockFn} from "@/utils/useLockFn";

const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false
  },
  roleId: {
    type: Number,
    required: true,
    default: 0
  }
});
const emit = defineEmits(["success", "update:visible"]);
const treeRef = shallowRef<InstanceType<typeof ElTree>>();
const formRef = shallowRef<FormInstance>();
const isExpand = ref(false);
const menuArray = ref<any[]>([]);
const menuTree = ref<any[]>([]);

// 获取所有选择的节点
const getDeptAllCheckedKeys = () => {
  const checkedKeys = treeRef.value?.getCheckedKeys();
  const halfCheckedKeys = treeRef.value?.getHalfCheckedKeys()!;
  checkedKeys?.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
};

const handleExpand = (check: CheckboxValueType) => {
  const treeList = menuTree.value;
  for (let i = 0; i < treeList.length; i++) {
    treeRef.value.store.nodesMap[treeList[i].id].expanded = check;
  }
};

const handleSelectAll = (check: CheckboxValueType) => {
  if (check) {
    treeRef.value?.setCheckedKeys(menuArray.value.map((item) => item.id));
  } else {
    treeRef.value?.setCheckedKeys([]);
  }
};

const handleSubmit = async () => {
    await formRef.value?.validate();
    const menuIds = getDeptAllCheckedKeys()!;
    await roleMenuSave({menuIds,roleId:props.roleId});
    message("操作成功");
    emit("update:visible", false);
    emit("success");
};

const { isLock:subLoading,lockFn: submit } = useLockFn(handleSubmit);

const dialogClose = () => {
  emit("update:visible", false);
};

const setFormData = async () => {
  const data = await getRoleMenuList(props.roleId);
  menuTree.value = buildTree(data);
  menuArray.value =data;
  nextTick(()=>{
    menuArray.value.map(item=>{
      if(item.checked){
        treeRef.value?.setChecked(item.id,true, false);
      }
    })
  })
};

onMounted(() => {
  setFormData();
});
</script>
<style lang="scss">
.roleMenuDialog .el-dialog__body {
  max-height:600px;
  overflow: auto
}
</style>
