| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963 |
- import React, { useState, useCallback } from 'react';
- import { useQuery, useMutation } from '@tanstack/react-query';
- import { format } from 'date-fns';
- import { zhCN } from 'date-fns/locale';
- import { toast } from 'sonner';
- import { zodResolver } from '@hookform/resolvers/zod';
- import { useForm } from 'react-hook-form';
- import type { InferRequestType, InferResponseType } from 'hono/client';
- import { Button } from '@d8d/shared-ui-components/components/ui/button';
- import { Input } from '@d8d/shared-ui-components/components/ui/input';
- import { Badge } from '@d8d/shared-ui-components/components/ui/badge';
- import { RadioGroup, RadioGroupItem } from '@d8d/shared-ui-components/components/ui/radio-group';
- import { Label } from '@d8d/shared-ui-components/components/ui/label';
- import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@d8d/shared-ui-components/components/ui/card';
- import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@d8d/shared-ui-components/components/ui/table';
- import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@d8d/shared-ui-components/components/ui/dialog';
- import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components/components/ui/form';
- import { Textarea } from '@d8d/shared-ui-components/components/ui/textarea';
- import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@d8d/shared-ui-components/components/ui/select';
- import { goodsClient, goodsClientManager } from '../api/goodsClient';
- import { AdminCreateGoodsDto, AdminUpdateGoodsDto } from '@d8d/goods-module-mt/schemas';
- import { DataTablePagination } from '@d8d/shared-ui-components/components/admin/DataTablePagination';
- import { FileSelector } from '@d8d/file-management-ui-mt';
- import { GoodsCategoryCascadeSelector } from '@d8d/goods-category-management-ui-mt/components';
- import { SupplierSelector } from '@d8d/supplier-management-ui-mt/components';
- import { MerchantSelector } from '@d8d/merchant-management-ui-mt/components';
- import { GoodsParentChildPanel, type ParentChildData, type BatchSpecTemplate } from './GoodsParentChildPanel';
- import { Search, Plus, Edit, Trash2, Package } from 'lucide-react';
- type CreateRequest = InferRequestType<typeof goodsClient.index.$post>['json'];
- type UpdateRequest = InferRequestType<typeof goodsClient[':id']['$put']>['json'];
- type GoodsResponse = InferResponseType<typeof goodsClient.index.$get, 200>['data'][0];
- const createFormSchema = AdminCreateGoodsDto;
- const updateFormSchema = AdminUpdateGoodsDto;
- export const GoodsManagement: React.FC = () => {
- const [searchParams, setSearchParams] = useState({ page: 1, limit: 10, search: '', filter: 'parent' as 'parent' | 'all' });
- const [isModalOpen, setIsModalOpen] = useState(false);
- const [editingGoods, setEditingGoods] = useState<GoodsResponse | null>(null);
- const [isCreateForm, setIsCreateForm] = useState(true);
- const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
- const [goodsToDelete, setGoodsToDelete] = useState<number | null>(null);
- const [parentChildData, setParentChildData] = useState({
- spuId: 0,
- spuName: null as string | null,
- childGoodsIds: [] as number[],
- batchSpecs: [] as BatchSpecTemplate[]
- });
- const [isVisible, setIsVisible] = useState(false);
- // 创建表单
- const createForm = useForm<CreateRequest>({
- resolver: zodResolver(createFormSchema),
- defaultValues: {
- name: '',
- price: 0,
- costPrice: 0,
- categoryId1: 0,
- categoryId2: 0,
- categoryId3: 0,
- goodsType: 1,
- supplierId: null,
- merchantId: null,
- imageFileId: null,
- slideImageIds: [],
- detail: '',
- instructions: '',
- sort: 0,
- state: 1,
- stock: 0,
- lowestBuy: 1,
- },
- });
- // 更新表单
- const updateForm = useForm<UpdateRequest>({
- resolver: zodResolver(updateFormSchema),
- });
- // 获取商品列表
- const { data, isLoading, refetch } = useQuery({
- queryKey: ['goods', searchParams],
- queryFn: async () => {
- const res = await goodsClientManager.get().index.$get({
- query: {
- page: searchParams.page,
- pageSize: searchParams.limit,
- keyword: searchParams.search,
- ...(searchParams.filter === 'parent' && { filters: '{"spuId": 0}' })
- }
- });
- if (res.status !== 200) throw new Error('获取商品列表失败');
- return await res.json();
- }
- });
- // 创建商品
- const createMutation = useMutation({
- mutationFn: async (data: CreateRequest) => {
- const res = await goodsClientManager.get().index.$post({ json: data });
- if (res.status !== 201) throw new Error('创建商品失败');
- return await res.json();
- },
- onSuccess: () => {
- toast.success('商品创建成功');
- setIsModalOpen(false);
- createForm.reset();
- refetch();
- },
- onError: (error) => {
- toast.error(error.message || '创建商品失败');
- }
- });
- // 更新商品
- const updateMutation = useMutation({
- mutationFn: async ({ id, data }: { id: number; data: UpdateRequest }) => {
- const res = await goodsClientManager.get()[':id']['$put']({
- param: { id: id },
- json: data
- });
- if (res.status !== 200) throw new Error('更新商品失败');
- return await res.json();
- },
- onSuccess: () => {
- toast.success('商品更新成功');
- setIsModalOpen(false);
- setEditingGoods(null);
- refetch();
- },
- onError: (error) => {
- toast.error(error.message || '更新商品失败');
- }
- });
- // 删除商品
- const deleteMutation = useMutation({
- mutationFn: async (id: number) => {
- const res = await goodsClientManager.get()[':id']['$delete']({
- param: { id: id }
- });
- if (res.status !== 204) throw new Error('删除商品失败');
- return id;
- },
- onSuccess: () => {
- toast.success('商品删除成功');
- setDeleteDialogOpen(false);
- setGoodsToDelete(null);
- refetch();
- },
- onError: (error) => {
- toast.error(error.message || '删除商品失败');
- }
- });
- // 批量创建子商品
- const batchCreateChildrenMutation = useMutation({
- mutationFn: async ({ parentGoodsId, specs }: { parentGoodsId: number; specs: Array<{ name: string; price: number; costPrice: number; stock: number; sort: number }> }) => {
- const res = await goodsClientManager.get().batchCreateChildren.$post({
- json: { parentGoodsId, specs }
- });
- if (res.status !== 200) throw new Error('批量创建子商品失败');
- return await res.json();
- },
- onSuccess: (data) => {
- toast.success(`成功创建 ${data.count} 个子商品`);
- refetch();
- },
- onError: (error) => {
- toast.error(error.message || '批量创建子商品失败');
- }
- });
- // 处理搜索
- const handleSearch = (e: React.FormEvent) => {
- e.preventDefault();
- setSearchParams(prev => ({ ...prev, page: 1 }));
- };
- // 处理创建
- const handleCreateGoods = () => {
- setIsCreateForm(true);
- setEditingGoods(null);
- createForm.reset();
- setIsModalOpen(true);
- };
- // 处理编辑
- const handleEditGoods = (goods: GoodsResponse) => {
- setIsCreateForm(false);
- setEditingGoods(goods);
- updateForm.reset({
- name: goods.name,
- price: goods.price,
- costPrice: goods.costPrice,
- categoryId1: goods.categoryId1,
- categoryId2: goods.categoryId2,
- categoryId3: goods.categoryId3,
- goodsType: goods.goodsType,
- supplierId: goods.supplierId,
- merchantId: goods.merchantId,
- imageFileId: goods.imageFileId,
- slideImageIds: goods.slideImages?.map(img => img.id) || [],
- detail: goods.detail || '',
- instructions: goods.instructions || '',
- sort: goods.sort,
- state: goods.state,
- stock: goods.stock,
- lowestBuy: goods.lowestBuy,
- });
- // 更新父子商品数据
- setParentChildData({
- spuId: goods.spuId,
- spuName: goods.parent?.name ?? null,
- childGoodsIds: goods.childGoodsIds || [],
- batchSpecs: []
- });
- setIsModalOpen(true);
- };
- // 处理删除
- const handleDeleteGoods = (id: number) => {
- setGoodsToDelete(id);
- setDeleteDialogOpen(true);
- };
- // 确认删除
- const confirmDelete = () => {
- if (goodsToDelete) {
- deleteMutation.mutate(goodsToDelete);
- }
- };
- // 提交表单
- const handleSubmit = (data: CreateRequest | UpdateRequest) => {
- // 合并表单数据和父子商品数据
- const submitData = {
- ...data,
- spuId: parentChildData.spuId,
- childGoodsIds: parentChildData.childGoodsIds,
- };
- if (isCreateForm) {
- createMutation.mutate(submitData as CreateRequest, {
- onSuccess: (result) => {
- // 如果创建成功且有批量创建模板,创建子商品
- if (parentChildData.batchSpecs.length > 0 && result.id) {
- batchCreateChildrenMutation.mutate({
- parentGoodsId: result.id,
- specs: parentChildData.batchSpecs
- });
- }
- }
- });
- } else if (editingGoods) {
- updateMutation.mutate({ id: editingGoods.id, data: submitData as UpdateRequest });
- }
- };
- // 处理父子商品数据变化,适配GoodsParentChildPanel的onDataChange类型
- const handleParentChildDataChange = useCallback((data: ParentChildData) => {
- setParentChildData({
- spuId: data.spuId,
- spuName: data.spuName ?? null,
- childGoodsIds: data.childGoodsIds,
- batchSpecs: data.batchSpecs || []
- });
- }, [setParentChildData]);
- return (
- <div className="space-y-4">
- <div className="flex justify-between items-center">
- <h1 className="text-2xl font-bold">商品管理</h1>
- <Button onClick={handleCreateGoods} data-testid="create-goods-button">
- <Plus className="mr-2 h-4 w-4" />
- 创建商品
- </Button>
- </div>
- <Card>
- <CardHeader>
- <CardTitle>商品列表</CardTitle>
- <CardDescription>管理您的商品信息</CardDescription>
- </CardHeader>
- <CardContent>
- <form onSubmit={handleSearch} className="mb-4">
- <div className="flex gap-2">
- <div className="relative flex-1 max-w-sm">
- <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
- <Input
- placeholder="搜索商品名称..."
- value={searchParams.search}
- onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
- className="pl-8"
- />
- </div>
- <Button type="submit" variant="outline">
- 搜索
- </Button>
- </div>
- <div className="mt-4">
- <RadioGroup
- value={searchParams.filter}
- onValueChange={(value) => setSearchParams(prev => ({ ...prev, filter: value as 'parent' | 'all', page: 1 }))}
- className="flex gap-4"
- >
- <div className="flex items-center space-x-2">
- <RadioGroupItem value="all" id="filter-all" />
- <Label htmlFor="filter-all">显示所有商品</Label>
- </div>
- <div className="flex items-center space-x-2">
- <RadioGroupItem value="parent" id="filter-parent" />
- <Label htmlFor="filter-parent">只显示父商品</Label>
- </div>
- </RadioGroup>
- </div>
- </form>
- <div className="rounded-md border">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead>商品图片</TableHead>
- <TableHead>商品名称</TableHead>
- <TableHead>价格</TableHead>
- <TableHead>库存</TableHead>
- <TableHead>销量</TableHead>
- <TableHead>供应商</TableHead>
- <TableHead>商户</TableHead>
- <TableHead>状态</TableHead>
- <TableHead>创建时间</TableHead>
- <TableHead className="text-right">操作</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {data?.data.map((goods) => (
- <TableRow key={goods.id}>
- <TableCell>
- {goods.imageFile?.fullUrl ? (
- <img
- src={goods.imageFile.fullUrl}
- alt={goods.name}
- className="w-12 h-12 object-cover rounded"
- />
- ) : (
- <div className="w-12 h-12 bg-gray-200 rounded flex items-center justify-center">
- <Package className="h-6 w-6 text-gray-400" />
- </div>
- )}
- </TableCell>
- <TableCell className="font-medium">
- <div className="flex flex-col gap-1">
- <div>{goods.name}</div>
- <div className="flex items-center gap-2">
- {goods.spuId === 0 ? (
- goods.childGoodsIds?.length > 0 ? (
- <>
- <Badge variant="outline" className="text-xs">父商品</Badge>
- <span className="text-xs text-muted-foreground">
- 子商品: {goods.childGoodsIds.length}个
- </span>
- </>
- ) : (
- <Badge variant="outline" className="text-xs">单规格</Badge>
- )
- ) : (
- <>
- <Badge variant="secondary" className="text-xs">子商品</Badge>
- <span className="text-xs text-muted-foreground">
- 父商品: {goods.parent?.name || '未知'}
- </span>
- </>
- )}
- </div>
- </div>
- </TableCell>
- <TableCell>¥{goods.price.toFixed(2)}</TableCell>
- <TableCell>{goods.stock}</TableCell>
- <TableCell>{goods.salesNum}</TableCell>
- <TableCell>{goods.supplier?.name || '-'}</TableCell>
- <TableCell>{goods.merchant?.name || goods.merchant?.username || '-'}</TableCell>
- <TableCell>
- <Badge variant={goods.state === 1 ? 'default' : 'secondary'}>
- {goods.state === 1 ? '可用' : '不可用'}
- </Badge>
- </TableCell>
- <TableCell>
- {format(new Date(goods.createdAt), 'yyyy-MM-dd', { locale: zhCN })}
- </TableCell>
- <TableCell className="text-right">
- <div className="flex justify-end gap-2">
- <Button
- variant="ghost"
- size="icon"
- onClick={() => handleEditGoods(goods)}
- data-testid="edit-goods-button"
- >
- <Edit className="h-4 w-4" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- onClick={() => handleDeleteGoods(goods.id)}
- data-testid="delete-goods-button"
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- </div>
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- {data?.data.length === 0 && !isLoading && (
- <div className="text-center py-8">
- <p className="text-muted-foreground">暂无商品数据</p>
- </div>
- )}
- </div>
- <DataTablePagination
- currentPage={searchParams.page}
- pageSize={searchParams.limit}
- totalCount={data?.pagination.total || 0}
- onPageChange={(page, limit) => setSearchParams(prev => ({ ...prev, page, limit }))}
- />
- </CardContent>
- </Card>
- {/* 创建/编辑对话框 */}
- <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
- <DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto" data-testid="create-edit-goods-dialog">
- <DialogHeader>
- <DialogTitle>{isCreateForm ? '创建商品' : '编辑商品'}</DialogTitle>
- <DialogDescription>
- {isCreateForm ? '创建一个新的商品' : '编辑商品信息'}
- </DialogDescription>
- </DialogHeader>
- {isCreateForm ? (
- <Form {...createForm}>
- <form id="create-goods-form" onSubmit={createForm.handleSubmit(handleSubmit)} className="space-y-4">
- <FormField
- control={createForm.control}
- name="name"
- render={({ field }) => (
- <FormItem>
- <FormLabel>商品名称 <span className="text-red-500">*</span></FormLabel>
- <FormControl>
- <Input
- placeholder="请输入商品名称"
- data-testid="goods-name-input"
- {...field}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <div className="grid grid-cols-2 gap-4">
- <FormField
- control={createForm.control}
- name="price"
- render={({ field }) => (
- <FormItem>
- <FormLabel>售卖价 <span className="text-red-500">*</span></FormLabel>
- <FormControl>
- <Input
- type="number"
- step="0.01"
- placeholder="0.00"
- data-testid="goods-price-input"
- {...field}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="costPrice"
- render={({ field }) => (
- <FormItem>
- <FormLabel>成本价 <span className="text-red-500">*</span></FormLabel>
- <FormControl>
- <Input
- type="number"
- step="0.01"
- placeholder="0.00"
- data-testid="goods-cost-price-input"
- {...field}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- <GoodsCategoryCascadeSelector required={true} />
- <div className="grid grid-cols-2 gap-4">
- <FormField
- control={createForm.control}
- name="supplierId"
- render={({ field }) => (
- <FormItem>
- <FormLabel>供应商</FormLabel>
- <FormControl>
- <SupplierSelector
- value={field.value || undefined}
- onChange={field.onChange}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="merchantId"
- render={({ field }) => (
- <FormItem>
- <FormLabel>商户</FormLabel>
- <FormControl>
- <MerchantSelector
- value={field.value || undefined}
- onChange={field.onChange}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- <div className="grid grid-cols-2 gap-4">
- <FormField
- control={createForm.control}
- name="goodsType"
- render={({ field }) => (
- <FormItem>
- <FormLabel>商品类型</FormLabel>
- <Select
- value={field.value?.toString()}
- onValueChange={(value) => field.onChange(parseInt(value))}
- >
- <FormControl>
- <SelectTrigger>
- <SelectValue placeholder="选择商品类型" />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- <SelectItem value="1">实物产品</SelectItem>
- <SelectItem value="2">虚拟产品</SelectItem>
- </SelectContent>
- </Select>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="stock"
- render={({ field }) => (
- <FormItem>
- <FormLabel>库存 <span className="text-red-500">*</span></FormLabel>
- <FormControl>
- <Input
- type="number"
- placeholder="0"
- data-testid="goods-stock-input"
- {...field}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- <FormField
- control={createForm.control}
- name="sort"
- render={({ field }) => (
- <FormItem>
- <FormLabel>排序</FormLabel>
- <FormControl>
- <Input type="number" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="imageFileId"
- render={({ field }) => (
- <FormItem>
- <FormLabel>商品主图</FormLabel>
- <FormControl>
- <FileSelector
- value={field.value || undefined}
- onChange={field.onChange}
- maxSize={2}
- uploadPath="/goods"
- title="上传商品主图"
- previewSize="medium"
- placeholder="选择商品主图"
- filterType="image"
- />
- </FormControl>
- <FormDescription>推荐尺寸:800x800px</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="slideImageIds"
- render={({ field }) => (
- <FormItem>
- <FormLabel>商品轮播图</FormLabel>
- <FormControl>
- <FileSelector
- value={field.value || []}
- onChange={field.onChange}
- allowMultiple={true}
- maxSize={5}
- uploadPath="/goods/slide"
- title="上传轮播图"
- previewSize="small"
- placeholder="选择商品轮播图"
- filterType="image"
- />
- </FormControl>
- <FormDescription>最多上传5张轮播图,推荐尺寸:800x800px</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="instructions"
- render={({ field }) => (
- <FormItem>
- <FormLabel>商品简介</FormLabel>
- <FormControl>
- <Textarea
- placeholder="请输入商品简介"
- className="resize-none"
- {...field}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </form>
- </Form>
- ) : (
- <Form {...updateForm}>
- <form id="edit-goods-form" onSubmit={updateForm.handleSubmit(handleSubmit)} className="space-y-4">
- <FormField
- control={updateForm.control}
- name="name"
- render={({ field }) => (
- <FormItem>
- <FormLabel>商品名称 <span className="text-red-500">*</span></FormLabel>
- <FormControl>
- <Input placeholder="请输入商品名称" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <div className="grid grid-cols-2 gap-4">
- <FormField
- control={updateForm.control}
- name="price"
- render={({ field }) => (
- <FormItem>
- <FormLabel>售卖价</FormLabel>
- <FormControl>
- <Input type="number" step="0.01" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="costPrice"
- render={({ field }) => (
- <FormItem>
- <FormLabel>成本价</FormLabel>
- <FormControl>
- <Input type="number" step="0.01" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- <GoodsCategoryCascadeSelector />
- <div className="grid grid-cols-2 gap-4">
- <FormField
- control={updateForm.control}
- name="supplierId"
- render={({ field }) => (
- <FormItem>
- <FormLabel>供应商</FormLabel>
- <FormControl>
- <SupplierSelector
- value={field.value || undefined}
- onChange={field.onChange}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="merchantId"
- render={({ field }) => (
- <FormItem>
- <FormLabel>商户</FormLabel>
- <FormControl>
- <MerchantSelector
- value={field.value || undefined}
- onChange={field.onChange}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- <div className="grid grid-cols-2 gap-4">
- <FormField
- control={updateForm.control}
- name="stock"
- render={({ field }) => (
- <FormItem>
- <FormLabel>库存</FormLabel>
- <FormControl>
- <Input type="number" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="state"
- render={({ field }) => (
- <FormItem>
- <FormLabel>状态</FormLabel>
- <Select
- value={field.value?.toString()}
- onValueChange={(value) => field.onChange(parseInt(value))}
- >
- <FormControl>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- <SelectItem value="1">可用</SelectItem>
- <SelectItem value="2">不可用</SelectItem>
- </SelectContent>
- </Select>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- <FormField
- control={updateForm.control}
- name="sort"
- render={({ field }) => (
- <FormItem>
- <FormLabel>排序</FormLabel>
- <FormControl>
- <Input type="number" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="imageFileId"
- render={({ field }) => (
- <FormItem>
- <FormLabel>商品主图</FormLabel>
- <FormControl>
- <FileSelector
- value={field.value || undefined}
- onChange={field.onChange}
- maxSize={2}
- uploadPath="/goods"
- title="上传商品主图"
- previewSize="medium"
- placeholder="选择商品主图"
- filterType="image"
- />
- </FormControl>
- <FormDescription>推荐尺寸:800x800px</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="slideImageIds"
- render={({ field }) => (
- <FormItem>
- <FormLabel>商品轮播图</FormLabel>
- <FormControl>
- <FileSelector
- value={field.value || []}
- onChange={field.onChange}
- allowMultiple={true}
- maxSize={5}
- uploadPath="/goods/slide"
- title="上传轮播图"
- previewSize="small"
- placeholder="选择商品轮播图"
- filterType="image"
- />
- </FormControl>
- <FormDescription>最多上传5张轮播图,推荐尺寸:800x800px</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
-
- <FormField
- control={updateForm.control}
- name="instructions"
- render={({ field }) => (
- <FormItem>
- <FormLabel>商品简介</FormLabel>
- <FormControl>
- <Textarea
- placeholder="请输入商品简介"
- className="resize-none"
- {...field}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </form>
- </Form>
- )}
- {/* 父子商品管理面板 - 移到表单下方 */}
- <div className="mt-6 pt-6 border-t">
- <GoodsParentChildPanel
- mode={isCreateForm ? 'create' : 'edit'}
- goodsId={isCreateForm ? undefined : editingGoods?.id}
- goodsName={isCreateForm ? createForm.watch('name') : editingGoods?.name}
- spuId={parentChildData.spuId}
- spuName={parentChildData.spuName ?? undefined}
- childGoodsIds={parentChildData.childGoodsIds}
- batchSpecs={isCreateForm ? parentChildData.batchSpecs : undefined}
- onDataChange={handleParentChildDataChange}
- onUpdate={refetch}
- disabled={isCreateForm ? createMutation.isPending : updateMutation.isPending}
- />
- </div>
- {/* 对话框底部按钮 */}
- <DialogFooter>
- <Button
- type="button"
- variant="outline"
- onClick={() => setIsModalOpen(false)}
- >
- 取消
- </Button>
- <Button
- type="submit"
- form={isCreateForm ? "create-goods-form" : "edit-goods-form"}
- disabled={isCreateForm ? createMutation.isPending : updateMutation.isPending}
- >
- {isCreateForm
- ? (createMutation.isPending ? '创建中...' : '创建')
- : (updateMutation.isPending ? '更新中...' : '更新')
- }
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- {/* 删除确认对话框 */}
- <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>确认删除</DialogTitle>
- <DialogDescription>
- 确定要删除这个商品吗?此操作无法撤销。
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
- 取消
- </Button>
- <Button
- variant="destructive"
- onClick={confirmDelete}
- disabled={deleteMutation.isPending}
- >
- {deleteMutation.isPending ? '删除中...' : '删除'}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </div>
- );
- };
|