<template>
  <div class="app-container">
    <Filter
      v-model="filterData"
      :config="filterConfig"
      @handleAction="handleFilterData"
    />
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >添加</el-button
        >
      </el-col>
    </el-row>
    <!-- 表格 -->
    <Table :xbTable="xbTable" @tablePageChange="handleTablePageChange">
      <template v-slot:status="scope">
        <el-switch
          v-model="scope.row.status"
          active-value="0"
          inactive-value="1"
          @change="handleStatusChange(scope.row)"
        />
      </template>
      <template v-slot:operation="scope">
        <el-button
          link
          type="primary"
          icon="Edit"
          @click="handleUpdate(scope.row)"
          >编辑</el-button
        >
        <el-button
          link
          type="primary"
          icon="Edit"
          @click="handleAuthority(scope.row)"
          >权限管理</el-button
        >
        <el-button
          link
          type="danger"
          icon="Delete"
          @click="handleDelete(scope.row)"
          >删除</el-button
        >
      </template>
    </Table>
    <!-- 编辑新增角色信息 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="600px"
      append-to-body
      :before-close="cancel"
    >
      <el-form ref="diaRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item v-if="useUserStore().showAllTenant" label="学校名称">
          <SchoolSelect v-model="form.tenantId" />
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="form.roleName"
            placeholder="请输入"
            clearable
            maxlength="50"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            active-value="0"
            inactive-value="1"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入"
            clearable
            maxlength="200"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 权限管理 -->
    <el-dialog
      title="权限管理"
      v-model="openAuth"
      width="600px"
      append-to-body
      :before-close="cancelAuthDia"
    >
      <!--    :default-checked-keys="authForm.menuIds" -->
      <el-tree
        class="tree-border"
        :data="menuOptions"
        show-checkbox
        ref="menuRef"
        node-key="id"
        empty-text="加载中，请稍候"
        :props="{ label: 'label', children: 'children' }"
      ></el-tree>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAuthDia">确 定</el-button>
          <el-button @click="cancelAuthDia">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="roleManage">
import Filter from "@/views/smartCampus/components/Filter/index.vue";
import Table from "@/views/smartCampus/components/Table/index.vue";
import useUserStore from "@/store/modules/user";
import {
  getRoleListApi,
  updateRoleStatusApi,
  addRoleApi,
  updateRoleApi,
  getRoleDetailsApi,
  deleteRoleApi,
  getRoleAuth,
  updateRoleAuth,
} from "@/api/smartCampus/index";
const { proxy } = getCurrentInstance();
const selectConfig = ref({
  statusOption: [
    { label: "正常", value: "0" },
    { label: "停用", value: "1" },
  ],
});
const filterData = ref({}); //过滤
const filterConfig = computed(() => {
  return [
    {
      comName: "admin",
      label: "学校名称",
      prop: "tenantId",
      placeholder: "请选择",
      clearable: true,
    },
    {
      comName: "el-input",
      label: "角色",
      placeholder: "请输入",
      prop: "roleName",
      clearable: true,
    },
    {
      comName: "el-select",
      label: "状态",
      prop: "status",
      clearable: true,
      options: selectConfig.value.statusOption,
      selectConfig: {
        label: "label",
        value: "value",
      },
    },
  ];
});
const title = ref(""); //弹窗标题
const open = ref(false); //弹窗开关
const menuRef = ref(null); //权限
const openAuth = ref(false); //权限弹窗
const menuOptions = ref([]); //权限菜单
const authForm = ref({ roleId: "", menuIds: [], menuCheckStrictly: false }); //权限管理
// 弹窗数据
const data = reactive({
  form: {},
  rules: {
    tenantId: [
      { required: true, message: "学校名称不能为空", trigger: "change" },
    ],
    roleName: [
      { required: true, message: "角色名称不能为空", trigger: "blur" },
    ],
    status: [{ required: true, message: "状态不能为空", trigger: "change" }],
    remark: [{ required: true, message: "角色描述不能为空", trigger: "blur" }],
  },
});
const { form, rules } = toRefs(data);
const multiple = ref(true); //批量删除
const ids = ref([]); //批量删除的id
const xbTable = ref({
  loading: false,
  columns: [
    { prop: "roleName", label: "角色名称" },
    { prop: "status", label: "状态", slot: "status" },
    { prop: "remark", label: "角色描述" },
    { label: "操作", slot: "operation" },
  ],
  tableData: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
  },
});
/** 查询列表 */
function getList() {
  xbTable.value.loading = true;
  getRoleListApi({ ...xbTable.value.pagination, ...filterData.value }).then(
    (res) => {
      xbTable.value.tableData = res.rows.filter((item) => !item.admin);
      xbTable.value.loading = false;
      xbTable.value.pagination.total = res.total;
    }
  );
}

// 过滤按钮
function handleFilterData(type) {
  switch (type.value) {
    case "search":
      getList();
      break;
    case "reset":
      xbTable.value.pagination.pageNum = 1;
      getList();
      break;
  }
}
/** 用户状态修改  */
function handleStatusChange(row) {
  if (!row.roleId) return;
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.roleName + '"角色吗?')
    .then(() => {
      return updateRoleStatusApi(row);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      row.status = row.status === "0" ? "1" : "0";
    });
}

/** 表单重置 */
function reset() {
  form.value = {
    roleName: undefined,
    status: "0",
    remark: undefined,
  };
  proxy.resetForm("diaRef");
}
// 添加按钮
function handleAdd() {
  reset();
  title.value = "角色管理/添加";
  open.value = true;
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

// 表格分页
function handleTablePageChange(val) {
  xbTable.value.pagination.pageSize = val.limit;
  xbTable.value.pagination.pageNum = val.page;
  getList();
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  title.value = "角色管理/编辑";
  getRoleDetailsApi(row.roleId).then((res) => {
    if (res.code === 200) {
      form.value = res.data;
      open.value = true;
    }
  });
}

/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
  // 目前被选中的菜单节点
  let checkedKeys = menuRef.value.getCheckedKeys();
  // 半选中的菜单节点
  let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}
// 权限管理
function handleAuthority(row) {
  authForm.value.roleId = row.roleId;
  getRoleAuth(row.roleId).then((res) => {
    if (res.code === 200) {
      menuOptions.value = res.data.menus;
      openAuth.value = true;
      let checkedKeys = res.data.checkedKeys;
      checkedKeys.forEach((v) => {
        nextTick(() => {
          menuRef.value.setChecked(v, true, false);
        });
      });
    }
  });
}
// 重置权限管理
function resetAuth() {
  authForm.value = {
    roleId: "",
    menuIds: [],
    menuCheckStrictly: false,
  };
}
// 权限管理关闭
function cancelAuthDia() {
  openAuth.value = false;
  resetAuth();
}
// 修改权限管理
function submitAuthDia() {
  authForm.value.menuIds = getMenuAllCheckedKeys();
  updateRoleAuth(authForm.value).then((res) => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess("权限设置成功");
      openAuth.value = false;
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const deleteId = row.roleId;
  proxy.$modal
    .confirm("是否确认删除？")
    .then(() => {
      xbTable.value.loading = true;
      return deleteRoleApi(deleteId);
    })
    .then(() => {
      xbTable.value.loading = false;
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .finally(() => {
      xbTable.value.loading = false;
    });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["diaRef"].validate((valid) => {
    if (valid) {
      if (form.value.roleId != undefined) {
        updateRoleApi(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRoleApi(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
// 超管
function handleAdminRole() {
  if (useUserStore().showAllTenant) {
    xbTable.value.columns.unshift({
      prop: "tenantName",
      label: "学校名称",
    });
  }
}
handleAdminRole();
getList();
</script>
<style lang="scss" scoped></style>
