GoodsManagement.tsx 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  1. import React, { useState, useCallback } from 'react';
  2. import { useQuery, useMutation } from '@tanstack/react-query';
  3. import { format } from 'date-fns';
  4. import { zhCN } from 'date-fns/locale';
  5. import { toast } from 'sonner';
  6. import { zodResolver } from '@hookform/resolvers/zod';
  7. import { useForm } from 'react-hook-form';
  8. import type { InferRequestType, InferResponseType } from 'hono/client';
  9. import { Button } from '@d8d/shared-ui-components/components/ui/button';
  10. import { Input } from '@d8d/shared-ui-components/components/ui/input';
  11. import { Badge } from '@d8d/shared-ui-components/components/ui/badge';
  12. import { RadioGroup, RadioGroupItem } from '@d8d/shared-ui-components/components/ui/radio-group';
  13. import { Label } from '@d8d/shared-ui-components/components/ui/label';
  14. import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@d8d/shared-ui-components/components/ui/card';
  15. import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@d8d/shared-ui-components/components/ui/table';
  16. import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@d8d/shared-ui-components/components/ui/dialog';
  17. import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components/components/ui/form';
  18. import { Textarea } from '@d8d/shared-ui-components/components/ui/textarea';
  19. import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@d8d/shared-ui-components/components/ui/select';
  20. import { goodsClient, goodsClientManager } from '../api/goodsClient';
  21. import { AdminCreateGoodsDto, AdminUpdateGoodsDto } from '@d8d/goods-module-mt/schemas';
  22. import { DataTablePagination } from '@d8d/shared-ui-components/components/admin/DataTablePagination';
  23. import { FileSelector } from '@d8d/file-management-ui-mt';
  24. import { GoodsCategoryCascadeSelector } from '@d8d/goods-category-management-ui-mt/components';
  25. import { SupplierSelector } from '@d8d/supplier-management-ui-mt/components';
  26. import { MerchantSelector } from '@d8d/merchant-management-ui-mt/components';
  27. import { GoodsParentChildPanel, type ParentChildData, type BatchSpecTemplate } from './GoodsParentChildPanel';
  28. import { Search, Plus, Edit, Trash2, Package } from 'lucide-react';
  29. type CreateRequest = InferRequestType<typeof goodsClient.index.$post>['json'];
  30. type UpdateRequest = InferRequestType<typeof goodsClient[':id']['$put']>['json'];
  31. type GoodsResponse = InferResponseType<typeof goodsClient.index.$get, 200>['data'][0];
  32. const createFormSchema = AdminCreateGoodsDto;
  33. const updateFormSchema = AdminUpdateGoodsDto;
  34. export const GoodsManagement: React.FC = () => {
  35. const [searchParams, setSearchParams] = useState({ page: 1, limit: 10, search: '', filter: 'parent' as 'parent' | 'all' });
  36. const [isModalOpen, setIsModalOpen] = useState(false);
  37. const [editingGoods, setEditingGoods] = useState<GoodsResponse | null>(null);
  38. const [isCreateForm, setIsCreateForm] = useState(true);
  39. const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  40. const [goodsToDelete, setGoodsToDelete] = useState<number | null>(null);
  41. const [parentChildData, setParentChildData] = useState({
  42. spuId: 0,
  43. spuName: null as string | null,
  44. childGoodsIds: [] as number[],
  45. batchSpecs: [] as BatchSpecTemplate[]
  46. });
  47. const [isVisible, setIsVisible] = useState(false);
  48. // 创建表单
  49. const createForm = useForm<CreateRequest>({
  50. resolver: zodResolver(createFormSchema),
  51. defaultValues: {
  52. name: '',
  53. price: 0,
  54. costPrice: 0,
  55. categoryId1: 0,
  56. categoryId2: 0,
  57. categoryId3: 0,
  58. goodsType: 1,
  59. supplierId: null,
  60. merchantId: null,
  61. imageFileId: null,
  62. slideImageIds: [],
  63. detail: '',
  64. instructions: '',
  65. sort: 0,
  66. state: 1,
  67. stock: 0,
  68. lowestBuy: 1,
  69. },
  70. });
  71. // 更新表单
  72. const updateForm = useForm<UpdateRequest>({
  73. resolver: zodResolver(updateFormSchema),
  74. });
  75. // 获取商品列表
  76. const { data, isLoading, refetch } = useQuery({
  77. queryKey: ['goods', searchParams],
  78. queryFn: async () => {
  79. const res = await goodsClientManager.get().index.$get({
  80. query: {
  81. page: searchParams.page,
  82. pageSize: searchParams.limit,
  83. keyword: searchParams.search,
  84. ...(searchParams.filter === 'parent' && { filters: '{"spuId": 0}' })
  85. }
  86. });
  87. if (res.status !== 200) throw new Error('获取商品列表失败');
  88. return await res.json();
  89. }
  90. });
  91. // 创建商品
  92. const createMutation = useMutation({
  93. mutationFn: async (data: CreateRequest) => {
  94. const res = await goodsClientManager.get().index.$post({ json: data });
  95. if (res.status !== 201) throw new Error('创建商品失败');
  96. return await res.json();
  97. },
  98. onSuccess: () => {
  99. toast.success('商品创建成功');
  100. setIsModalOpen(false);
  101. createForm.reset();
  102. refetch();
  103. },
  104. onError: (error) => {
  105. toast.error(error.message || '创建商品失败');
  106. }
  107. });
  108. // 更新商品
  109. const updateMutation = useMutation({
  110. mutationFn: async ({ id, data }: { id: number; data: UpdateRequest }) => {
  111. const res = await goodsClientManager.get()[':id']['$put']({
  112. param: { id: id },
  113. json: data
  114. });
  115. if (res.status !== 200) throw new Error('更新商品失败');
  116. return await res.json();
  117. },
  118. onSuccess: () => {
  119. toast.success('商品更新成功');
  120. setIsModalOpen(false);
  121. setEditingGoods(null);
  122. refetch();
  123. },
  124. onError: (error) => {
  125. toast.error(error.message || '更新商品失败');
  126. }
  127. });
  128. // 删除商品
  129. const deleteMutation = useMutation({
  130. mutationFn: async (id: number) => {
  131. const res = await goodsClientManager.get()[':id']['$delete']({
  132. param: { id: id }
  133. });
  134. if (res.status !== 204) throw new Error('删除商品失败');
  135. return id;
  136. },
  137. onSuccess: () => {
  138. toast.success('商品删除成功');
  139. setDeleteDialogOpen(false);
  140. setGoodsToDelete(null);
  141. refetch();
  142. },
  143. onError: (error) => {
  144. toast.error(error.message || '删除商品失败');
  145. }
  146. });
  147. // 批量创建子商品
  148. const batchCreateChildrenMutation = useMutation({
  149. mutationFn: async ({ parentGoodsId, specs }: { parentGoodsId: number; specs: Array<{ name: string; price: number; costPrice: number; stock: number; sort: number }> }) => {
  150. const res = await goodsClientManager.get().batchCreateChildren.$post({
  151. json: { parentGoodsId, specs }
  152. });
  153. if (res.status !== 200) throw new Error('批量创建子商品失败');
  154. return await res.json();
  155. },
  156. onSuccess: (data) => {
  157. toast.success(`成功创建 ${data.count} 个子商品`);
  158. refetch();
  159. },
  160. onError: (error) => {
  161. toast.error(error.message || '批量创建子商品失败');
  162. }
  163. });
  164. // 处理搜索
  165. const handleSearch = (e: React.FormEvent) => {
  166. e.preventDefault();
  167. setSearchParams(prev => ({ ...prev, page: 1 }));
  168. };
  169. // 处理创建
  170. const handleCreateGoods = () => {
  171. setIsCreateForm(true);
  172. setEditingGoods(null);
  173. createForm.reset();
  174. setIsModalOpen(true);
  175. };
  176. // 处理编辑
  177. const handleEditGoods = (goods: GoodsResponse) => {
  178. setIsCreateForm(false);
  179. setEditingGoods(goods);
  180. updateForm.reset({
  181. name: goods.name,
  182. price: goods.price,
  183. costPrice: goods.costPrice,
  184. categoryId1: goods.categoryId1,
  185. categoryId2: goods.categoryId2,
  186. categoryId3: goods.categoryId3,
  187. goodsType: goods.goodsType,
  188. supplierId: goods.supplierId,
  189. merchantId: goods.merchantId,
  190. imageFileId: goods.imageFileId,
  191. slideImageIds: goods.slideImages?.map(img => img.id) || [],
  192. detail: goods.detail || '',
  193. instructions: goods.instructions || '',
  194. sort: goods.sort,
  195. state: goods.state,
  196. stock: goods.stock,
  197. lowestBuy: goods.lowestBuy,
  198. });
  199. // 更新父子商品数据
  200. setParentChildData({
  201. spuId: goods.spuId,
  202. spuName: goods.parent?.name ?? null,
  203. childGoodsIds: goods.childGoodsIds || [],
  204. batchSpecs: []
  205. });
  206. setIsModalOpen(true);
  207. };
  208. // 处理删除
  209. const handleDeleteGoods = (id: number) => {
  210. setGoodsToDelete(id);
  211. setDeleteDialogOpen(true);
  212. };
  213. // 确认删除
  214. const confirmDelete = () => {
  215. if (goodsToDelete) {
  216. deleteMutation.mutate(goodsToDelete);
  217. }
  218. };
  219. // 提交表单
  220. const handleSubmit = (data: CreateRequest | UpdateRequest) => {
  221. // 合并表单数据和父子商品数据
  222. const submitData = {
  223. ...data,
  224. spuId: parentChildData.spuId,
  225. childGoodsIds: parentChildData.childGoodsIds,
  226. };
  227. if (isCreateForm) {
  228. createMutation.mutate(submitData as CreateRequest, {
  229. onSuccess: (result) => {
  230. // 如果创建成功且有批量创建模板,创建子商品
  231. if (parentChildData.batchSpecs.length > 0 && result.id) {
  232. batchCreateChildrenMutation.mutate({
  233. parentGoodsId: result.id,
  234. specs: parentChildData.batchSpecs
  235. });
  236. }
  237. }
  238. });
  239. } else if (editingGoods) {
  240. updateMutation.mutate({ id: editingGoods.id, data: submitData as UpdateRequest });
  241. }
  242. };
  243. // 处理父子商品数据变化,适配GoodsParentChildPanel的onDataChange类型
  244. const handleParentChildDataChange = useCallback((data: ParentChildData) => {
  245. setParentChildData({
  246. spuId: data.spuId,
  247. spuName: data.spuName ?? null,
  248. childGoodsIds: data.childGoodsIds,
  249. batchSpecs: data.batchSpecs || []
  250. });
  251. }, [setParentChildData]);
  252. return (
  253. <div className="space-y-4">
  254. <div className="flex justify-between items-center">
  255. <h1 className="text-2xl font-bold">商品管理</h1>
  256. <Button onClick={handleCreateGoods} data-testid="create-goods-button">
  257. <Plus className="mr-2 h-4 w-4" />
  258. 创建商品
  259. </Button>
  260. </div>
  261. <Card>
  262. <CardHeader>
  263. <CardTitle>商品列表</CardTitle>
  264. <CardDescription>管理您的商品信息</CardDescription>
  265. </CardHeader>
  266. <CardContent>
  267. <form onSubmit={handleSearch} className="mb-4">
  268. <div className="flex gap-2">
  269. <div className="relative flex-1 max-w-sm">
  270. <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
  271. <Input
  272. placeholder="搜索商品名称..."
  273. value={searchParams.search}
  274. onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
  275. className="pl-8"
  276. />
  277. </div>
  278. <Button type="submit" variant="outline">
  279. 搜索
  280. </Button>
  281. </div>
  282. <div className="mt-4">
  283. <RadioGroup
  284. value={searchParams.filter}
  285. onValueChange={(value) => setSearchParams(prev => ({ ...prev, filter: value as 'parent' | 'all', page: 1 }))}
  286. className="flex gap-4"
  287. >
  288. <div className="flex items-center space-x-2">
  289. <RadioGroupItem value="all" id="filter-all" />
  290. <Label htmlFor="filter-all">显示所有商品</Label>
  291. </div>
  292. <div className="flex items-center space-x-2">
  293. <RadioGroupItem value="parent" id="filter-parent" />
  294. <Label htmlFor="filter-parent">只显示父商品</Label>
  295. </div>
  296. </RadioGroup>
  297. </div>
  298. </form>
  299. <div className="rounded-md border">
  300. <Table>
  301. <TableHeader>
  302. <TableRow>
  303. <TableHead>商品图片</TableHead>
  304. <TableHead>商品名称</TableHead>
  305. <TableHead>价格</TableHead>
  306. <TableHead>库存</TableHead>
  307. <TableHead>销量</TableHead>
  308. <TableHead>供应商</TableHead>
  309. <TableHead>商户</TableHead>
  310. <TableHead>状态</TableHead>
  311. <TableHead>创建时间</TableHead>
  312. <TableHead className="text-right">操作</TableHead>
  313. </TableRow>
  314. </TableHeader>
  315. <TableBody>
  316. {data?.data.map((goods) => (
  317. <TableRow key={goods.id}>
  318. <TableCell>
  319. {goods.imageFile?.fullUrl ? (
  320. <img
  321. src={goods.imageFile.fullUrl}
  322. alt={goods.name}
  323. className="w-12 h-12 object-cover rounded"
  324. />
  325. ) : (
  326. <div className="w-12 h-12 bg-gray-200 rounded flex items-center justify-center">
  327. <Package className="h-6 w-6 text-gray-400" />
  328. </div>
  329. )}
  330. </TableCell>
  331. <TableCell className="font-medium">
  332. <div className="flex flex-col gap-1">
  333. <div>{goods.name}</div>
  334. <div className="flex items-center gap-2">
  335. {goods.spuId === 0 ? (
  336. goods.childGoodsIds?.length > 0 ? (
  337. <>
  338. <Badge variant="outline" className="text-xs">父商品</Badge>
  339. <span className="text-xs text-muted-foreground">
  340. 子商品: {goods.childGoodsIds.length}个
  341. </span>
  342. </>
  343. ) : (
  344. <Badge variant="outline" className="text-xs">单规格</Badge>
  345. )
  346. ) : (
  347. <>
  348. <Badge variant="secondary" className="text-xs">子商品</Badge>
  349. <span className="text-xs text-muted-foreground">
  350. 父商品: {goods.parent?.name || '未知'}
  351. </span>
  352. </>
  353. )}
  354. </div>
  355. </div>
  356. </TableCell>
  357. <TableCell>¥{goods.price.toFixed(2)}</TableCell>
  358. <TableCell>{goods.stock}</TableCell>
  359. <TableCell>{goods.salesNum}</TableCell>
  360. <TableCell>{goods.supplier?.name || '-'}</TableCell>
  361. <TableCell>{goods.merchant?.name || goods.merchant?.username || '-'}</TableCell>
  362. <TableCell>
  363. <Badge variant={goods.state === 1 ? 'default' : 'secondary'}>
  364. {goods.state === 1 ? '可用' : '不可用'}
  365. </Badge>
  366. </TableCell>
  367. <TableCell>
  368. {format(new Date(goods.createdAt), 'yyyy-MM-dd', { locale: zhCN })}
  369. </TableCell>
  370. <TableCell className="text-right">
  371. <div className="flex justify-end gap-2">
  372. <Button
  373. variant="ghost"
  374. size="icon"
  375. onClick={() => handleEditGoods(goods)}
  376. data-testid="edit-goods-button"
  377. >
  378. <Edit className="h-4 w-4" />
  379. </Button>
  380. <Button
  381. variant="ghost"
  382. size="icon"
  383. onClick={() => handleDeleteGoods(goods.id)}
  384. data-testid="delete-goods-button"
  385. >
  386. <Trash2 className="h-4 w-4" />
  387. </Button>
  388. </div>
  389. </TableCell>
  390. </TableRow>
  391. ))}
  392. </TableBody>
  393. </Table>
  394. {data?.data.length === 0 && !isLoading && (
  395. <div className="text-center py-8">
  396. <p className="text-muted-foreground">暂无商品数据</p>
  397. </div>
  398. )}
  399. </div>
  400. <DataTablePagination
  401. currentPage={searchParams.page}
  402. pageSize={searchParams.limit}
  403. totalCount={data?.pagination.total || 0}
  404. onPageChange={(page, limit) => setSearchParams(prev => ({ ...prev, page, limit }))}
  405. />
  406. </CardContent>
  407. </Card>
  408. {/* 创建/编辑对话框 */}
  409. <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
  410. <DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto" data-testid="create-edit-goods-dialog">
  411. <DialogHeader>
  412. <DialogTitle>{isCreateForm ? '创建商品' : '编辑商品'}</DialogTitle>
  413. <DialogDescription>
  414. {isCreateForm ? '创建一个新的商品' : '编辑商品信息'}
  415. </DialogDescription>
  416. </DialogHeader>
  417. {isCreateForm ? (
  418. <Form {...createForm}>
  419. <form id="create-goods-form" onSubmit={createForm.handleSubmit(handleSubmit)} className="space-y-4">
  420. <FormField
  421. control={createForm.control}
  422. name="name"
  423. render={({ field }) => (
  424. <FormItem>
  425. <FormLabel>商品名称 <span className="text-red-500">*</span></FormLabel>
  426. <FormControl>
  427. <Input
  428. placeholder="请输入商品名称"
  429. data-testid="goods-name-input"
  430. {...field}
  431. />
  432. </FormControl>
  433. <FormMessage />
  434. </FormItem>
  435. )}
  436. />
  437. <div className="grid grid-cols-2 gap-4">
  438. <FormField
  439. control={createForm.control}
  440. name="price"
  441. render={({ field }) => (
  442. <FormItem>
  443. <FormLabel>售卖价 <span className="text-red-500">*</span></FormLabel>
  444. <FormControl>
  445. <Input
  446. type="number"
  447. step="0.01"
  448. placeholder="0.00"
  449. data-testid="goods-price-input"
  450. {...field}
  451. />
  452. </FormControl>
  453. <FormMessage />
  454. </FormItem>
  455. )}
  456. />
  457. <FormField
  458. control={createForm.control}
  459. name="costPrice"
  460. render={({ field }) => (
  461. <FormItem>
  462. <FormLabel>成本价 <span className="text-red-500">*</span></FormLabel>
  463. <FormControl>
  464. <Input
  465. type="number"
  466. step="0.01"
  467. placeholder="0.00"
  468. data-testid="goods-cost-price-input"
  469. {...field}
  470. />
  471. </FormControl>
  472. <FormMessage />
  473. </FormItem>
  474. )}
  475. />
  476. </div>
  477. <GoodsCategoryCascadeSelector required={true} />
  478. <div className="grid grid-cols-2 gap-4">
  479. <FormField
  480. control={createForm.control}
  481. name="supplierId"
  482. render={({ field }) => (
  483. <FormItem>
  484. <FormLabel>供应商</FormLabel>
  485. <FormControl>
  486. <SupplierSelector
  487. value={field.value || undefined}
  488. onChange={field.onChange}
  489. />
  490. </FormControl>
  491. <FormMessage />
  492. </FormItem>
  493. )}
  494. />
  495. <FormField
  496. control={createForm.control}
  497. name="merchantId"
  498. render={({ field }) => (
  499. <FormItem>
  500. <FormLabel>商户</FormLabel>
  501. <FormControl>
  502. <MerchantSelector
  503. value={field.value || undefined}
  504. onChange={field.onChange}
  505. />
  506. </FormControl>
  507. <FormMessage />
  508. </FormItem>
  509. )}
  510. />
  511. </div>
  512. <div className="grid grid-cols-2 gap-4">
  513. <FormField
  514. control={createForm.control}
  515. name="goodsType"
  516. render={({ field }) => (
  517. <FormItem>
  518. <FormLabel>商品类型</FormLabel>
  519. <Select
  520. value={field.value?.toString()}
  521. onValueChange={(value) => field.onChange(parseInt(value))}
  522. >
  523. <FormControl>
  524. <SelectTrigger>
  525. <SelectValue placeholder="选择商品类型" />
  526. </SelectTrigger>
  527. </FormControl>
  528. <SelectContent>
  529. <SelectItem value="1">实物产品</SelectItem>
  530. <SelectItem value="2">虚拟产品</SelectItem>
  531. </SelectContent>
  532. </Select>
  533. <FormMessage />
  534. </FormItem>
  535. )}
  536. />
  537. <FormField
  538. control={createForm.control}
  539. name="stock"
  540. render={({ field }) => (
  541. <FormItem>
  542. <FormLabel>库存 <span className="text-red-500">*</span></FormLabel>
  543. <FormControl>
  544. <Input
  545. type="number"
  546. placeholder="0"
  547. data-testid="goods-stock-input"
  548. {...field}
  549. />
  550. </FormControl>
  551. <FormMessage />
  552. </FormItem>
  553. )}
  554. />
  555. </div>
  556. <FormField
  557. control={createForm.control}
  558. name="sort"
  559. render={({ field }) => (
  560. <FormItem>
  561. <FormLabel>排序</FormLabel>
  562. <FormControl>
  563. <Input type="number" {...field} />
  564. </FormControl>
  565. <FormMessage />
  566. </FormItem>
  567. )}
  568. />
  569. <FormField
  570. control={createForm.control}
  571. name="imageFileId"
  572. render={({ field }) => (
  573. <FormItem>
  574. <FormLabel>商品主图</FormLabel>
  575. <FormControl>
  576. <FileSelector
  577. value={field.value || undefined}
  578. onChange={field.onChange}
  579. maxSize={2}
  580. uploadPath="/goods"
  581. title="上传商品主图"
  582. previewSize="medium"
  583. placeholder="选择商品主图"
  584. filterType="image"
  585. />
  586. </FormControl>
  587. <FormDescription>推荐尺寸:800x800px</FormDescription>
  588. <FormMessage />
  589. </FormItem>
  590. )}
  591. />
  592. <FormField
  593. control={createForm.control}
  594. name="slideImageIds"
  595. render={({ field }) => (
  596. <FormItem>
  597. <FormLabel>商品轮播图</FormLabel>
  598. <FormControl>
  599. <FileSelector
  600. value={field.value || []}
  601. onChange={field.onChange}
  602. allowMultiple={true}
  603. maxSize={5}
  604. uploadPath="/goods/slide"
  605. title="上传轮播图"
  606. previewSize="small"
  607. placeholder="选择商品轮播图"
  608. filterType="image"
  609. />
  610. </FormControl>
  611. <FormDescription>最多上传5张轮播图,推荐尺寸:800x800px</FormDescription>
  612. <FormMessage />
  613. </FormItem>
  614. )}
  615. />
  616. <FormField
  617. control={createForm.control}
  618. name="instructions"
  619. render={({ field }) => (
  620. <FormItem>
  621. <FormLabel>商品简介</FormLabel>
  622. <FormControl>
  623. <Textarea
  624. placeholder="请输入商品简介"
  625. className="resize-none"
  626. {...field}
  627. />
  628. </FormControl>
  629. <FormMessage />
  630. </FormItem>
  631. )}
  632. />
  633. </form>
  634. </Form>
  635. ) : (
  636. <Form {...updateForm}>
  637. <form id="edit-goods-form" onSubmit={updateForm.handleSubmit(handleSubmit)} className="space-y-4">
  638. <FormField
  639. control={updateForm.control}
  640. name="name"
  641. render={({ field }) => (
  642. <FormItem>
  643. <FormLabel>商品名称 <span className="text-red-500">*</span></FormLabel>
  644. <FormControl>
  645. <Input placeholder="请输入商品名称" {...field} />
  646. </FormControl>
  647. <FormMessage />
  648. </FormItem>
  649. )}
  650. />
  651. <div className="grid grid-cols-2 gap-4">
  652. <FormField
  653. control={updateForm.control}
  654. name="price"
  655. render={({ field }) => (
  656. <FormItem>
  657. <FormLabel>售卖价</FormLabel>
  658. <FormControl>
  659. <Input type="number" step="0.01" {...field} />
  660. </FormControl>
  661. <FormMessage />
  662. </FormItem>
  663. )}
  664. />
  665. <FormField
  666. control={updateForm.control}
  667. name="costPrice"
  668. render={({ field }) => (
  669. <FormItem>
  670. <FormLabel>成本价</FormLabel>
  671. <FormControl>
  672. <Input type="number" step="0.01" {...field} />
  673. </FormControl>
  674. <FormMessage />
  675. </FormItem>
  676. )}
  677. />
  678. </div>
  679. <GoodsCategoryCascadeSelector />
  680. <div className="grid grid-cols-2 gap-4">
  681. <FormField
  682. control={updateForm.control}
  683. name="supplierId"
  684. render={({ field }) => (
  685. <FormItem>
  686. <FormLabel>供应商</FormLabel>
  687. <FormControl>
  688. <SupplierSelector
  689. value={field.value || undefined}
  690. onChange={field.onChange}
  691. />
  692. </FormControl>
  693. <FormMessage />
  694. </FormItem>
  695. )}
  696. />
  697. <FormField
  698. control={updateForm.control}
  699. name="merchantId"
  700. render={({ field }) => (
  701. <FormItem>
  702. <FormLabel>商户</FormLabel>
  703. <FormControl>
  704. <MerchantSelector
  705. value={field.value || undefined}
  706. onChange={field.onChange}
  707. />
  708. </FormControl>
  709. <FormMessage />
  710. </FormItem>
  711. )}
  712. />
  713. </div>
  714. <div className="grid grid-cols-2 gap-4">
  715. <FormField
  716. control={updateForm.control}
  717. name="stock"
  718. render={({ field }) => (
  719. <FormItem>
  720. <FormLabel>库存</FormLabel>
  721. <FormControl>
  722. <Input type="number" {...field} />
  723. </FormControl>
  724. <FormMessage />
  725. </FormItem>
  726. )}
  727. />
  728. <FormField
  729. control={updateForm.control}
  730. name="state"
  731. render={({ field }) => (
  732. <FormItem>
  733. <FormLabel>状态</FormLabel>
  734. <Select
  735. value={field.value?.toString()}
  736. onValueChange={(value) => field.onChange(parseInt(value))}
  737. >
  738. <FormControl>
  739. <SelectTrigger>
  740. <SelectValue />
  741. </SelectTrigger>
  742. </FormControl>
  743. <SelectContent>
  744. <SelectItem value="1">可用</SelectItem>
  745. <SelectItem value="2">不可用</SelectItem>
  746. </SelectContent>
  747. </Select>
  748. <FormMessage />
  749. </FormItem>
  750. )}
  751. />
  752. </div>
  753. <FormField
  754. control={updateForm.control}
  755. name="sort"
  756. render={({ field }) => (
  757. <FormItem>
  758. <FormLabel>排序</FormLabel>
  759. <FormControl>
  760. <Input type="number" {...field} />
  761. </FormControl>
  762. <FormMessage />
  763. </FormItem>
  764. )}
  765. />
  766. <FormField
  767. control={updateForm.control}
  768. name="imageFileId"
  769. render={({ field }) => (
  770. <FormItem>
  771. <FormLabel>商品主图</FormLabel>
  772. <FormControl>
  773. <FileSelector
  774. value={field.value || undefined}
  775. onChange={field.onChange}
  776. maxSize={2}
  777. uploadPath="/goods"
  778. title="上传商品主图"
  779. previewSize="medium"
  780. placeholder="选择商品主图"
  781. filterType="image"
  782. />
  783. </FormControl>
  784. <FormDescription>推荐尺寸:800x800px</FormDescription>
  785. <FormMessage />
  786. </FormItem>
  787. )}
  788. />
  789. <FormField
  790. control={updateForm.control}
  791. name="slideImageIds"
  792. render={({ field }) => (
  793. <FormItem>
  794. <FormLabel>商品轮播图</FormLabel>
  795. <FormControl>
  796. <FileSelector
  797. value={field.value || []}
  798. onChange={field.onChange}
  799. allowMultiple={true}
  800. maxSize={5}
  801. uploadPath="/goods/slide"
  802. title="上传轮播图"
  803. previewSize="small"
  804. placeholder="选择商品轮播图"
  805. filterType="image"
  806. />
  807. </FormControl>
  808. <FormDescription>最多上传5张轮播图,推荐尺寸:800x800px</FormDescription>
  809. <FormMessage />
  810. </FormItem>
  811. )}
  812. />
  813. <FormField
  814. control={updateForm.control}
  815. name="instructions"
  816. render={({ field }) => (
  817. <FormItem>
  818. <FormLabel>商品简介</FormLabel>
  819. <FormControl>
  820. <Textarea
  821. placeholder="请输入商品简介"
  822. className="resize-none"
  823. {...field}
  824. />
  825. </FormControl>
  826. <FormMessage />
  827. </FormItem>
  828. )}
  829. />
  830. </form>
  831. </Form>
  832. )}
  833. {/* 父子商品管理面板 - 移到表单下方 */}
  834. <div className="mt-6 pt-6 border-t">
  835. <GoodsParentChildPanel
  836. mode={isCreateForm ? 'create' : 'edit'}
  837. goodsId={isCreateForm ? undefined : editingGoods?.id}
  838. goodsName={isCreateForm ? createForm.watch('name') : editingGoods?.name}
  839. spuId={parentChildData.spuId}
  840. spuName={parentChildData.spuName ?? undefined}
  841. childGoodsIds={parentChildData.childGoodsIds}
  842. batchSpecs={isCreateForm ? parentChildData.batchSpecs : undefined}
  843. onDataChange={handleParentChildDataChange}
  844. onUpdate={refetch}
  845. disabled={isCreateForm ? createMutation.isPending : updateMutation.isPending}
  846. />
  847. </div>
  848. {/* 对话框底部按钮 */}
  849. <DialogFooter>
  850. <Button
  851. type="button"
  852. variant="outline"
  853. onClick={() => setIsModalOpen(false)}
  854. >
  855. 取消
  856. </Button>
  857. <Button
  858. type="submit"
  859. form={isCreateForm ? "create-goods-form" : "edit-goods-form"}
  860. disabled={isCreateForm ? createMutation.isPending : updateMutation.isPending}
  861. >
  862. {isCreateForm
  863. ? (createMutation.isPending ? '创建中...' : '创建')
  864. : (updateMutation.isPending ? '更新中...' : '更新')
  865. }
  866. </Button>
  867. </DialogFooter>
  868. </DialogContent>
  869. </Dialog>
  870. {/* 删除确认对话框 */}
  871. <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
  872. <DialogContent>
  873. <DialogHeader>
  874. <DialogTitle>确认删除</DialogTitle>
  875. <DialogDescription>
  876. 确定要删除这个商品吗?此操作无法撤销。
  877. </DialogDescription>
  878. </DialogHeader>
  879. <DialogFooter>
  880. <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
  881. 取消
  882. </Button>
  883. <Button
  884. variant="destructive"
  885. onClick={confirmDelete}
  886. disabled={deleteMutation.isPending}
  887. >
  888. {deleteMutation.isPending ? '删除中...' : '删除'}
  889. </Button>
  890. </DialogFooter>
  891. </DialogContent>
  892. </Dialog>
  893. </div>
  894. );
  895. };