"use client" import { zodResolver } from "@hookform/resolvers/zod" import { useCallback, useEffect, useState } from "react" import { Controller, useForm } from "react-hook-form" import { toast } from "sonner" import { z } from "zod" import { getAllAdmin } from "@/actions/admin" import { createCust } from "@/actions/cust" import { getAllProductDiscount } from "@/actions/product_discount" import { Button } from "@/components/ui/button" import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog" import { Field, 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 { Admin } from "@/models/admin" import type { ProductDiscount } from "@/models/product_discount" // 表单验证规则 const addUserSchema = z .object({ username: z.string().optional(), password: z .string() .optional() .refine(val => !val || val.length >= 6, { message: "密码至少6位" }), confirmPassword: z.string().optional(), phone: z.string().regex(/^1[3-9]\d{9}$/, "请输入正确的手机号格式"), email: z .string() .email("请输入正确的邮箱格式") .optional() .or(z.literal("")), name: z.string().optional(), admin_id: z.string().optional(), discount_id: z.string().optional(), source: z.string().optional(), avatar: z.string().optional(), status: z.string().optional(), contact_qq: z.string().optional(), contact_wechat: z.string().optional(), }) .refine( data => { if (data.password) { return data.password === data.confirmPassword } return true }, { message: "两次输入的密码不一致", path: ["confirmPassword"], }, ) export type AddUserFormValues = z.infer interface AddUserDialogProps { onSuccess?: () => void } export function AddUserDialog({ onSuccess }: AddUserDialogProps) { const [open, setOpen] = useState(false) const [isAdding, setIsAdding] = useState(false) const [discountList, setDiscountList] = useState([]) const [isLoadingDiscount, setIsLoadingDiscount] = useState(false) const [adminList, setAdminList] = useState([]) const [isLoadingAdmin, setIsLoadingAdmin] = useState(false) const { control, handleSubmit, reset: resetAddForm, } = useForm({ resolver: zodResolver(addUserSchema), defaultValues: { username: "", password: "", confirmPassword: "", phone: "", email: "", name: "", admin_id: "", discount_id: "", avatar: "", status: "1", contact_qq: "", contact_wechat: "", }, }) const statusOptions = [ { value: "0", label: "禁用" }, { value: "1", label: "正常" }, ] const fetchDiscountList = useCallback(async () => { setIsLoadingDiscount(true) try { const res = await getAllProductDiscount() if (res.success) { setDiscountList(res.data || []) } else { toast.error(res.message || "获取折扣失败") } } catch (error) { const message = error instanceof Error ? error.message : error toast.error(`获取折扣失败: ${message}`) } finally { setIsLoadingDiscount(false) } }, []) const fetchAdminList = useCallback(async () => { setIsLoadingAdmin(true) try { const res = await getAllAdmin() if (res.success) { setAdminList(res.data || []) } else { toast.error(res.message || "获取管理员失败") } } catch (error) { const message = error instanceof Error ? error.message : error toast.error(`获取管理员失败: ${message}`) } finally { setIsLoadingAdmin(false) } }, []) useEffect(() => { if (open) { fetchDiscountList() fetchAdminList() } }, [open, fetchDiscountList, fetchAdminList]) const onSubmit = handleSubmit(async data => { const payload = { phone: data.phone, username: data?.username, password: data?.password, email: data?.email || "", name: data?.name, admin_id: data.admin_id ? Number(data.admin_id) : undefined, discount_id: data.discount_id ? Number(data.discount_id) : undefined, avatar: data?.avatar, status: data.status ? parseInt(data?.status) : 1, contact_qq: data?.contact_qq, contact_wechat: data?.contact_wechat, } setIsAdding(true) try { const result = await createCust(payload) if (result?.success) { toast.success("添加用户成功") setOpen(false) resetAddForm() onSuccess?.() } else { toast.error(result?.message || "添加失败") } } catch (error) { toast.error("添加失败,请稍后重试") console.error(error) } finally { setIsAdding(false) } }) const handleOpenChange = (open: boolean) => { if (!open) { resetAddForm() } setOpen(open) } return ( 添加用户
( 用户名 {fieldState.error?.message} )} /> ( 手机号 * {fieldState.error?.message} )} />
( 用户密码 (选填) {fieldState.error?.message} )} /> ( 确认密码 {fieldState.error?.message} )} />
( 邮箱 {fieldState.error?.message} )} /> ( 用户状态 {fieldState.error?.message} )} />
( QQ联系方式 {fieldState.error?.message} )} /> ( 微信/联系方式 {fieldState.error?.message} )} />
( 折扣 {fieldState.error?.message} )} /> ( 管理员 {fieldState.error?.message} )} />
) }