import { zodResolver } from "@hookform/resolvers/zod" import { useState } from "react" import { Controller, useForm } from "react-hook-form" import { toast } from "sonner" import z from "zod" import { updateCoupon } from "@/actions/coupon" import { Button } from "@/components/ui/button" import { Dialog, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog" import { FieldError, FieldGroup, FieldLabel } from "@/components/ui/field" import { Input } from "@/components/ui/input" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select" import type { Coupon } from "@/models/coupon" const schema = z.object({ code: z.string().min(1, "请输入优惠券名称"), amount: z.string().min(1, "请输入优惠券金额"), remark: z.string().optional(), min_amount: z.string().optional(), expire_at: z.string().optional(), status: z.string().optional(), }) export function UpdateCoupon(props: { coupon: Coupon onSuccess?: () => void }) { const [open, setOpen] = useState(false) const form = useForm({ resolver: zodResolver(schema), defaultValues: { code: props.coupon.code || "", remark: props.coupon.remark || "", amount: String(props.coupon.amount || 0), min_amount: String(props.coupon.min_amount || 0), expire_at: props.coupon.expire_at ? new Date(props.coupon.expire_at).toISOString().split("T")[0] : "", status: String(props.coupon.status || "0"), }, mode: "onChange", }) const { control, handleSubmit, reset } = form const onSubmit = async (data: z.infer) => { try { const payload = { id: props.coupon.id, code: data.code, amount: Number(data.amount), remark: data.remark, min_amount: Number(data.min_amount), expire_at: data.expire_at ? new Date(data.expire_at) : undefined, status: Number(data.status), } const resp = await updateCoupon(payload) if (resp.success) { toast.success("优惠券修改成功") props.onSuccess?.() setOpen(false) } else { toast.error(resp.message) } } catch (error) { const message = error instanceof Error ? error.message : error toast.error(`接口请求错误: ${message}`) } } const handleOpenChange = (value: boolean) => { if (value) { reset({ code: props.coupon.code || "", remark: props.coupon.remark || "", amount: String(props.coupon.amount || 0), min_amount: String(props.coupon.min_amount || 0), expire_at: props.coupon.expire_at ? new Date(props.coupon.expire_at).toISOString().split("T")[0] : "", status: String(props.coupon.status || "0"), }) } setOpen(value) } return ( 修改优惠券
(
名称:
{fieldState.error?.message}
)} /> (
备注:
{fieldState.error?.message}
)} /> (
金额:
{ const value = e.target.value if (value === "" || parseFloat(value) >= 0) { field.onChange(value) } }} /> {fieldState.error?.message}
)} /> (
最低消费:
{ const value = e.target.value if (value === "" || parseFloat(value) >= 0) { field.onChange(value) } }} /> {fieldState.error?.message}
)} /> (
过期时间:
{fieldState.error?.message}
)} /> (
状态:
{fieldState.error?.message}
)} />
) }