<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>
      <template #menu-right="{}">
        <el-button
            class="ml-3"
            @click="exportData('/api/v1/syn/user/info/export')"
        >
          <template #icon> <i-ep-download /> </template>导出
        </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: 'roleName',
            value: 'id',
            disabled: '',
          }"
            node-key="id"
            show-checkbox
            style="margin-top: 20px"
        >
          <template #default="{ data }">
            {{ data.roleName }}
          </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 {

  allRoleList,
  bindedUserRoleList,

  bindRoleUserList,

  treeList,
} from "@/api/user/index";

// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
    useCrud({
      src: "/api/v1/syn/user/info",
    });
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 router = useRouter(); //路由对象
const route = useRoute();

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: false, //是否显示编辑按钮
  delBtn: false, //是否显示删除按钮
  addBtn: false, //是否显示新增按钮
  viewBtn: false, //是否显示查看按钮
  menu: true, //是否显示操作列
  menuWidth: 150, //操作列宽度
  column: [
    {
      label: "用户名称",
      prop: "userName",
      rules: [
        {
          required: true,
          message: "请输入账号",
          trigger: "blur",
        },
      ],
      search: true,
    },
    {
      label: "账号编码",
      prop: "employeeCode",
      rules: [
        {
          required: true,
          message: "请输入账号编码",
          trigger: "blur",
        },
      ],
      search: true,
      editDisabled: true,
    },
    // {
    //   label: "昵称",
    //   prop: "nickName",
    //   rules: [
    //     {
    //       required: true,
    //       message: "请输入昵称",
    //       trigger: "blur",
    //     },
    //   ],
    //   search: true,
    // },
    {
      label: "账号装填",
      prop: "state",
      type: "select", //类型为单选框
      dicData: [
        {
          label: "启用",
          value: 0,
        },
        {
          label: "禁用",
          value: 1,
        },
        {
          label: "锁定",
          value: 2,
        },
      ],
      value: 0,
    },
    {
      label: "性别",
      prop: "sex",
      search: true,
      type: "select", //类型为单选框
      dicData: [
        {
          label: "未知",
          value: 0,
        },
        {
          label: "男",
          value: 1,
        },
        {
          label: "女",
          value: 2,
        },
      ],
      value: 0,
    },
    {
      label: "部门名称",
      prop: "deptIds",
      type: "tree",
      dicData: deptList, // 使用树形结构数据
      props: {
        label: "deptName", // 显示的字段
        value: "id", // 传递给后端的字段
        children: "children", // 子节点字段
      },
      checkStrictly: true,
      multiple: true, // 支持多选
      showCheckbox: true, // 显示复选框
      search: true,
      valueformat: "array", // 确保值是数组格式
    },
    {
      label: "邮箱",
      prop: "email",
      // rules: [
      //   {
      //     required: true,
      //     message: "请输入账号",
      //     trigger: "blur",
      //   },
      // ],
      search: false,
      addDisplay: false,
      editDisabled: true,
    },
  ],
});

// 编辑权限
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 allRoleList();
  menuList.value = allMenu.data ?? [];
  let selectMenu = await bindedUserRoleList(row.id);
  if (selectMenu.data && selectMenu.data.length > 0) {
    treeRef.value && treeRef.value.setCheckedKeys(selectMenu.data);
  }
};

const handleRoleMenuSubmit = async () => {
  loading.value = true;

  bindRoleUserList({
    userId: currentUserId.value,
    roleIds: 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);
};

const changePassword = (row) => {
  router.push({
    name: "changePassword",
    query: {
      redirect: route.fullPath,
      id: row.id,
    },
  });
};

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