<script setup lang="ts">
import { ref, reactive } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { postAddRole, postUpdateRole, postUpdateRoleName } from "@/api/roles";
const emit = defineEmits(["handleClick"]);
const dialogVisibleAdd = ref(false);
const dialogTitle = ref("新增");
const formRef = ref();
const form = reactive({
  roleName: "",
  roleCode: ""
});
const postAddRoleApi = async () => {
  const res =
    dialogTitle.value == "新增"
      ? await postAddRole(form)
      : await postUpdateRoleName(form);
  if (res.code === 200) {
    emit("handleClick");
    dialogVisibleAdd.value = false;

    ElMessage({
      message: `${dialogTitle.value}成功`,
      type: "success"
    });
  } else {
  }
};
const handleClose = () => {
  formRef.value.clearValidate(); // 清除验证错误
  formRef.value.resetFields(); // 重置表单字段
  dialogVisibleAdd.value = !dialogVisibleAdd.value;
  // ElMessageBox.confirm("确认关闭弹窗吗？")
  //   .then(() => {
  //     ElMessage({
  //       message: "已关闭",
  //       type: "success"
  //     });
  //   })
  //   .catch(() => {
  //     // catch error
  //   });
};
// 添加部门保存
const saveDepartment = () => {
  formRef.value.validate(valid => {
    if (valid) {
      postAddRoleApi();
    }
  });
};
const open = item => {
  console.log(item);
  if (item) {
    form.roleCode = item.roleCode;
    dialogTitle.value = "编辑";
    form.roleName = item.roleName;
  } else {
    dialogTitle.value = "新增";
    form.roleName = "";
  }
  dialogVisibleAdd.value = true;
  console.log(item);
};
defineExpose({
  open
});
</script>

<template>
  <div>
    <el-dialog
      v-model="dialogVisibleAdd"
      :title="dialogTitle + '角色'"
      width="500"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item
          prop="roleName"
          label="角色"
          :rules="[
            {
              required: true,
              message: '请填写角色名称',
              trigger: 'blur'
            }
          ]"
        >
          <el-input v-model="form.roleName" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="saveDepartment"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
