<template>
  <el-dialog :title="form.id ? '编辑区域' : '添加区域'" v-model="dialogVisible" @close="reset">
    <el-form ref="refForm" :model="form" :rules="rules" label-width="120px" label-position="left">
      <el-form-item label="区域名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入区域名称"></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="form.sort" placeholder="请输入排序"></el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmitHandle">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import APi from "@/api/account/shopArea";

let dialogVisible = ref(false);
const form = reactive({
  name: "",
});
const rules = reactive({
  name: [
    {
      required: true,
      message: "请输入区域名称",
      trigger: "blur",
    },
  ],
  sort: [
    {
      required: true,
      message: "请输入排序",
      trigger: "blur",
    },
  ],
});

const emits = defineEmits(["success"]);
const refForm = ref(null);
function onSubmitHandle() {
  refForm.value.validate(async (valid) => {
    if (valid) {
      try {
        let res = !form.id ? await APi.add(form) : await APi.edit(form);
        emits("success", res);
        close();
        ElNotification({
          title: "成功",
          message: `${form.id ? "编辑" : "添加"}成功`,
          type: "success",
        });
      } catch (error) {
        console.log(error);
      }
    }
  });
}
function show(obj) {
  dialogVisible.value = true;
  if (obj && obj.id) {
    Object.assign(form, obj);
  }
}
function close() {
  dialogVisible.value = false;
}
function reset() {
  form.id = "";
  form.name = "";
  form.sort = "";
}
defineExpose({
  show,
  close,
});
</script>