<template>
  <div class="mainContentBox">
    <avue-crud
      ref="crudRef"
      v-model="form"
      v-model:page="page"
      v-model:search="search"
      :data="data"
      :option="option"
      @search-change="searchChange"
      @search-reset="resetChange"
      @size-change="dataList"
      @current-change="dataList"
      @row-save="createRow"
      @row-update="updateRow"
    >
      <template #menu="{ row }">
        <el-button text type="primary" @click="editPermission(row)"
          >分配权限
        </el-button>
      </template>
    </avue-crud>

    <!-- 分配菜单弹窗  -->
    <el-dialog v-model="menuDialogVisible" title="权限分配" width="700px">
      <el-scrollbar v-loading="loading" max-height="600px">
        <el-button type="primary" @click="toggleCheckAll">全选</el-button>
        <el-button @click="resetChecked">清空</el-button>
        <el-tree
          ref="treeRef"
          :data="menuList"
          :default-expand-all="false"
          :props="{
            children: 'childs',
            label: 'menuName',
            value: 'id',
            disabled: '',
          }"
          node-key="id"
          show-checkbox
          style="margin-top: 20px"
        >
          <template #default="{ data }">
            {{ data.menuName }}
          </template>
        </el-tree>
      </el-scrollbar>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleRoleMenuSubmit"
            >确 定
          </el-button>
          <el-button @click="menuDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref } from "vue";
import { useCrud } from "@/hooks/userCrud";
import {
  addSystemUserMenu,
  bindedRoleMenuList,
  bindRoleMenuList,
  systemMenuList,
  systemUserMenuList,
  treeList,
} from "@/api/user/index";

// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/synRoleInfo",
  });
const { dataList, createRow, updateRow, deleteRow, searchChange, resetChange } =
  Methords; //增删改查
const { selectionChange, multipleDelete } = Methords; //选中和批量删除事件
const { checkBtnPerm, downloadTemplate, exportData } = Utils; //按钮权限等工具

const crudRef = ref(null); //crudRef.value 获取avue-crud对象

const deptList = ref([]); //部门列表
const getDeptList = async () => {
  let res = await treeList();
  if (res && res.code == 200) {
    deptList.value = res.data ?? []; //获取部门列表
  }
};

// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  editBtn: true, //是否显示编辑按钮
  delBtn: false, //是否显示删除按钮
  addBtn: true, //是否显示新增按钮
  viewBtn: false, //是否显示查看按钮
  menu: true, //是否显示操作列
  column: [
    {
      label: "角色编码",
      prop: "roleCode",
      rules: [
        {
          required: true,
          message: "请输入角色编码",
          trigger: "blur",
        },
      ],
      search: true,
    },
    {
      label: "角色名称",
      prop: "roleName",
      rules: [
        {
          required: true,
          message: "请输入角色名称",
          trigger: "blur",
        },
      ],
      search: true,
    },

    {
      label: "状态",
      prop: "state",
      type: "radio", //类型为单选框
      dicData: [
        {
          label: "启用",
          value: 0,
        },
        {
          label: "禁用",
          value: 1,
        },
      ],
      value: 0,
    },
  ],
});

// 编辑权限
const currentUserId = ref("");
const treeRef = ref(null);
const menuDialogVisible = ref(false);
const loading = ref(false);
const menuList = ref([]);
const editPermission = async (row) => {
  currentUserId.value = row.id;
  menuDialogVisible.value = true;
  // 清空已选菜单
  treeRef.value && treeRef.value.setCheckedKeys([]);
  let allMenu = await systemMenuList();
  menuList.value = allMenu.data ?? [];
  let selectMenu = await bindedRoleMenuList(row.id);
  if (selectMenu.data && selectMenu.data.length > 0) {
    treeRef.value && treeRef.value.setCheckedKeys(selectMenu.data);
  }
};

const handleRoleMenuSubmit = async () => {
  loading.value = true;
  bindRoleMenuList({
    roleId: currentUserId.value,
    menuIds: treeRef.value.getCheckedKeys(),
  })
    .then(() => {
      ElMessage.success("权限分配成功");
    })
    .finally(() => {
      loading.value = false;
      menuDialogVisible.value = false;
    });
};

const toggleCheckAll = () => {
  const allKeys = menuList.value.map((item) => item.id);
  treeRef.value.setCheckedKeys(allKeys);
};
const resetChecked = () => {
  treeRef.value.setCheckedKeys([], false);
};

onMounted(() => {
  getDeptList(); //获取部门列表
  dataList();
});
</script>
