<template>
  <fs-page>
    <fs-crud ref="crudRef" v-bind="crudBinding" @add-success="onAddSuccess" @edit-success="onEditSuccess" @del-success="onDelSuccess" @add-error="onError" @edit-error="onError" @del-error="onError" />
  </fs-page>
</template>

<script setup lang="ts">
import { onMounted } from "vue";
import { useFs } from "@fast-crud/fast-crud";
import { ElMessage } from "element-plus";
import { createPermissionCrudOptions } from "./permission-crud";

const { crudBinding, crudRef, crudExpose } = useFs({
  createCrudOptions: createPermissionCrudOptions,
});

const onAddSuccess = () => {
  ElMessage.success({ message: "添加成功", duration: 5000 });
};

const onEditSuccess = () => {
  ElMessage.success({ message: "修改成功", duration: 5000 });
};

const onDelSuccess = () => {
  ElMessage.success({ message: "删除成功", duration: 5000 });
};

const onError = (error: any) => {
  let message = "操作失败";
  if (error.response?.data) {
    const data = error.response.data;
    if (data.message) {
      message = data.message;
    } else if (data.detail) {
      message = typeof data.detail === "string" ? data.detail : "操作失败";
    }
  }
  ElMessage.error({ message, duration: 5000 });
};

onMounted(() => {
  crudExpose.doRefresh();
});
</script>
