summaryrefslogtreecommitdiff
path: root/lib/rfq-last/vendor-response/editor/quotation-items-table.tsx
blob: 281316eb7758a55081bee8d7689ee033442224af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
59
60
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
104
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
146
147
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
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
255
256
257
258
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
331
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
361
362
363
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
437
438
439
440
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
527
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
626
627
628
629
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
716
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
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
"use client"

import { useFormContext, useFieldArray } from "react-hook-form"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Checkbox } from "@/components/ui/checkbox"
import { Button } from "@/components/ui/button"
import { Calendar } from "@/components/ui/calendar"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Badge } from "@/components/ui/badge"
import { Label } from "@/components/ui/label"
import { Separator } from "@/components/ui/separator"
import { ScrollArea } from "@/components/ui/scroll-area"
import { CalendarIcon, Eye, FileText, Download, ExternalLink, Upload, FileDown } from "lucide-react"
import { format } from "date-fns"
import { cn, formatCurrency } from "@/lib/utils"
import { useState, useEffect, useRef } from "react"
import { toast } from "sonner"
import { checkPosFileExists, getDownloadUrlByMaterialCode } from "@/lib/pos"
import { PosFileSelectionDialog } from "@/lib/pos/components/pos-file-selection-dialog"
import ExcelJS from "exceljs"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"

interface QuotationItemsTableProps {
  prItems: any[]
  decimalPlaces?: number
}

export default function QuotationItemsTable({ prItems, decimalPlaces = 2 }: QuotationItemsTableProps) {
  const { control, register, setValue, watch } = useFormContext()
  const { fields } = useFieldArray({
    control,
    name: "quotationItems"
  })
  
  const [selectedItem, setSelectedItem] = useState<any>(null)
  const [showDetail, setShowDetail] = useState(false)
  const [showBulkDateDialog, setShowBulkDateDialog] = useState(false)
  const [bulkDeliveryDate, setBulkDeliveryDate] = useState<Date | undefined>(undefined)
  
  // POS 파일 관련 상태
  const [posDialogOpen, setPosDialogOpen] = useState(false)
  const [selectedMaterialCode, setSelectedMaterialCode] = useState<string>("")
  const [posFiles, setPosFiles] = useState<Array<{
    fileName: string
    dcmtmId: string
    projNo: string
    posNo: string
    posRevNo: string
    fileSer: string
  }>>([])
  const [loadingPosFiles, setLoadingPosFiles] = useState(false)
  const [downloadingFileIndex, setDownloadingFileIndex] = useState<number | null>(null)
  
  // 엑셀 import/export 관련 상태
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [isImporting, setIsImporting] = useState(false)

  const currency = watch("vendorCurrency") || "USD"
  const quotationItems = watch("quotationItems")

  console.log(prItems,"prItems")
  
  // PR 아이템 정보를 quotationItems에 초기화
  useEffect(() => {
    if (prItems && prItems.length > 0) {
      prItems.forEach((prItem, index) => {
        // PR 아이템 정보를 quotationItem에 포함
        setValue(`quotationItems.${index}.prNo`, prItem.prNo)
        setValue(`quotationItems.${index}.materialCode`, prItem.materialCode)
        setValue(`quotationItems.${index}.materialDescription`, prItem.materialDescription)
        setValue(`quotationItems.${index}.quantity`, prItem.quantity)
        setValue(`quotationItems.${index}.uom`, prItem.uom)
        setValue(`quotationItems.${index}.rfqPrItemId`, prItem.id)
        
        // currency는 vendorCurrency를 따름
        setValue(`quotationItems.${index}.currency`, currency)
        
        // 납기일은 PR납기요청일을 Default로 설정 (기존 값이 없을 때만)
        const currentDeliveryDate = quotationItems?.[index]?.vendorDeliveryDate
        if (prItem.deliveryDate && !currentDeliveryDate) {
          setValue(`quotationItems.${index}.vendorDeliveryDate`, new Date(prItem.deliveryDate))
        }
      })
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [prItems, setValue, currency])
  
  // 단가 * 수량 계산
  const calculateTotal = (index: number) => {
    const item = quotationItems[index]
    const prItem = prItems[index]
    if (item && prItem) {
      const total = (item.unitPrice || 0) * (prItem.quantity || 0)
      setValue(`quotationItems.${index}.totalPrice`, total)
      
      // PR 아이템 정보도 함께 업데이트 (값이 변경되었을 수 있음)
      setValue(`quotationItems.${index}.prNo`, prItem.prNo)
      setValue(`quotationItems.${index}.materialCode`, prItem.materialCode)
      setValue(`quotationItems.${index}.materialDescription`, prItem.materialDescription)
      setValue(`quotationItems.${index}.quantity`, prItem.quantity)
      setValue(`quotationItems.${index}.uom`, prItem.uom)
    }
  }

  // 일괄 납기일 적용
  const applyBulkDeliveryDate = () => {
    if (bulkDeliveryDate && fields.length > 0) {
      fields.forEach((_, index) => {
        setValue(`quotationItems.${index}.vendorDeliveryDate`, bulkDeliveryDate)
      })
      setShowBulkDateDialog(false)
      setBulkDeliveryDate(undefined)
    }
  }

  // 납기일 초기화 (주석처리)
  // const clearAllDeliveryDates = () => {
  //   fields.forEach((_, index) => {
  //     setValue(`quotationItems.${index}.vendorDeliveryDate`, undefined)
  //   })
  // }
  
  // 사양서 링크 열기
  const handleOpenSpec = (specUrl: string) => {
    window.open(specUrl, '_blank', 'noopener,noreferrer')
  }

  // POS 파일 목록 조회 및 다이얼로그 열기
  const handleOpenPosDialog = async (materialCode: string) => {
    if (!materialCode) {
      toast.error("자재코드가 없습니다")
      return
    }

    setLoadingPosFiles(true)
    setSelectedMaterialCode(materialCode)

    try {
      toast.loading(`POS 파일 목록 조회 중... (${materialCode})`, { id: `pos-check-${materialCode}` })
      
      const result = await checkPosFileExists(materialCode)
      
      if (result.exists && result.files && result.files.length > 0) {
        const detailResult = await getDownloadUrlByMaterialCode(materialCode)
        
        if (detailResult.success && detailResult.availableFiles) {
          setPosFiles(detailResult.availableFiles)
          setPosDialogOpen(true)
          toast.success(`${result.fileCount}개의 POS 파일을 찾았습니다`, { id: `pos-check-${materialCode}` })
        } else {
          toast.error('POS 파일 정보를 가져올 수 없습니다', { id: `pos-check-${materialCode}` })
        }
      } else {
        toast.error(result.error || 'POS 파일을 찾을 수 없습니다', { id: `pos-check-${materialCode}` })
      }
    } catch (error) {
      console.error("POS 파일 조회 오류:", error)
      toast.error("POS 파일 조회에 실패했습니다", { id: `pos-check-${materialCode}` })
    } finally {
      setLoadingPosFiles(false)
    }
  }

  // POS 파일 다운로드 실행
  const handleDownloadPosFile = async (fileIndex: number, fileName: string) => {
    if (!selectedMaterialCode) return

    setDownloadingFileIndex(fileIndex)

    try {
      toast.loading(`POS 파일 다운로드 준비 중...`, { id: `download-${fileIndex}` })
      
      const downloadUrl = `/api/pos/download-on-demand?materialCode=${encodeURIComponent(selectedMaterialCode)}&fileIndex=${fileIndex}`
      
      toast.success(`POS 파일 다운로드 시작: ${fileName}`, { id: `download-${fileIndex}` })
      window.open(downloadUrl, '_blank', 'noopener,noreferrer')
      
      setTimeout(() => {
        setDownloadingFileIndex(null)
      }, 1000)
    } catch (error) {
      console.error("POS 파일 다운로드 오류:", error)
      toast.error("POS 파일 다운로드에 실패했습니다", { id: `download-${fileIndex}` })
      setDownloadingFileIndex(null)
    }
  }

  // POS 다이얼로그 닫기
  const handleClosePosDialog = () => {
    setPosDialogOpen(false)
    setSelectedMaterialCode("")
    setPosFiles([])
    setDownloadingFileIndex(null)
  }
  
  // 엑셀 Export
  const handleExportExcel = async () => {
    try {
      const workbook = new ExcelJS.Workbook()
      const worksheet = workbook.addWorksheet('견적품목')
      
      // 헤더 설정
      worksheet.columns = [
        { header: 'No', key: 'no', width: 10 },
        { header: 'PR No', key: 'prNo', width: 15 },
        { header: 'PR 아이템', key: 'prItem', width: 15 },
        { header: '자재코드', key: 'materialCode', width: 20 },
        { header: '자재명', key: 'materialDescription', width: 40 },
        { header: '수량', key: 'quantity', width: 15 },
        { header: '단위', key: 'uom', width: 10 },
        { header: '중량', key: 'grossWeight', width: 15 },
        { header: '중량단위', key: 'gwUom', width: 15 },
        { header: '단가', key: 'unitPrice', width: 20 },
        { header: '총액', key: 'totalPrice', width: 20 },
        { header: 'Spec.', key: 'specNo', width: 20 },
        { header: 'POS', key: 'pos', width: 15 },
        { header: 'PR납기 요청일', key: 'deliveryDate', width: 20 },
        { header: '벤더 가능납기일', key: 'vendorDeliveryDate', width: 20 },
      ]
      
      // 데이터 추가
      fields.forEach((field, index) => {
        const prItem = prItems[index]
        const quotationItem = quotationItems[index]
        const row = worksheet.addRow({
          no: index + 1,
          prNo: prItem?.prNo || '',
          prItem: prItem?.prItem || prItem?.rfqItem || '',
          materialCode: prItem?.materialCode || '',
          materialDescription: prItem?.materialDescription || '',
          quantity: prItem?.quantity || 0,
          uom: prItem?.uom || '',
          grossWeight: prItem?.grossWeight || 0,
          gwUom: prItem?.gwUom || '',
          unitPrice: quotationItem?.unitPrice || 0,
          totalPrice: quotationItem?.totalPrice || 0,
          specNo: prItem?.specNo || '',
          pos: prItem?.materialCode ? 'POS' : '',
          deliveryDate: prItem?.deliveryDate ? format(new Date(prItem.deliveryDate), 'yyyy-MM-dd') : '',
          vendorDeliveryDate: quotationItem?.vendorDeliveryDate ? format(new Date(quotationItem.vendorDeliveryDate), 'yyyy-MM-dd') : '',
        })
      })
      
      // 스타일 적용
      worksheet.getRow(1).font = { bold: true }
      worksheet.getRow(1).fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFE0E0E0' }
      }
      
      // 파일 다운로드
      const buffer = await workbook.xlsx.writeBuffer()
      const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `견적품목_${format(new Date(), 'yyyyMMdd_HHmmss')}.xlsx`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      
      toast.success('엑셀 파일이 다운로드되었습니다.')
    } catch (error) {
      console.error('엑셀 Export 오류:', error)
      toast.error('엑셀 파일 다운로드에 실패했습니다.')
    }
  }
  
  // 엑셀 Import
  const handleImportExcel = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (!file) return
    
    if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
      toast.error('Excel 파일(.xlsx 또는 .xls)만 업로드 가능합니다')
      return
    }
    
    setIsImporting(true)
    try {
      const workbook = new ExcelJS.Workbook()
      const arrayBuffer = await file.arrayBuffer()
      await workbook.xlsx.load(arrayBuffer)
      
      const worksheet = workbook.worksheets[0]
      if (!worksheet) {
        toast.error('워크시트를 찾을 수 없습니다.')
        return
      }
      
      // 헤더 매핑
      const headerRow = worksheet.getRow(1)
      const headerMap: { [key: string]: number } = {}
      headerRow.eachCell((cell, colNumber) => {
        const header = String(cell.value || '').trim()
        if (header) {
          headerMap[header] = colNumber
        }
      })
      
      // 데이터 읽기
      let successCount = 0
      let errorCount = 0
      
      worksheet.eachRow((row, rowNumber) => {
        if (rowNumber === 1) return // 헤더 건너뛰기
        
        const index = rowNumber - 2 // 0-based index
        if (index >= fields.length) return
        
        try {
          const unitPriceCol = headerMap['단가'] || headerMap['unitPrice']
          const totalPriceCol = headerMap['총액'] || headerMap['totalPrice']
          const vendorDeliveryDateCol = headerMap['벤더 가능납기일'] || headerMap['vendorDeliveryDate']
          
          if (unitPriceCol) {
            const unitPriceValue = row.getCell(unitPriceCol).value
            const unitPrice = typeof unitPriceValue === 'number' ? unitPriceValue : parseFloat(String(unitPriceValue || 0))
            if (!isNaN(unitPrice) && unitPrice >= 0) {
              const formattedPrice = decimalPlaces === 0 
                ? Math.floor(unitPrice) 
                : parseFloat(unitPrice.toFixed(decimalPlaces))
              setValue(`quotationItems.${index}.unitPrice`, formattedPrice)
              calculateTotal(index)
              successCount++
            }
          }
          
          if (totalPriceCol) {
            const totalPriceValue = row.getCell(totalPriceCol).value
            const totalPrice = typeof totalPriceValue === 'number' ? totalPriceValue : parseFloat(String(totalPriceValue || 0))
            if (!isNaN(totalPrice) && totalPrice >= 0) {
              setValue(`quotationItems.${index}.totalPrice`, totalPrice)
            }
          }
          
          if (vendorDeliveryDateCol) {
            const dateValue = row.getCell(vendorDeliveryDateCol).value
            if (dateValue) {
              let date: Date | null = null
              if (dateValue instanceof Date) {
                date = dateValue
              } else if (typeof dateValue === 'string') {
                date = new Date(dateValue)
              } else if (typeof dateValue === 'number') {
                // Excel serial date
                date = new Date((dateValue - 25569) * 86400 * 1000)
              }
              
              if (date && !isNaN(date.getTime())) {
                setValue(`quotationItems.${index}.vendorDeliveryDate`, date)
              }
            }
          }
        } catch (error) {
          console.error(`Row ${rowNumber} import error:`, error)
          errorCount++
        }
      })
      
      if (fileInputRef.current) {
        fileInputRef.current.value = ''
      }
      
      toast.success(`${successCount}개 항목이 성공적으로 가져왔습니다.${errorCount > 0 ? ` (${errorCount}개 오류)` : ''}`)
    } catch (error) {
      console.error('엑셀 Import 오류:', error)
      toast.error('엑셀 파일 가져오기에 실패했습니다.')
    } finally {
      setIsImporting(false)
    }
  }
  
  const totalAmount = quotationItems?.reduce(
    (sum: number, item: any) => sum + (item.totalPrice || 0), 0
  ) || 0
  
  // 상세 정보 다이얼로그
  const ItemDetailDialog = ({ item, prItem, index }: any) => {
    const [localDeviationReason, setLocalDeviationReason] = useState("")
    const [localItemRemark, setLocalItemRemark] = useState("")
    const [localTechnicalCompliance, setLocalTechnicalCompliance] = useState(false)
    const [localAlternativeProposal, setLocalAlternativeProposal] = useState("")

    // 다이얼로그가 열릴 때 기존 값으로 초기화
    useEffect(() => {
      if (item) {
        setLocalDeviationReason(item.deviationReason || "")
        setLocalItemRemark(item.itemRemark || "")
        setLocalTechnicalCompliance(item.technicalCompliance || false)
        setLocalAlternativeProposal(item.alternativeProposal || "")
      }
    }, [item])

    // 저장 버튼 클릭 핸들러
    const handleSaveDetail = () => {
      setValue(`quotationItems.${index}.deviationReason`, localTechnicalCompliance ? "" : localDeviationReason)
      setValue(`quotationItems.${index}.itemRemark`, localItemRemark)
      setValue(`quotationItems.${index}.technicalCompliance`, localTechnicalCompliance)
      setValue(`quotationItems.${index}.alternativeProposal`, localAlternativeProposal)
      setShowDetail(false)
    }

    // 취소 버튼 클릭 핸들러
    const handleCancelDetail = () => {
      setShowDetail(false)
    }

    return (
      <Dialog open={showDetail} onOpenChange={(open) => !open && setShowDetail(false)}>
      <DialogContent className="max-w-3xl max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>견적 상세 정보</DialogTitle>
          <DialogDescription>
            {prItem.materialCode} - {prItem.materialDescription}
          </DialogDescription>
        </DialogHeader>
        
        <div className="space-y-4">
          {/* PR 아이템 정보 */}
          {/* <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base">PR 아이템 정보</CardTitle>
            </CardHeader>
            <CardContent className="grid grid-cols-2 gap-4">
              <div>
                <Label className="text-xs text-muted-foreground">PR 번호</Label>
                <p className="font-medium">{prItem.prNo}</p>
              </div>
              <div>
                <Label className="text-xs text-muted-foreground">자재 코드</Label>
                <p className="font-medium">{prItem.materialCode}</p>
              </div>
              <div>
                <Label className="text-xs text-muted-foreground">수량</Label>
                <p className="font-medium">{prItem.quantity} {prItem.uom}</p>
              </div>
              <div>
                <Label className="text-xs text-muted-foreground">요청 납기일</Label>
                <p className="font-medium">
                  {prItem.deliveryDate ? format(new Date(prItem.deliveryDate), "yyyy-MM-dd") : '-'}
                </p>
              </div>
              {prItem.specNo && (
                <div>
                  <Label className="text-xs text-muted-foreground">스펙 번호</Label>
                  <p className="font-medium">{prItem.specNo}</p>
                </div>
              )}
              {prItem.trackingNo && (
                <div>
                  <Label className="text-xs text-muted-foreground">추적 번호</Label>
                  <p className="font-medium">{prItem.trackingNo}</p>
                </div>
              )}
            </CardContent>
          </Card> */}
          
          {/* 제조사 정보 */}
          {/* <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base">제조사 정보</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor={`manufacturer-${index}`}>제조사</Label>
                  <Input
                    id={`manufacturer-${index}`}
                    {...register(`quotationItems.${index}.manufacturer`)}
                    placeholder="제조사 입력"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor={`manufacturerCountry-${index}`}>제조국</Label>
                  <Input
                    id={`manufacturerCountry-${index}`}
                    {...register(`quotationItems.${index}.manufacturerCountry`)}
                    placeholder="제조국 입력"
                  />
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor={`modelNo-${index}`}>모델 번호</Label>
                <Input
                  id={`modelNo-${index}`}
                  {...register(`quotationItems.${index}.modelNo`)}
                  placeholder="모델 번호 입력"
                />
              </div>
            </CardContent>
          </Card> */}
          
          {/* 기술 준수 및 대안 */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base">기술 사양</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex items-center space-x-2">
                <Checkbox
                  id={`technicalCompliance-${index}`}
                  checked={localTechnicalCompliance}
                  onCheckedChange={(checked) => setLocalTechnicalCompliance(checked === true)}
                />
                <Label htmlFor={`technicalCompliance-${index}`}>
                  기술 사양 준수
                </Label>
              </div>
              
              {!localTechnicalCompliance && (
                <div className="space-y-2">
                  <Label htmlFor={`alternativeProposal-${index}`}>
                    대안 제안 <span className="text-red-500">*</span>
                  </Label>
                  <Textarea
                    id={`alternativeProposal-${index}`}
                    value={localAlternativeProposal}
                    onChange={(e) => setLocalAlternativeProposal(e.target.value)}
                    placeholder="기술 사양을 준수하지 않는 경우 대안을 제시해주세요"
                    className="min-h-[100px]"
                  />
                </div>
              )}

              {!localTechnicalCompliance && (
                <div className="space-y-2">
                  <Label htmlFor={`deviationReason-${index}`}>편차 사유</Label>
                  <Textarea
                    id={`deviationReason-${index}`}
                    value={localDeviationReason}
                    onChange={(e) => setLocalDeviationReason(e.target.value)}
                    placeholder="요구사항과 다른 부분이 있는 경우 사유를 입력하세요"
                    className="min-h-[80px]"
                  />
                </div>
              )}
            </CardContent>
          </Card>
          
          {/* 할인 정보 */}
          {/* <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base">할인 정보</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor={`discountRate-${index}`}>할인율 (%)</Label>
                  <Input
                    id={`discountRate-${index}`}
                    type="number"
                    step="0.01"
                    {...register(`quotationItems.${index}.discountRate`, { valueAsNumber: true })}
                    onChange={(e) => {
                      setValue(`quotationItems.${index}.discountRate`, parseFloat(e.target.value))
                      applyDiscount(index)
                    }}
                    placeholder="0.00"
                  />
                </div>
                <div className="space-y-2">
                  <Label>할인 금액</Label>
                  <div className="h-10 px-3 py-2 border rounded-md bg-muted">
                    {formatCurrency(
                      (watch(`quotationItems.${index}.unitPrice`) || 0) * 
                      (prItem.quantity || 0) * 
                      ((watch(`quotationItems.${index}.discountRate`) || 0) / 100),
                      currency
                    )}
                  </div>
                </div>
              </div>
            </CardContent>
          </Card> */}
          
          {/* 비고 */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base">비고</CardTitle>
            </CardHeader>
            <CardContent>
              <Textarea
                value={localItemRemark}
                onChange={(e) => setLocalItemRemark(e.target.value)}
                placeholder="아이템별 비고사항을 입력하세요"
                className="min-h-[100px]"
              />
            </CardContent>
          </Card>
        </div>

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            onClick={handleCancelDetail}
          >
            취소
          </Button>
          <Button
            type="button"
            onClick={handleSaveDetail}
          >
            확인
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
  
  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle>견적 품목</CardTitle>
            <CardDescription>
              각 PR 아이템에 대한 견적 단가와 정보를 입력하세요
            </CardDescription>
          </div>
          <div className="flex items-center gap-2">
            <div className="flex gap-2">
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => setShowBulkDateDialog(true)}
              >
                <CalendarIcon className="h-4 w-4 mr-1" />
                전체 납기일 설정
              </Button>
              {/* 납기일 초기화 버튼 주석처리 */}
              {/* <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={clearAllDeliveryDates}
              >
                납기일 초기화
              </Button> */}
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={handleExportExcel}
              >
                <FileDown className="h-4 w-4 mr-1" />
                엑셀 Export
              </Button>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => fileInputRef.current?.click()}
                disabled={isImporting}
              >
                <Upload className="h-4 w-4 mr-1" />
                {isImporting ? '가져오는 중...' : '엑셀 Import'}
              </Button>
              <input
                ref={fileInputRef}
                type="file"
                accept=".xlsx,.xls"
                onChange={handleImportExcel}
                style={{ display: 'none' }}
              />
            </div>
            <div className="text-right">
              <p className="text-sm text-muted-foreground">총 견적금액</p>
              <p className="text-2xl font-bold text-primary">
                {formatCurrency(totalAmount, currency)}
              </p>
            </div>
          </div>
        </div>
      </CardHeader>
      <CardContent>
        <ScrollArea className="h-[600px]">
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[60px]">No</TableHead>
                  <TableHead className="w-[100px]">PR No</TableHead>
                  <TableHead className="w-[80px]">PR 아이템</TableHead>
                  <TableHead className="min-w-[150px]">자재코드</TableHead>
                  <TableHead className="min-w-[200px]">자재명</TableHead>
                  <TableHead className="text-right w-[80px]">수량</TableHead>
                  <TableHead className="w-[60px]">단위</TableHead>
                  <TableHead className="text-right w-[80px]">중량</TableHead>
                  <TableHead className="w-[60px]">중량단위</TableHead>
                  <TableHead className="w-[150px]">단가</TableHead>
                  <TableHead className="text-right w-[150px]">총액</TableHead>
                  <TableHead className="w-[120px]">Spec.</TableHead>
                  <TableHead className="w-[100px]">POS</TableHead>
                  <TableHead className="w-[150px]">PR납기 요청일</TableHead>
                  <TableHead className="w-[150px]">벤더 가능납기일</TableHead>
                  <TableHead className="w-[80px]">상세</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {fields.map((field, index) => {
                  const prItem = prItems[index]
                  const quotationItem = quotationItems[index]
                  const isMajor = prItem?.majorYn
                  
                  return (
                    <TableRow key={field.id} className={isMajor ? "bg-blue-50 border-l-4 border-l-blue-500" : ""}>
                      <TableCell>
                        <div className="flex flex-col items-center gap-1">
                          <span className="text-xs font-mono">#{index + 1}</span>
                          {isMajor && (
                            <Badge variant="default" className="text-xs px-1 py-0">
                              주요
                            </Badge>
                          )}
                        </div>
                      </TableCell>
                      <TableCell className="font-mono text-xs">
                        {prItem?.prNo || "-"}
                      </TableCell>
                      <TableCell className="font-mono text-xs">
                        {prItem?.prItem || prItem?.rfqItem || "-"}
                      </TableCell>
                      <TableCell>
                        <div className="flex flex-col">
                          <span className="font-mono text-sm font-medium">{prItem?.materialCode || "-"}</span>
                          {prItem?.acc && (
                            <span className="text-xs text-muted-foreground font-mono">
                              ACC: {prItem.acc}
                            </span>
                          )}
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex flex-col max-w-[200px]">
                          <p className="truncate text-sm font-medium" title={prItem?.materialDescription}>
                            {prItem?.materialDescription || "-"}
                          </p>
                          {prItem?.materialCategory && (
                            <span className="text-xs text-muted-foreground">
                              {prItem.materialCategory}
                            </span>
                          )}
                          {prItem?.size && (
                            <span className="text-xs text-muted-foreground">
                              크기: {prItem.size}
                            </span>
                          )}
                        </div>
                      </TableCell>
                      <TableCell className="text-right">
                        <span className="text-sm font-medium">
                          {prItem?.quantity ? prItem.quantity.toLocaleString() : "-"}
                        </span>
                      </TableCell>
                      <TableCell>
                        <span className="text-sm text-muted-foreground">
                          {prItem?.uom || "-"}
                        </span>
                      </TableCell>
                      <TableCell className="text-right">
                        <span className="text-sm font-medium">
                          {prItem?.grossWeight ? prItem.grossWeight.toLocaleString() : "-"}
                        </span>
                      </TableCell>
                      <TableCell>
                        <span className="text-sm text-muted-foreground">
                          {prItem?.gwUom || "-"}
                        </span>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-1">
                          <Input
                            type="number"
                            min="0"
                            step={decimalPlaces === 0 ? "1" : `0.${"1".padStart(decimalPlaces, "0")}`}
                            {...register(`quotationItems.${index}.unitPrice`, { valueAsNumber: true })}
                            onChange={(e) => {
                              const inputValue = parseFloat(e.target.value) || 0
                              const value = Math.max(0, decimalPlaces === 0 
                                ? Math.floor(inputValue) 
                                : parseFloat(inputValue.toFixed(decimalPlaces))
                              )
                              setValue(`quotationItems.${index}.unitPrice`, value)
                              calculateTotal(index)
                            }}
                            className="w-[120px]"
                            placeholder={decimalPlaces === 0 ? "0" : `0.${"0".repeat(decimalPlaces)}`}
                          />
                          <span className="text-xs text-muted-foreground">
                            {currency}
                          </span>
                        </div>
                      </TableCell>
                      <TableCell className="text-right font-medium">
                        {formatCurrency(quotationItem?.totalPrice || 0, currency)}
                      </TableCell>
                      <TableCell>
                        {/* Spec. 칼럼 */}
                        <div className="flex flex-col gap-1">
                          {prItem?.specNo && (
                            <div className="flex items-center gap-1">
                              <span className="text-xs font-mono">{prItem.specNo}</span>
                              {prItem.specUrl && (
                                <Button
                                  type="button"
                                  variant="ghost"
                                  size="sm"
                                  className="h-5 w-5 p-0"
                                  onClick={() => handleOpenSpec(prItem.specUrl!)}
                                  title="사양서 열기"
                                >
                                  <ExternalLink className="h-3 w-3" />
                                </Button>
                              )}
                            </div>
                          )}
                          {!prItem?.specNo && <span className="text-xs text-muted-foreground">-</span>}
                        </div>
                      </TableCell>
                      <TableCell>
                        {/* POS 칼럼 */}
                        {prItem?.materialCode ? (
                          <div className="flex items-center gap-1">
                            <FileText className="h-3 w-3 text-green-500" />
                            <Button
                              type="button"
                              variant="ghost"
                              size="sm"
                              className="h-5 p-1 text-xs text-green-600 hover:text-green-800"
                              onClick={() => handleOpenPosDialog(prItem.materialCode!)}
                              disabled={loadingPosFiles && selectedMaterialCode === prItem.materialCode}
                              title={`POS 파일 다운로드 (자재코드: ${prItem.materialCode})`}
                            >
                              <Download className="h-3 w-3 mr-1" />
                              {loadingPosFiles && selectedMaterialCode === prItem.materialCode ? '조회중...' : 'POS'}
                            </Button>
                          </div>
                        ) : (
                          <span className="text-xs text-muted-foreground">-</span>
                        )}
                      </TableCell>
                      <TableCell>
                        {/* PR납기 요청일 */}
                        <span className="text-sm">
                          {prItem?.deliveryDate ? format(new Date(prItem.deliveryDate), "yyyy-MM-dd") : "-"}
                        </span>
                      </TableCell>
                      <TableCell>
                        {/* 벤더 가능납기일 */}
                        <Popover>
                          <PopoverTrigger asChild>
                            <Button
                              variant="outline"
                              size="sm"
                              className={cn(
                                "w-[130px] justify-start text-left font-normal",
                                !quotationItem?.vendorDeliveryDate && "text-muted-foreground"
                              )}
                            >
                              <CalendarIcon className="mr-2 h-3 w-3" />
                              {quotationItem?.vendorDeliveryDate 
                                ? format(quotationItem.vendorDeliveryDate, "yyyy-MM-dd") 
                                : prItem?.deliveryDate
                                ? format(new Date(prItem.deliveryDate), "yyyy-MM-dd")
                                : "선택"}
                            </Button>
                          </PopoverTrigger>
                          <PopoverContent className="w-auto p-0" align="start">
                            <Calendar
                              mode="single"
                              selected={quotationItem?.vendorDeliveryDate || (prItem?.deliveryDate ? new Date(prItem.deliveryDate) : undefined)}
                              onSelect={(date) => setValue(`quotationItems.${index}.vendorDeliveryDate`, date)}
                              initialFocus
                            />
                          </PopoverContent>
                        </Popover>
                        {prItem?.deliveryDate && quotationItem?.vendorDeliveryDate && 
                         new Date(quotationItem.vendorDeliveryDate) > new Date(prItem.deliveryDate) && (
                          <div className="mt-1">
                            <Badge variant="destructive" className="text-xs">
                              지연
                            </Badge>
                          </div>
                        )}
                      </TableCell>
                      <TableCell>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setSelectedItem({ item: quotationItem, prItem, index })
                            setShowDetail(true)
                          }}
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  )
                })}
              </TableBody>
            </Table>
          </div>
        </ScrollArea>
        
        {/* 총액 요약 */}
        <div className="mt-4 flex justify-end">
          <Card className="w-[400px]">
            <CardContent className="pt-4">
              <div className="flex justify-between">
                <span className="font-semibold">총 견적금액</span>
                <span className="text-xl font-bold text-primary">
                  {formatCurrency(totalAmount, currency)}
                </span>
              </div>
            </CardContent>
          </Card>
        </div>
      </CardContent>
      
      {/* 상세 다이얼로그 */}
      {selectedItem && (
        <ItemDetailDialog
          item={selectedItem.item}
          prItem={selectedItem.prItem}
          index={selectedItem.index}
        />
      )}

      {/* 일괄 납기일 설정 다이얼로그 */}
      <Dialog open={showBulkDateDialog} onOpenChange={setShowBulkDateDialog}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>전체 납기일 설정</DialogTitle>
            <DialogDescription>
              모든 PR 아이템에 동일한 납기일을 적용합니다.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="space-y-2">
              <Label>납기일 선택</Label>
              <Popover>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    className={cn(
                      "w-full justify-start text-left font-normal",
                      !bulkDeliveryDate && "text-muted-foreground"
                    )}
                  >
                    <CalendarIcon className="mr-2 h-4 w-4" />
                    {bulkDeliveryDate ? format(bulkDeliveryDate, "yyyy-MM-dd") : "날짜 선택"}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0" align="start">
                  <Calendar
                    mode="single"
                    selected={bulkDeliveryDate}
                    onSelect={setBulkDeliveryDate}
                    initialFocus
                  />
                </PopoverContent>
              </Popover>
            </div>

            <div className="bg-muted/50 rounded-lg p-3">
              <p className="text-sm text-muted-foreground">
                선택된 날짜가 <strong>{fields.length}개</strong>의 모든 PR 아이템에 적용됩니다.
                기존에 설정된 납기일은 모두 교체됩니다.
              </p>
            </div>
          </div>

          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => {
                setShowBulkDateDialog(false)
                setBulkDeliveryDate(undefined)
              }}
            >
              취소
            </Button>
            <Button
              type="button"
              onClick={applyBulkDeliveryDate}
              disabled={!bulkDeliveryDate}
            >
              전체 적용
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      
      {/* POS 파일 선택 다이얼로그 */}
      <PosFileSelectionDialog
        isOpen={posDialogOpen}
        onClose={handleClosePosDialog}
        materialCode={selectedMaterialCode}
        files={posFiles}
        onDownload={handleDownloadPosFile}
        downloadingIndex={downloadingFileIndex}
      />
    </Card>
  )
}