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

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

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

const formRef = ref();
const formData = reactive({
  goodsName: "",
  price: 0,
  stock: 0,
  status: 1
});

const rules = reactive({
  goodsName: [{ required: true, message: "商品名称必填", trigger: "blur" }],
  price: [
    { required: true, message: "价格必填", trigger: "blur" },
    { type: 'number', min: 0, message: '价格不能小于0' }
  ],
  stock: [
    { required: true, message: "库存必填", trigger: "blur" },
    { type: 'number', min: 0, message: '库存不能小于0' }
  ]
});

const handleConfirm = async () => {
  try {
    await formRef.value.validate();
    await addGoodsApi(formData);
    ElMessage.success("商品添加成功");
    emit("refresh");
    closeDialog();
  } catch (error) {
    console.error("表单验证失败", error);
  }
};

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

<template>
  <el-dialog
    title="新增商品"
    :model-value="visible"
    width="600px"
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="80px"
      label-position="right"
    >
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="formData.goodsName"
          placeholder="请输入商品名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input-number
          v-model="formData.price"
          :min="0"
          :precision="2"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="库存" prop="stock">
        <el-input-number
          v-model="formData.stock"
          :min="0"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">上架</el-radio>
          <el-radio :label="2">下架</el-radio>
        </el-radio-group>
      </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>