<template>
  <el-dialog v-model="visible" title="添加商品" width="500px">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入商品名称" />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input-number v-model="form.price" :min="0" :precision="2" :step="1" style="width: 100%" />
      </el-form-item>
      <el-form-item label="库存" prop="stock">
        <el-input-number v-model="form.stock" :min="0" :step="1" style="width: 100%" />
      </el-form-item>
      <el-form-item label="图片链接" prop="image">
        <el-input v-model="form.image" placeholder="请输入图片URL" />
      </el-form-item>
      <el-form-item label="是否上架" prop="isOnSale">
        <el-switch v-model="form.isOnSale" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['success'])

const visible = ref(false)
const formRef = ref()

const form = reactive({
  name: '',
  price: 0,
  stock: 0,
  image: '',
  isOnSale: true,
})

const rules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存', trigger: 'blur' }],
}

const open = () => {
  form.name = ''
  form.price = 0
  form.stock = 0
  form.image = `https://picsum.photos/100/100?random=${Math.floor(Math.random() * 100)}`
  form.isOnSale = true
  visible.value = true
}

const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      emit('success', { ...form })
      visible.value = false
      ElMessage.success('添加商品成功')
    }
  })
}

defineExpose({
  open,
})
</script>
