<script setup lang="ts">
import { reactive, ref, watch } from "vue";
import { FormInstance, FormRules } from "element-plus";
import { updateCategoryApi, addCategoryApi } from "@/api/shop/category";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Confirm from "@iconify-icons/ep/check";
import { ElMessage } from "element-plus";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  row: {
    type: Object,
    default: null
  }
});

const emit = defineEmits(["update:visible", "refresh"]);

const isEdit = ref(false);
const formRef = ref<FormInstance>();
const formData = reactive({
  categoryId: 0,
  categoryName: "",
  sort: 0,
  description: ""
});

const rules = reactive<FormRules>({
  categoryName: [{
    required: true,
    message: "分类名称必填",
    trigger: "blur"
  }],
  sort: [{
    required: true,
    message: "排序值必填",
    trigger: "blur",
    type: "number"
  }]
});

// 初始化表单数据
const initForm = () => {
  if (props.row?.categoryId) {
    isEdit.value = true;
    Object.assign(formData, props.row);
  } else {
    isEdit.value = false;
    formData.categoryId = 0;
    formData.categoryName = "";
    formData.sort = 0;
    formData.description = "";
  }
};

// 提交处理
const handleConfirm = async () => {
  try {
    await formRef.value?.validate();

    if (isEdit.value) {
      await updateCategoryApi(formData.categoryId, formData);
    } else {
      await addCategoryApi(formData);
    }

    ElMessage.success(`${isEdit.value ? "修改" : "新增"}成功`);
    emit("refresh");
    closeDialog();
  } catch (error) {
    console.error("表单提交失败", error);
  }
};

const closeDialog = () => {
  formRef.value?.resetFields();
  emit("update:visible", false);
};

// 监听visible变化初始化表单
watch(
  () => props.visible,
  val => {
    if (val) initForm();
  }
);
</script>

<template>
  <el-dialog :title="isEdit ? '编辑分类' : '新增分类'" :model-value="visible" width="500px" @close="closeDialog">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px" label-position="right">
      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="formData.categoryName" placeholder="请输入分类名称" clearable />
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="formData.sort" :min="0" controls-position="right" class="!w-full" />
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入分类描述" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" :icon="useRenderIcon(Confirm)" @click="handleConfirm">
        确认
      </el-button>
    </template>
  </el-dialog>
</template>