<script setup lang="ts">
import { reactive, ref } from "vue";
import { addRole, modifyRole, getRoleDetail } from "@/api/role";
import { ElMessage } from "element-plus";

const emit = defineEmits(["refresh"]);
const formRef = ref();

const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const loading = ref(false);

const state = reactive({
  ruleForm: {
    id: null as number | null,
    roleName: "",
    roleDesc: "",
    permissions: ""
  },
  rules: {
    roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }]
  }
});

const resetForm = () => {
  state.ruleForm = {
    id: null,
    roleName: "",
    roleDesc: "",
    permissions: ""
  };
  formRef.value?.resetFields();
};

const getTitle = () => {
  return dialogType.value === "add" ? "新增角色" : "编辑角色";
};

const open = async (type: "add" | "edit", row?: any) => {
  dialogType.value = type;
  resetForm();
  if (type === "edit" && row) {
    loading.value = true;
    try {
      const res = await getRoleDetail(row.id);
      Object.assign(state.ruleForm, res || {});
    } catch {
      ElMessage.error("获取角色详情失败");
    } finally {
      loading.value = false;
    }
  }
  dialogVisible.value = true;
};

const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

const handleSubmit = async () => {
  const valid = await formRef.value?.validate().catch(() => false);
  if (!valid) return;

  loading.value = true;
  try {
    if (dialogType.value === "add") {
      await addRole(state.ruleForm);
    } else {
      await modifyRole(state.ruleForm);
    }
    ElMessage.success("操作成功");
    handleClose();
    emit("refresh");
  } catch {
    ElMessage.error("操作失败");
  } finally {
    loading.value = false;
  }
};

defineExpose({ open });
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="getTitle()"
    width="550px"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <el-form ref="formRef" :model="state.ruleForm" :rules="state.rules" label-width="100px" :disabled="loading">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="state.ruleForm.roleName" placeholder="请输入角色名称" clearable />
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input
          v-model="state.ruleForm.roleDesc"
          type="textarea"
          :rows="3"
          placeholder="请输入角色描述"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button :loading="loading" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>
