Blame view

美国版/Food Labeling Management Platform/src/components/labels/MultipleOptionsView.tsx 27 KB
0e27ddc8   杨鑫   标签
1
  import React, { useEffect, useMemo, useRef, useState } from 'react';
884054fb   “wangming”   项目初始化
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
  } from "../ui/table";
  import { Input } from "../ui/input";
  import { Button } from "../ui/button";
  import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
  } from "../ui/select";
0e27ddc8   杨鑫   标签
19
20
21
22
23
24
25
26
27
28
29
  import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
  } from "../ui/dialog";
  import { Label } from "../ui/label";
  import { Switch } from "../ui/switch";
  import { Badge } from "../ui/badge";
3af4878d   杨鑫   产品 标签 关联
30
  import { Plus, Edit, MoreHorizontal, X, Trash2 } from "lucide-react";
0e27ddc8   杨鑫   标签
31
  import { toast } from "sonner";
143afd59   杨鑫   打印,标签
32
  import { skipCountForPage } from "../../lib/paginationQuery";
0e27ddc8   杨鑫   标签
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
  import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
  import {
    Pagination,
    PaginationContent,
    PaginationItem,
    PaginationLink,
    PaginationNext,
    PaginationPrevious,
  } from "../ui/pagination";
  import {
    getLabelMultipleOptions,
    getLabelMultipleOption,
    createLabelMultipleOption,
    updateLabelMultipleOption,
    deleteLabelMultipleOption,
  } from "../../services/labelMultipleOptionService";
  import type {
    LabelMultipleOptionDto,
    LabelMultipleOptionCreateInput,
    LabelMultipleOptionUpdateInput,
  } from "../../types/labelMultipleOption";
  
  function toDisplay(v: string | null | undefined): string {
    const s = (v ?? "").trim();
    return s ? s : "None";
  }
884054fb   “wangming”   项目初始化
59
60
  
  export function MultipleOptionsView() {
0e27ddc8   杨鑫   标签
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
    const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
    const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
    const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
    const [editingOption, setEditingOption] = useState<LabelMultipleOptionDto | null>(null);
    const [deletingOption, setDeletingOption] = useState<LabelMultipleOptionDto | null>(null);
    const [options, setOptions] = useState<LabelMultipleOptionDto[]>([]);
    const [loading, setLoading] = useState(false);
    const [total, setTotal] = useState(0);
    const [refreshSeq, setRefreshSeq] = useState(0);
    const [actionsOpenForId, setActionsOpenForId] = useState<string | null>(null);
  
    const [keyword, setKeyword] = useState("");
    const [stateFilter, setStateFilter] = useState<string>("all");
  
    const [pageIndex, setPageIndex] = useState(1);
    const [pageSize, setPageSize] = useState(10);
  
    const abortRef = useRef<AbortController | null>(null);
    const keywordTimerRef = useRef<number | null>(null);
    const [debouncedKeyword, setDebouncedKeyword] = useState("");
  
    useEffect(() => {
      if (keywordTimerRef.current) window.clearTimeout(keywordTimerRef.current);
      keywordTimerRef.current = window.setTimeout(() => setDebouncedKeyword(keyword.trim()), 300);
      return () => {
        if (keywordTimerRef.current) window.clearTimeout(keywordTimerRef.current);
      };
    }, [keyword]);
  
    const totalPages = Math.max(1, Math.ceil(total / pageSize));
  
    useEffect(() => {
      setPageIndex(1);
    }, [debouncedKeyword, stateFilter, pageSize]);
  
    useEffect(() => {
      const run = async () => {
        abortRef.current?.abort();
        const ac = new AbortController();
        abortRef.current = ac;
  
        setLoading(true);
        try {
143afd59   杨鑫   打印,标签
104
          const skipCount = skipCountForPage(pageIndex);
0e27ddc8   杨鑫   标签
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
          const res = await getLabelMultipleOptions(
            {
              skipCount,
              maxResultCount: pageSize,
              keyword: debouncedKeyword || undefined,
              state: stateFilter === "all" ? undefined : stateFilter === "true",
            },
            ac.signal,
          );
  
          setOptions(res.items ?? []);
          setTotal(res.totalCount ?? 0);
        } catch (e: any) {
          if (e?.name === "AbortError") return;
          toast.error("Failed to load multiple options.", {
            description: e?.message ? String(e.message) : "Please try again.",
          });
          setOptions([]);
          setTotal(0);
        } finally {
          setLoading(false);
        }
      };
  
      run();
      return () => abortRef.current?.abort();
    }, [debouncedKeyword, stateFilter, pageIndex, pageSize, refreshSeq]);
  
    const refreshList = () => setRefreshSeq((x) => x + 1);
  
    const openEdit = (opt: LabelMultipleOptionDto) => {
      setActionsOpenForId(null);
      setEditingOption(opt);
      setIsEditDialogOpen(true);
    };
  
    const openDelete = (opt: LabelMultipleOptionDto) => {
      setActionsOpenForId(null);
      setDeletingOption(opt);
      setIsDeleteDialogOpen(true);
    };
884054fb   “wangming”   项目初始化
146
147
  
    return (
0e27ddc8   杨鑫   标签
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
      <div className="h-full flex flex-col">
        <div className="pb-4">
          <div className="flex flex-col gap-4">
            <div className="flex flex-nowrap items-center gap-3">
              <Input
                placeholder="Search"
                value={keyword}
                onChange={(e) => setKeyword(e.target.value)}
                style={{ height: 40, boxSizing: 'border-box' }}
                className="bg-white border border-gray-300 rounded-md w-40 shrink-0 placeholder:text-gray-500"
              />
              <Select value={stateFilter} onValueChange={setStateFilter}>
                <SelectTrigger className="bg-white border border-gray-300 rounded-md w-[150px] shrink-0" style={{ height: 40, boxSizing: 'border-box' }}>
                  <SelectValue placeholder="State" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All States</SelectItem>
                  <SelectItem value="true">Active</SelectItem>
                  <SelectItem value="false">Inactive</SelectItem>
                </SelectContent>
              </Select>
              <div className="flex-1" />
              <Button
                className="bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-md h-10 px-6 shrink-0"
                onClick={() => setIsCreateDialogOpen(true)}
              >
                New Multiple Options <Plus className="ml-1 h-4 w-4" />
              </Button>
            </div>
          </div>
884054fb   “wangming”   项目初始化
178
179
        </div>
  
0e27ddc8   杨鑫   标签
180
181
182
183
184
185
186
187
188
189
190
191
        <div className="flex-1 overflow-auto pt-6">
          <div className="rounded-md border bg-white shadow-sm">
            <Table>
              <TableHeader>
                <TableRow className="bg-gray-50 hover:bg-gray-50">
                  <TableHead className="font-bold text-gray-900 w-[200px]">Multiple Option Name</TableHead>
                  <TableHead className="font-bold text-gray-900 w-[200px]">Option Code</TableHead>
                  <TableHead className="font-bold text-gray-900">Contents</TableHead>
                  <TableHead className="font-bold text-gray-900 w-[100px]">State</TableHead>
                  <TableHead className="font-bold text-gray-900 w-[100px]">Order</TableHead>
                  <TableHead className="font-bold text-gray-900 w-[180px]">Last Edited</TableHead>
                  <TableHead className="font-bold text-gray-900 text-center w-[100px]">Actions</TableHead>
884054fb   “wangming”   项目初始化
192
                </TableRow>
0e27ddc8   杨鑫   标签
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
                    <TableCell colSpan={7} className="text-center text-sm text-gray-500 py-10">
                      Loading...
                    </TableCell>
                  </TableRow>
                ) : options.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={7} className="text-center text-sm text-gray-500 py-10">
                      No results.
                    </TableCell>
                  </TableRow>
                ) : (
                  options.map((item) => (
                    <TableRow key={item.id} className="hover:bg-gray-50">
                      <TableCell className="font-medium">{toDisplay(item.optionName)}</TableCell>
                      <TableCell className="text-gray-600">{toDisplay(item.optionCode)}</TableCell>
                      <TableCell className="text-gray-600">
                        {item.optionValuesJson && item.optionValuesJson.length > 0
                          ? item.optionValuesJson.join("; ")
                          : "None"}
                      </TableCell>
                      <TableCell>
                        <Badge className={item.state ? "bg-green-600" : "bg-gray-400"}>
                          {item.state ? "Active" : "Inactive"}
                        </Badge>
                      </TableCell>
                      <TableCell className="font-numeric">{item.orderNum ?? "None"}</TableCell>
                      <TableCell className="text-gray-500 tabular-nums font-numeric">
                        {item.creationTime ? new Date(item.creationTime).toLocaleString() : "None"}
                      </TableCell>
                      <TableCell className="text-center">
                        <Popover
                          open={actionsOpenForId === item.id}
                          onOpenChange={(open) => setActionsOpenForId(open ? item.id : null)}
                        >
                          <PopoverTrigger asChild>
                            <Button
                              type="button"
                              variant="ghost"
                              size="icon"
                              className="h-8 w-8"
                              aria-label="Row actions"
                            >
                              <MoreHorizontal className="h-4 w-4 text-gray-500" />
                            </Button>
                          </PopoverTrigger>
                          <PopoverContent align="end" className="w-40 p-1">
                            <Button
                              type="button"
                              variant="ghost"
                              className="w-full justify-start gap-2 h-9 px-2 font-normal"
                              onClick={() => openEdit(item)}
                            >
                              <Edit className="w-4 h-4" />
                              Edit
                            </Button>
                            <Button
                              type="button"
                              variant="ghost"
3af4878d   杨鑫   产品 标签 关联
255
                              className="w-full justify-start gap-2 h-9 px-2 font-normal text-red-600 hover:text-red-700 hover:bg-red-50"
0e27ddc8   杨鑫   标签
256
257
                              onClick={() => openDelete(item)}
                            >
3af4878d   杨鑫   产品 标签 关联
258
                              <Trash2 className="w-4 h-4 shrink-0" />
0e27ddc8   杨鑫   标签
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
                              Delete
                            </Button>
                          </PopoverContent>
                        </Popover>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </div>
  
        <div className="pt-4">
          <div className="flex items-center justify-between text-sm text-gray-600">
            <div>
              Showing {total === 0 ? 0 : (pageIndex - 1) * pageSize + 1}-
              {Math.min(pageIndex * pageSize, total)} of {total}
            </div>
            <div className="flex items-center gap-3">
              <Select value={String(pageSize)} onValueChange={(v) => setPageSize(Number(v))}>
                <SelectTrigger className="w-[110px] h-9 rounded-md border border-gray-300 bg-white text-gray-900">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {[10, 20, 50].map((n) => (
                    <SelectItem key={n} value={String(n)}>
                      {n} / page
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Pagination className="mx-0 w-auto justify-end">
                <PaginationContent>
                  <PaginationItem>
                    <PaginationPrevious
                      href="#"
                      size="default"
                      onClick={(e) => {
                        e.preventDefault();
                        setPageIndex((p) => Math.max(1, p - 1));
                      }}
                      aria-disabled={pageIndex <= 1}
                      className={pageIndex <= 1 ? "pointer-events-none opacity-50" : ""}
                    />
                  </PaginationItem>
                  <PaginationItem>
                    <PaginationLink
                      href="#"
                      isActive
                      size="default"
                      onClick={(e) => e.preventDefault()}
                    >
                      Page {pageIndex} / {totalPages}
                    </PaginationLink>
                  </PaginationItem>
                  <PaginationItem>
                    <PaginationNext
                      href="#"
                      size="default"
                      onClick={(e) => {
                        e.preventDefault();
                        setPageIndex((p) => Math.min(totalPages, p + 1));
                      }}
                      aria-disabled={pageIndex >= totalPages}
                      className={pageIndex >= totalPages ? "pointer-events-none opacity-50" : ""}
                    />
                  </PaginationItem>
                </PaginationContent>
              </Pagination>
            </div>
          </div>
884054fb   “wangming”   项目初始化
331
        </div>
0e27ddc8   杨鑫   标签
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
  
        <CreateMultipleOptionDialog
          open={isCreateDialogOpen}
          onOpenChange={setIsCreateDialogOpen}
          onCreated={() => {
            setPageIndex(1);
            refreshList();
          }}
        />
  
        <EditMultipleOptionDialog
          open={isEditDialogOpen}
          option={editingOption}
          onOpenChange={(open) => {
            setIsEditDialogOpen(open);
            if (!open) setEditingOption(null);
          }}
          onUpdated={refreshList}
        />
  
        <DeleteMultipleOptionDialog
          open={isDeleteDialogOpen}
          option={deletingOption}
          onOpenChange={(open) => {
            setIsDeleteDialogOpen(open);
            if (!open) setDeletingOption(null);
          }}
          onDeleted={refreshList}
        />
884054fb   “wangming”   项目初始化
361
362
363
      </div>
    );
  }
0e27ddc8   杨鑫   标签
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
  
  function CreateMultipleOptionDialog({
    open,
    onOpenChange,
    onCreated,
  }: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    onCreated: () => void;
  }) {
    const [submitting, setSubmitting] = useState(false);
    const [form, setForm] = useState<LabelMultipleOptionCreateInput>({
      optionCode: "",
      optionName: "",
      optionValuesJson: [],
      state: true,
      orderNum: null,
    });
    const [newValue, setNewValue] = useState("");
  
    const resetForm = () => {
      setForm({
        optionCode: "",
        optionName: "",
        optionValuesJson: [],
        state: true,
        orderNum: null,
      });
      setNewValue("");
    };
  
    useEffect(() => {
      if (!open) {
        resetForm();
      }
    }, [open]);
  
    const addValue = () => {
      const trimmed = newValue.trim();
      if (!trimmed) return;
      if (form.optionValuesJson.includes(trimmed)) {
        toast.error("Duplicate value", {
          description: "This value already exists.",
        });
        return;
      }
      setForm((p) => ({
        ...p,
        optionValuesJson: [...p.optionValuesJson, trimmed],
      }));
      setNewValue("");
    };
  
    const removeValue = (index: number) => {
      setForm((p) => ({
        ...p,
        optionValuesJson: p.optionValuesJson.filter((_, i) => i !== index),
      }));
    };
  
    const submit = async () => {
      if (!form.optionCode.trim() || !form.optionName.trim()) {
        toast.error("Validation failed", {
          description: "Option Code and Option Name are required.",
        });
        return;
      }
      if (form.optionValuesJson.length === 0) {
        toast.error("Validation failed", {
          description: "At least one option value is required.",
        });
        return;
      }
3d4c10ac   杨鑫   对接,标签产品
437
438
439
440
      if (form.orderNum === null || form.orderNum === undefined || !Number.isFinite(form.orderNum)) {
        toast.error("Validation failed", { description: "Order is required." });
        return;
      }
0e27ddc8   杨鑫   标签
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
  
      setSubmitting(true);
      try {
        await createLabelMultipleOption(form);
        toast.success("Multiple option created.", {
          description: "The multiple option has been created successfully.",
        });
        onOpenChange(false);
        onCreated();
      } catch (e: any) {
        toast.error("Failed to create multiple option.", {
          description: e?.message ? String(e.message) : "Please try again.",
        });
      } finally {
        setSubmitting(false);
      }
    };
  
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle>Add New Multiple Option</DialogTitle>
            <DialogDescription>
              Enter the details for the new multiple option.
            </DialogDescription>
          </DialogHeader>
  
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Option Code *</Label>
                <Input
                  placeholder="e.g. OPT_ALLERGENS"
                  value={form.optionCode}
                  onChange={(e) => setForm((p) => ({ ...p, optionCode: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
                <Label>Option Name *</Label>
                <Input
                  placeholder="e.g. Allergens"
                  value={form.optionName}
                  onChange={(e) => setForm((p) => ({ ...p, optionName: e.target.value }))}
                />
              </div>
            </div>
  
            <div className="space-y-2">
              <Label>Option Values *</Label>
              <div className="flex gap-2">
                <Input
                  placeholder="Enter a value and press Add"
                  value={newValue}
                  onChange={(e) => setNewValue(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      e.preventDefault();
                      addValue();
                    }
                  }}
                />
                <Button type="button" onClick={addValue} variant="outline">
                  Add
                </Button>
              </div>
              {form.optionValuesJson.length > 0 && (
                <div className="flex flex-wrap gap-2 mt-2">
                  {form.optionValuesJson.map((val, idx) => (
                    <Badge key={idx} variant="secondary" className="flex items-center gap-1">
                      {val}
                      <button
                        type="button"
                        onClick={() => removeValue(idx)}
                        className="ml-1 hover:text-red-600"
                      >
                        <X className="h-3 w-3" />
                      </button>
                    </Badge>
                  ))}
                </div>
              )}
            </div>
  
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
3d4c10ac   杨鑫   对接,标签产品
527
                <Label>Order *</Label>
0e27ddc8   杨鑫   标签
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
                <Input
                  type="number"
                  placeholder="e.g. 1"
                  value={form.orderNum ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, orderNum: e.target.value ? Number(e.target.value) : null }))}
                />
              </div>
              <div className="flex items-center justify-between border border-gray-200 rounded-md px-3 bg-white" style={{ height: 40 }}>
                <div className="text-sm font-medium text-gray-900">Enabled</div>
                <Switch checked={form.state} onCheckedChange={(checked) => setForm((p) => ({ ...p, state: checked }))} />
              </div>
            </div>
          </div>
  
          <DialogFooter>
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <Button disabled={submitting} onClick={submit}>
              {submitting ? "Creating..." : "Create"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    );
  }
  
  function EditMultipleOptionDialog({
    open,
    option,
    onOpenChange,
    onUpdated,
  }: {
    open: boolean;
    option: LabelMultipleOptionDto | null;
    onOpenChange: (open: boolean) => void;
    onUpdated: () => void;
  }) {
    const [submitting, setSubmitting] = useState(false);
    const [form, setForm] = useState<LabelMultipleOptionUpdateInput>({
      optionCode: "",
      optionName: "",
      optionValuesJson: [],
      state: true,
      orderNum: null,
    });
    const [newValue, setNewValue] = useState("");
  
    useEffect(() => {
      if (open && option) {
        setForm({
          optionCode: option.optionCode ?? "",
          optionName: option.optionName ?? "",
          optionValuesJson: option.optionValuesJson ?? [],
          state: option.state ?? true,
          orderNum: option.orderNum ?? null,
        });
        setNewValue("");
      }
    }, [open, option]);
  
    const addValue = () => {
      const trimmed = newValue.trim();
      if (!trimmed) return;
      if (form.optionValuesJson.includes(trimmed)) {
        toast.error("Duplicate value", {
          description: "This value already exists.",
        });
        return;
      }
      setForm((p) => ({
        ...p,
        optionValuesJson: [...p.optionValuesJson, trimmed],
      }));
      setNewValue("");
    };
  
    const removeValue = (index: number) => {
      setForm((p) => ({
        ...p,
        optionValuesJson: p.optionValuesJson.filter((_, i) => i !== index),
      }));
    };
  
    const submit = async () => {
      if (!option?.id) return;
      if (!form.optionCode.trim() || !form.optionName.trim()) {
        toast.error("Validation failed", {
          description: "Option Code and Option Name are required.",
        });
        return;
      }
      if (form.optionValuesJson.length === 0) {
        toast.error("Validation failed", {
          description: "At least one option value is required.",
        });
        return;
      }
3d4c10ac   杨鑫   对接,标签产品
626
627
628
629
      if (form.orderNum === null || form.orderNum === undefined || !Number.isFinite(form.orderNum)) {
        toast.error("Validation failed", { description: "Order is required." });
        return;
      }
0e27ddc8   杨鑫   标签
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
  
      setSubmitting(true);
      try {
        await updateLabelMultipleOption(option.id, form);
        toast.success("Multiple option updated.", {
          description: "The multiple option has been updated successfully.",
        });
        onOpenChange(false);
        onUpdated();
      } catch (e: any) {
        toast.error("Failed to update multiple option.", {
          description: e?.message ? String(e.message) : "Please try again.",
        });
      } finally {
        setSubmitting(false);
      }
    };
  
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle>Edit Multiple Option</DialogTitle>
            <DialogDescription>
              Update the multiple option details.
            </DialogDescription>
          </DialogHeader>
  
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Option Code *</Label>
                <Input
                  placeholder="e.g. OPT_ALLERGENS"
                  value={form.optionCode}
                  onChange={(e) => setForm((p) => ({ ...p, optionCode: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
                <Label>Option Name *</Label>
                <Input
                  placeholder="e.g. Allergens"
                  value={form.optionName}
                  onChange={(e) => setForm((p) => ({ ...p, optionName: e.target.value }))}
                />
              </div>
            </div>
  
            <div className="space-y-2">
              <Label>Option Values *</Label>
              <div className="flex gap-2">
                <Input
                  placeholder="Enter a value and press Add"
                  value={newValue}
                  onChange={(e) => setNewValue(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      e.preventDefault();
                      addValue();
                    }
                  }}
                />
                <Button type="button" onClick={addValue} variant="outline">
                  Add
                </Button>
              </div>
              {form.optionValuesJson.length > 0 && (
                <div className="flex flex-wrap gap-2 mt-2">
                  {form.optionValuesJson.map((val, idx) => (
                    <Badge key={idx} variant="secondary" className="flex items-center gap-1">
                      {val}
                      <button
                        type="button"
                        onClick={() => removeValue(idx)}
                        className="ml-1 hover:text-red-600"
                      >
                        <X className="h-3 w-3" />
                      </button>
                    </Badge>
                  ))}
                </div>
              )}
            </div>
  
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
3d4c10ac   杨鑫   对接,标签产品
716
                <Label>Order *</Label>
0e27ddc8   杨鑫   标签
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
                <Input
                  type="number"
                  placeholder="e.g. 1"
                  value={form.orderNum ?? ""}
                  onChange={(e) => setForm((p) => ({ ...p, orderNum: e.target.value ? Number(e.target.value) : null }))}
                />
              </div>
              <div className="flex items-center justify-between border border-gray-200 rounded-md px-3 bg-white" style={{ height: 40 }}>
                <div className="text-sm font-medium text-gray-900">Enabled</div>
                <Switch checked={form.state} onCheckedChange={(checked) => setForm((p) => ({ ...p, state: checked }))} />
              </div>
            </div>
          </div>
  
          <DialogFooter>
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <Button disabled={submitting} onClick={submit}>
              {submitting ? "Updating..." : "Update"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    );
  }
  
  function DeleteMultipleOptionDialog({
    open,
    option,
    onOpenChange,
    onDeleted,
  }: {
    open: boolean;
    option: LabelMultipleOptionDto | null;
    onOpenChange: (open: boolean) => void;
    onDeleted: () => void;
  }) {
    const [submitting, setSubmitting] = useState(false);
  
    const name = useMemo(() => {
      const n = (option?.optionName ?? "").trim();
      return n || option?.optionCode || "this option";
    }, [option]);
  
    const submit = async () => {
      if (!option?.id) return;
      setSubmitting(true);
      try {
        await deleteLabelMultipleOption(option.id);
        toast.success("Multiple option deleted.", {
          description: "The multiple option has been removed successfully.",
        });
        onOpenChange(false);
        onDeleted();
      } catch (e: any) {
        toast.error("Failed to delete multiple option.", {
          description: e?.message ? String(e.message) : "Please try again.",
        });
      } finally {
        setSubmitting(false);
      }
    };
  
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-none" style={{ width: "30%" }}>
          <DialogHeader>
            <DialogTitle>Delete Multiple Option</DialogTitle>
            <DialogDescription>This action cannot be undone.</DialogDescription>
          </DialogHeader>
  
          <div className="text-sm text-gray-700">
            Are you sure you want to delete <span className="font-medium">{name}</span>?
          </div>
  
          <DialogFooter className="flex-row flex-wrap justify-end">
            <Button className="min-w-24" variant="outline" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <Button
3af4878d   杨鑫   产品 标签 关联
798
              className="min-w-24 gap-2"
0e27ddc8   杨鑫   标签
799
800
801
802
              variant="destructive"
              disabled={submitting}
              onClick={submit}
            >
3af4878d   杨鑫   产品 标签 关联
803
              <Trash2 className="h-4 w-4 shrink-0" />
0e27ddc8   杨鑫   标签
804
805
806
807
808
809
810
              {submitting ? "Deleting..." : "Delete"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    );
  }