summaryrefslogtreecommitdiff
path: root/lib/techsales-rfq/table/detail-table/rfq-detail-table.tsx
blob: db2331af4c377930f3c0dbbd153ef84271badd7d (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
"use client"

import * as React from "react"
import { useEffect, useState, useCallback, useMemo } from "react"
import {
  DataTableRowAction,
  getRfqDetailColumns,
  RfqDetailView
} from "./rfq-detail-column"
import { toast } from "sonner"

import { Skeleton } from "@/components/ui/skeleton"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Loader2, UserPlus, Send, Trash2, CheckCircle } from "lucide-react"
import { ClientDataTable } from "@/components/client-data-table/data-table"
import { AddVendorDialog } from "./add-vendor-dialog"
import { VendorCommunicationDrawer } from "./vendor-communication-drawer"
import { DeleteVendorDialog } from "./delete-vendors-dialog"
import { QuotationHistoryDialog } from "@/lib/techsales-rfq/table/detail-table/quotation-history-dialog"
import { TechSalesQuotationAttachmentsSheet, type QuotationAttachment } from "../tech-sales-quotation-attachments-sheet"
import type { QuotationInfo } from "./rfq-detail-column"
import { VendorContactSelectionDialog } from "./vendor-contact-selection-dialog"
import { QuotationContactsViewDialog } from "./quotation-contacts-view-dialog"
import { ApprovalPreviewDialog } from "@/lib/approval/client"
import { ApplicationReasonDialog } from "@/lib/rfq-last/vendor/application-reason-dialog"
import { requestTechSalesRfqSendWithApproval } from "@/lib/techsales-rfq/approval-actions"
import { mapTechSalesRfqSendToTemplateVariables } from "@/lib/techsales-rfq/approval-handlers"
import { useSession } from "next-auth/react"

// 기본적인 RFQ 타입 정의
interface TechSalesRfq {
  id: number
  rfqCode: string | null
  status: string
  materialCode?: string | null
  itemName?: string | null
  remark?: string | null
  rfqSendDate?: Date | null
  dueDate?: Date | null
  createdByName?: string | null
  rfqType: "SHIP" | "TOP" | "HULL" | null
  ptypeNm?: string | null
}

// 프로퍼티 정의
interface RfqDetailTablesProps {
  selectedRfq: TechSalesRfq | null
  maxHeight?: string | number
}


export function RfqDetailTables({ selectedRfq, maxHeight }: RfqDetailTablesProps) {
  // console.log("selectedRfq", selectedRfq)
  
  const session = useSession()
  
  // 상태 관리
  const [isLoading, setIsLoading] = useState(false)
  const [details, setDetails] = useState<RfqDetailView[]>([])
  const [vendorDialogOpen, setVendorDialogOpen] = React.useState(false)

  const [isAdddialogLoading, setIsAdddialogLoading] = useState(false)

  const [rowAction, setRowAction] = React.useState<DataTableRowAction<RfqDetailView> | null>(null)
  
  // 벤더 커뮤니케이션 상태 관리
  const [communicationDrawerOpen, setCommunicationDrawerOpen] = useState(false)
  const [selectedVendor, setSelectedVendor] = useState<RfqDetailView | null>(null)

  // 읽지 않은 메시지 개수
  const [unreadMessages, setUnreadMessages] = useState<Record<number, number>>({})

  // 테이블 선택 상태 관리
  const [selectedRows, setSelectedRows] = useState<RfqDetailView[]>([])
  const [isSendingRfq, setIsSendingRfq] = useState(false)
  const [isDeletingVendors, setIsDeletingVendors] = useState(false)

  // 벤더 삭제 확인 다이얼로그 상태 추가
  const [deleteConfirmDialogOpen, setDeleteConfirmDialogOpen] = useState(false)

  // 견적 히스토리 다이얼로그 상태 관리
  const [historyDialogOpen, setHistoryDialogOpen] = useState(false)
  const [selectedQuotationId, setSelectedQuotationId] = useState<number | null>(null)

  // 견적서 첨부파일 sheet 상태 관리
  const [quotationAttachmentsSheetOpen, setQuotationAttachmentsSheetOpen] = useState(false)
  const [selectedQuotationInfo, setSelectedQuotationInfo] = useState<QuotationInfo | null>(null)
  const [quotationAttachments, setQuotationAttachments] = useState<QuotationAttachment[]>([])
  const [isLoadingAttachments, setIsLoadingAttachments] = useState(false)

  // 벤더 contact 선택 다이얼로그 상태 관리
  const [contactSelectionDialogOpen, setContactSelectionDialogOpen] = useState(false)

  // 담당자 조회 다이얼로그 상태 관리
  const [contactsDialogOpen, setContactsDialogOpen] = useState(false)
  const [selectedQuotationForContacts, setSelectedQuotationForContacts] = useState<{ id: number; vendorName?: string } | null>(null)

  // 결재 관련 상태 관리
  const [showApplicationReasonDialog, setShowApplicationReasonDialog] = useState(false)
  const [showApprovalPreview, setShowApprovalPreview] = useState(false)
  const [approvalPreviewData, setApprovalPreviewData] = useState<{
    vendors: Array<{
      vendorId: number
      vendorName: string
    }>
    drmAttachments: Array<{
      fileName?: string | null
      fileSize?: number | null
    }>
    drmAttachmentIds: number[]
    selectedContacts?: Array<{
      vendorId: number
      contactId: number
      contactEmail: string
      contactName: string
    }>
    templateVariables?: Record<string, string>
    applicationReason?: string
  } | null>(null)

  // selectedRfq ID 메모이제이션 (객체 참조 변경 방지)
  const selectedRfqId = useMemo(() => selectedRfq?.id, [selectedRfq?.id])

  // existingVendorIds 메모이제이션
  const existingVendorIds = useMemo(() => {
    return details.map(detail => Number(detail.vendorId)).filter(Boolean);
  }, [details]);

  // 읽지 않은 메시지 로드 함수 메모이제이션
  const loadUnreadMessages = useCallback(async () => {
    if (!selectedRfqId) return;

    try {
      // 기술영업용 읽지 않은 메시지 수 가져오기 함수 구현
      const { getTechSalesUnreadMessageCounts } = await import("@/lib/techsales-rfq/service");
      const unreadData = await getTechSalesUnreadMessageCounts(selectedRfqId);
      setUnreadMessages(unreadData);
    } catch (error) {
      console.error("읽지 않은 메시지 로드 오류:", error);
      setUnreadMessages({});
    }
  }, [selectedRfqId]);

  // 데이터 새로고침 함수 메모이제이션
  const handleRefreshData = useCallback(async () => {
    if (!selectedRfqId) return

    try {
      // 실제 벤더 견적 데이터 다시 로딩
      const { getTechSalesRfqTechVendors } = await import("@/lib/techsales-rfq/service")
      
      const result = await getTechSalesRfqTechVendors(selectedRfqId)
      
      // 데이터 변환
      const transformedData = result.data?.map((item: any) => ({
        ...item,
        detailId: item.id,
        rfqId: selectedRfqId,
        rfqCode: selectedRfq?.rfqCode || null,
        rfqType: selectedRfq?.rfqType || null,
        ptypeNm: selectedRfq?.ptypeNm || null,
        vendorId: item.vendorId ? Number(item.vendorId) : undefined,
      })) || []
      
      setDetails(transformedData)

      // 읽지 않은 메시지 개수 업데이트
      await loadUnreadMessages();
      
      toast.success("데이터를 성공적으로 새로고침했습니다")
    } catch (error) {
      console.error("데이터 새로고침 오류:", error)
      toast.error("데이터를 새로고침하는 중 오류가 발생했습니다")
    }
  }, [selectedRfqId, selectedRfq?.rfqCode, selectedRfq?.rfqType, selectedRfq?.ptypeNm, loadUnreadMessages])

  // 벤더 추가 핸들러 메모이제이션
  const handleAddVendor = useCallback(async () => {
    try {
      setIsAdddialogLoading(true)
      setVendorDialogOpen(true)
    } catch (error) {
      console.error("데이터 로드 오류:", error)
      toast.error("벤더 정보를 불러오는 중 오류가 발생했습니다")
    } finally {
      setIsAdddialogLoading(false)
    }
  }, [])

  // RFQ 발송 핸들러 메모이제이션 - contact selection dialog 사용
  const handleSendRfq = useCallback(async () => {
    if (selectedRows.length === 0) {
      toast.warning("발송할 벤더를 선택해주세요.");
      return;
    }

    if (!selectedRfqId) {
      toast.error("선택된 RFQ가 없습니다.");
      return;
    }

    // 선택된 벤더들의 status가 모두 'Assigned'인지 확인
    const nonAssignedVendors = selectedRows.filter(row => row.status !== "Assigned");
    if (nonAssignedVendors.length > 0) {
      toast.warning("Assigned 상태의 벤더만 RFQ를 발송할 수 있습니다.");
      return;
    }

    // 선택된 벤더들의 담당자 존재 여부 확인
    try {
      const vendorIds = selectedRows.map(row => row.vendorId).filter(Boolean) as number[];
      
      if (vendorIds.length === 0) {
        toast.error("유효한 벤더가 선택되지 않았습니다.");
        return;
      }

      // 벤더별 담당자 조회
      const { getTechVendorsContacts } = await import("@/lib/techsales-rfq/service");
      const contactsResult = await getTechVendorsContacts(vendorIds);
      
      if (contactsResult.error) {
        toast.error("벤더 담당자 정보를 불러오는 중 오류가 발생했습니다.");
        return;
      }

      // 담당자가 없는 벤더 확인
      const vendorsWithoutContacts = vendorIds.filter(vendorId => {
        const vendorContacts = contactsResult.data[vendorId];
        return !vendorContacts || vendorContacts.contacts.length === 0;
      });

      if (vendorsWithoutContacts.length > 0) {
        toast.error("담당자가 지정되지 않은 협력업체가 있습니다.");
        return;
      }

      // contact selection dialog 열기
      setContactSelectionDialogOpen(true);
    } catch (error) {
      console.error("벤더 담당자 확인 오류:", error);
      toast.error("벤더 담당자 정보를 확인하는 중 오류가 발생했습니다.");
    }
  }, [selectedRows, selectedRfqId]);

  // contact 기반 RFQ 발송 핸들러
  const handleSendRfqWithContacts = useCallback(async (selectedContacts: Array<{
    vendorId: number;
    contactId: number;
    contactEmail: string;
    contactName: string;
  }>) => {
    if (!selectedRfqId) {
      toast.error("선택된 RFQ가 없습니다.");
      return;
    }

    try {
      setIsSendingRfq(true);
      
      // DRM 해제 여부 확인
      const { checkTechSalesRfqHasDrmAttachments, sendTechSalesRfqToVendors } = await import("@/lib/techsales-rfq/service");
      const drmCheck = await checkTechSalesRfqHasDrmAttachments(selectedRfqId);
      
      // DRM 파일이 걸려있으면 결재 프로세스 진행
      if (drmCheck.hasDrm) {
        // 결재 데이터 저장
        setApprovalPreviewData({
          vendors: selectedRows.map(row => ({
            vendorId: row.vendorId!,
            vendorName: row.vendorName || "",
          })),
          drmAttachments: drmCheck.drmAttachments,
          drmAttachmentIds: drmCheck.drmAttachmentIds,
          selectedContacts: selectedContacts,
        });
        
        // 신청사유 입력 다이얼로그 표시
        setShowApplicationReasonDialog(true);
        setIsSendingRfq(false);
        return;
      }
      
      // DRM 해제가 안 걸려있으면 바로 발송
      const vendorIds = selectedRows.map(row => row.vendorId).filter(Boolean);
      const result = await sendTechSalesRfqToVendors({
        rfqId: selectedRfqId,
        vendorIds: vendorIds as number[],
        selectedContacts: selectedContacts
      });
      
      if (result.success) {
        toast.success(result.message || `${selectedContacts.length}명의 연락처에게 RFQ가 발송되었습니다.`);
      } else {
        toast.error(result.message || "RFQ 발송 중 오류가 발생했습니다.");
      }
      
      // 선택 해제
      setSelectedRows([]);
      
      // 데이터 새로고침
      await handleRefreshData();
      
    } catch (error) {
      console.error("RFQ 발송 오류:", error);
      toast.error("RFQ 발송 중 오류가 발생했습니다.");
    } finally {
      setIsSendingRfq(false);
    }
  }, [selectedRfqId, selectedRows, handleRefreshData]);

  // 벤더 선택 핸들러 추가
  const [isAcceptingVendors, setIsAcceptingVendors] = useState(false);

  const handleAcceptVendors = useCallback(async () => {
    if (selectedRows.length === 0) {
      toast.warning("선택할 벤더를 선택해주세요.");
      return;
    }

    if (selectedRows.length > 1) {
      toast.warning("하나의 벤더만 선택할 수 있습니다.");
      return;
    }

    const selectedQuotation = selectedRows[0];
    if (selectedQuotation.status !== "Submitted") {
      toast.warning("제출된 견적서만 선택할 수 있습니다.");
      return;
    }

    try {
      setIsAcceptingVendors(true);
      
      // 벤더 견적 승인 서비스 함수 호출
      const { acceptTechSalesVendorQuotationAction } = await import("@/lib/techsales-rfq/actions");
      
      const result = await acceptTechSalesVendorQuotationAction(selectedQuotation.id);
      
      if (result.success) {
        toast.success(result.message || "벤더가 성공적으로 선택되었습니다.");
      } else {
        toast.error(result.error || "벤더 선택 중 오류가 발생했습니다.");
      }
      
      // 선택 해제
      setSelectedRows([]);
      
      // 데이터 새로고침
      await handleRefreshData();
      
    } catch (error) {
      console.error("벤더 선택 오류:", error);
      toast.error("벤더 선택 중 오류가 발생했습니다.");
    } finally {
      setIsAcceptingVendors(false);
    }
  }, [selectedRows, handleRefreshData]);

  // 벤더 삭제 핸들러 메모이제이션
  const handleDeleteVendors = useCallback(async () => {
    if (selectedRows.length === 0) {
      toast.warning("삭제할 벤더를 선택해주세요.");
      return;
    }

    if (!selectedRfqId) {
      toast.error("선택된 RFQ가 없습니다.");
      return;
    }

    try {
      setIsDeletingVendors(true);
      
      const vendorIds = selectedRows.map(row => row.vendorId).filter(Boolean) as number[];
      
      if (vendorIds.length === 0) {
        toast.error("유효한 벤더 ID가 없습니다.");
        return;
      }

      // 서비스 함수 호출
      const { removeTechVendorsFromTechSalesRfq } = await import("@/lib/techsales-rfq/service");
      
      const result = await removeTechVendorsFromTechSalesRfq({
        rfqId: selectedRfqId,
        vendorIds: vendorIds
      });
      
      if (result.error) {
        toast.error(result.error);
      } else {
        const successCount = result.data?.length || 0
        toast.success(`${successCount}개의 벤더가 성공적으로 삭제되었습니다`);
      }
      
      // 선택 해제
      setSelectedRows([]);
      
      // 데이터 새로고침
      await handleRefreshData();
      
    } catch (error) {
      console.error("벤더 삭제 오류:", error);
      toast.error("벤더 삭제 중 오류가 발생했습니다.");
    } finally {
      setIsDeletingVendors(false);
    }
  }, [selectedRows, selectedRfqId, handleRefreshData]);

  // 벤더 삭제 확인 핸들러
  const handleDeleteVendorsConfirm = useCallback(() => {
    if (selectedRows.length === 0) {
      toast.warning("삭제할 벤더를 선택해주세요.");
      return;
    }
    setDeleteConfirmDialogOpen(true);
  }, [selectedRows]);

  // 벤더 삭제 확정 실행
  const executeDeleteVendors = useCallback(async () => {
    setDeleteConfirmDialogOpen(false);
    await handleDeleteVendors();
  }, [handleDeleteVendors]);


  // 견적 히스토리 다이얼로그 열기 핸들러 메모이제이션
  const handleOpenHistoryDialog = useCallback((quotationId: number) => {
    setSelectedQuotationId(quotationId);
    setHistoryDialogOpen(true);
  }, [])

  // 견적서 첨부파일 sheet 열기 핸들러 메모이제이션
  const handleOpenQuotationAttachmentsSheet = useCallback(async (quotationId: number, quotationInfo: QuotationInfo) => {
    try {
      setIsLoadingAttachments(true);
      setSelectedQuotationInfo(quotationInfo);
      setQuotationAttachmentsSheetOpen(true);

      // 견적서 첨부파일 조회
      const { getTechSalesVendorQuotationAttachments } = await import("@/lib/techsales-rfq/service");
      const result = await getTechSalesVendorQuotationAttachments(quotationId);

      if (result.error) {
        toast.error(result.error);
        setQuotationAttachments([]);
      } else {
        setQuotationAttachments(result.data || []);
      }
    } catch (error) {
      console.error("견적서 첨부파일 조회 오류:", error);
      toast.error("견적서 첨부파일을 불러오는 중 오류가 발생했습니다.");
      setQuotationAttachments([]);
    } finally {
      setIsLoadingAttachments(false);
    }
  }, [])

  // 담당자 조회 다이얼로그 열기 함수
  const handleOpenContactsDialog = useCallback((quotationId: number, vendorName?: string) => {
    setSelectedQuotationForContacts({ id: quotationId, vendorName })
    setContactsDialogOpen(true)
  }, [])

  // 신청사유 입력 완료 핸들러
  const handleApplicationReasonConfirm = useCallback(async (reason: string) => {
    if (!approvalPreviewData) {
      toast.error("결재 데이터가 없습니다.");
      return;
    }

    try {
      // 템플릿 변수 생성 (신청사유 포함)
      const templateVariables = await mapTechSalesRfqSendToTemplateVariables({
        attachments: approvalPreviewData.drmAttachments,
        vendorNames: approvalPreviewData.vendors.map(v => v.vendorName),
        applicationReason: reason,
      });

      // 결재 미리보기 데이터 업데이트
      setApprovalPreviewData({
        ...approvalPreviewData,
        templateVariables,
        applicationReason: reason,
      });

      // 결재 미리보기 열기
      setShowApprovalPreview(true);
    } catch (error) {
      console.error("템플릿 변수 생성 실패:", error);
      toast.error("결재 문서 생성에 실패했습니다.");
    }
  }, [approvalPreviewData]);

  // 결재 미리보기 확인 핸들러
  const handleApprovalConfirm = useCallback(async (approvalData: {
    approvers: string[];
    title: string;
    description?: string;
  }) => {
    if (!approvalPreviewData || !selectedRfq || !session.data?.user) {
      toast.error("결재 데이터가 없습니다.");
      return;
    }

    if (!session.data.user.epId) {
      toast.error("Knox EP ID가 필요합니다.");
      return;
    }

    try {
      const result = await requestTechSalesRfqSendWithApproval({
        rfqId: selectedRfq.id,
        rfqCode: selectedRfq.rfqCode || undefined,
        vendorIds: approvalPreviewData.vendors.map(v => v.vendorId),
        selectedContacts: approvalPreviewData.selectedContacts,
        drmAttachmentIds: approvalPreviewData.drmAttachmentIds,
        drmAttachments: approvalPreviewData.drmAttachments,
        applicationReason: approvalPreviewData.applicationReason || '',
        currentUser: {
          id: Number(session.data.user.id),
          epId: session.data.user.epId || null,
          name: session.data.user.name || undefined,
          email: session.data.user.email || undefined,
        },
        approvers: approvalData.approvers,
      });

      if (result.success) {
        toast.success(result.message);
        setShowApprovalPreview(false);
        setApprovalPreviewData(null);
        setSelectedRows([]);
        await handleRefreshData();
      }
    } catch (error) {
      console.error("결재 상신 실패:", error);
      toast.error(error instanceof Error ? error.message : "결재 상신에 실패했습니다.");
    }
  }, [approvalPreviewData, selectedRfq, session, handleRefreshData]);

  // 칼럼 정의 - unreadMessages 상태 전달 (메모이제이션)
  const columns = useMemo(() =>
    getRfqDetailColumns({
      setRowAction,
      unreadMessages,
      onQuotationClick: handleOpenHistoryDialog,
      openQuotationAttachmentsSheet: handleOpenQuotationAttachmentsSheet,
      openContactsDialog: handleOpenContactsDialog
    }), [unreadMessages, handleOpenHistoryDialog, handleOpenQuotationAttachmentsSheet, handleOpenContactsDialog])

  // 필터 필드 정의 (메모이제이션)
  const advancedFilterFields = useMemo(
    () => [
      {
        id: "vendorName",
        label: "벤더명",
        type: "text",
      },
      {
        id: "vendorCode",
        label: "벤더 코드",
        type: "text",
      },
      {
        id: "currency",
        label: "통화",
        type: "text",
      },
    ],
    []
  )

  // 계산된 값들 메모이제이션
  const vendorsWithQuotations = useMemo(() => 
    details.filter(detail => detail.status === "Submitted").length,
    [details]
  );

  // RFQ ID가 변경될 때 데이터 로드
  useEffect(() => {
    async function loadRfqDetails() {
      if (!selectedRfqId) {
        setDetails([])
        return
      }

      try {
        setIsLoading(true)
        
        // 실제 벤더 견적 데이터 로딩
        const { getTechSalesVendorQuotationsWithJoin } = await import("@/lib/techsales-rfq/service")
        
        const result = await getTechSalesVendorQuotationsWithJoin({
          rfqId: selectedRfqId,
          page: 1,
          perPage: 1000, // 모든 데이터 가져오기
        })
        
        // 데이터 변환 (procurement 패턴에 맞게)
        const transformedData = result.data?.map(item => ({
          ...item,
          detailId: item.id,
          rfqId: selectedRfqId,
          rfqCode: selectedRfq?.rfqCode || null,
          vendorId: item.vendorId ? Number(item.vendorId) : undefined,
          // 기타 필요한 필드 변환
        })) || []
        
        setDetails(transformedData)

        // 읽지 않은 메시지 개수 로드
        await loadUnreadMessages();
        
      } catch (error) {
        console.error("RFQ 디테일 로드 오류:", error)
        setDetails([])
        toast.error("RFQ 세부정보를 불러오는 중 오류가 발생했습니다")
      } finally {
        setIsLoading(false)
      }
    }

    loadRfqDetails()
  }, [selectedRfqId, selectedRfq?.rfqCode, loadUnreadMessages])

  // 주기적으로 읽지 않은 메시지 갱신 (60초마다) - 메모이제이션된 함수 사용
  useEffect(() => {
    if (!selectedRfqId) return;

    const intervalId = setInterval(() => {
      loadUnreadMessages();
    }, 60000); // 60초마다 갱신

    return () => clearInterval(intervalId);
  }, [selectedRfqId, loadUnreadMessages]);

  // rowAction 처리 - procurement 패턴 적용 (메모이제이션)
  useEffect(() => {
    if (!rowAction) return

    const handleRowAction = async () => {
      try {
        // 통신 액션인 경우 드로어 열기
        if (rowAction.type === "communicate") {
          setSelectedVendor(rowAction.row.original);
          setCommunicationDrawerOpen(true);

          // rowAction 초기화
          setRowAction(null);
          return;
        }

        // 삭제 액션인 경우 개별 벤더 삭제
        if (rowAction.type === "delete") {
          const vendor = rowAction.row.original;
          
          if (!vendor.vendorId || !selectedRfqId) {
            toast.error("벤더 정보가 없습니다.");
            setRowAction(null);
            return;
          }

          // Draft 상태 체크
          if (vendor.status !== "Assigned") {
            toast.error("Assigned 상태의 벤더만 삭제할 수 있습니다.");
            setRowAction(null);
            return;
          }

          // 개별 벤더 삭제
          const { removeTechVendorFromTechSalesRfq } = await import("@/lib/techsales-rfq/service");
          
          const result = await removeTechVendorFromTechSalesRfq({
            rfqId: selectedRfqId,
            vendorId: vendor.vendorId
          });
          
          if (result.error) {
            toast.error(result.error);
          } else {
            toast.success(`${vendor.vendorName || '벤더'}가 성공적으로 삭제되었습니다.`);
            // 데이터 새로고침
            await handleRefreshData();
          }

          // rowAction 초기화
          setRowAction(null);
          return;
        }
      } catch (error) {
        console.error("액션 처리 오류:", error);
        toast.error("작업을 처리하는 중 오류가 발생했습니다");
      }
    };

    handleRowAction();
  }, [rowAction, selectedRfqId, handleRefreshData])

  // 선택된 행 변경 핸들러 메모이제이션
  const handleSelectedRowsChange = useCallback((selectedRowsData: RfqDetailView[]) => {
    setSelectedRows(selectedRowsData);
  }, []);

  // 커뮤니케이션 드로어 변경 핸들러 메모이제이션
  const handleCommunicationDrawerChange = useCallback((open: boolean) => {
    setCommunicationDrawerOpen(open);
    // 드로어가 닫힐 때 해당 벤더의 메시지를 읽음 처리하고 읽지 않은 메시지 개수 갱신
    if (!open && selectedVendor?.vendorId && selectedRfqId) {
      // 메시지를 읽음으로 처리
      import("@/lib/techsales-rfq/service").then(({ markTechSalesMessagesAsRead }) => {
        markTechSalesMessagesAsRead(selectedRfqId, selectedVendor.vendorId || undefined).catch(error => {
          console.error("메시지 읽음 처리 오류:", error);
        });
      });
      
      // 해당 벤더의 읽지 않은 메시지를 0으로 즉시 업데이트
      setUnreadMessages(prev => ({
        ...prev,
        [selectedVendor.vendorId!]: 0
      }));
      
      // 전체 읽지 않은 메시지 개수 갱신
      loadUnreadMessages();
    }
  }, [selectedVendor, selectedRfqId, loadUnreadMessages]);

  if (!selectedRfq) {
    return (
      <div className="flex items-center justify-center h-full text-muted-foreground">
        RFQ를 선택하세요
        </div>
    )
  }

  // 로딩 중인 경우
  if (isLoading) {
    return (
      <div className="p-4 space-y-4">
        <Skeleton className="h-8 w-1/2" />
        <Skeleton className="h-24 w-full" />
        <Skeleton className="h-48 w-full" />
      </div>
    )
  }

  return (
    <div className="h-full overflow-hidden pt-4">
      {/* 테이블 또는 빈 상태 표시 */}
      {details.length > 0 ? (
        <ClientDataTable
          columns={columns}
          data={details}
          advancedFilterFields={advancedFilterFields}
          maxHeight={maxHeight}
          onSelectedRowsChange={handleSelectedRowsChange}
        >
          <div className="flex justify-between items-center">
            <div className="flex items-center gap-2 mr-2">
              {selectedRows.length > 0 && (
                <Badge variant="default" className="h-6">
                  {selectedRows.length}개 선택됨
                </Badge>
              )}
              {/* {totalUnreadMessages > 0 && (
                <Badge variant="destructive" className="h-6">
                  읽지 않은 메시지: {totalUnreadMessages}건
                </Badge>
              )} */}
              {vendorsWithQuotations > 0 && (
                <Badge variant="outline" className="h-6">
                  견적 제출: {vendorsWithQuotations}개 벤더
                </Badge>
              )}
            </div>
            <div className="flex gap-2">
              {/* 벤더 선택 버튼 */}
              <Button
                variant="default"
                size="sm"
                onClick={handleAcceptVendors}
                disabled={
                  selectedRows.length === 0 || 
                  isAcceptingVendors || 
                  selectedRows.length > 1 ||
                  selectedRows.some(row => row.status !== "Submitted")
                }
                className="gap-2"
              >
                {isAcceptingVendors ? (
                  <Loader2 className="size-4 animate-spin" aria-hidden="true" />
                ) : (
                  <CheckCircle className="size-4" aria-hidden="true" />
                )}
                <span>벤더 선택</span>
              </Button>

              {/* RFQ 발송 버튼 */}
            <Button
                variant="outline"
              size="sm"
                onClick={handleSendRfq}
                disabled={
                  selectedRows.length === 0 || 
                  isSendingRfq || 
                  selectedRows.some(row => row.status !== "Assigned") ||
                  selectedRfq?.status === "Closed"
                }
                className="gap-2"
                title={selectedRfq?.status === "Closed" ? "마감된 RFQ는 발송할 수 없습니다." : undefined}
              >
                {isSendingRfq ? (
                  <Loader2 className="size-4 animate-spin" aria-hidden="true" />
                ) : (
                  <Send className="size-4" aria-hidden="true" />
                )}
                <span>RFQ 발송</span>
            </Button>
            
              {/* 벤더 삭제 버튼 */}
              <Button
                variant="outline"
                size="sm"
                onClick={handleDeleteVendorsConfirm}
                disabled={selectedRows.length === 0 || isDeletingVendors}
                className="gap-2"
              >
                {isDeletingVendors ? (
                  <Loader2 className="size-4 animate-spin" aria-hidden="true" />
                ) : (
                  <Trash2 className="size-4" aria-hidden="true" />
                )}
                <span>벤더 삭제</span>
              </Button>
            
              {/* 벤더 추가 버튼 */}
              <Button
                variant="outline"
                size="sm"
                onClick={handleAddVendor}
                disabled={isAdddialogLoading || selectedRfq?.status === "Closed"}
                className="gap-2"
                title={selectedRfq?.status === "Closed" ? "마감된 RFQ는 벤더를 추가할 수 없습니다." : undefined}
              >
                {isAdddialogLoading ? (
                  <Loader2 className="size-4 animate-spin" aria-hidden="true" />
                ) : (
                  <UserPlus className="size-4" aria-hidden="true" />
                )}
                <span>벤더 추가</span>
              </Button>
            </div>
          </div>
        </ClientDataTable>
      ) : (
        <div className="flex h-full items-center justify-center text-muted-foreground">
          <div className="text-center">
            <p className="text-lg font-medium">벤더가 없습니다</p>
            <p className="text-sm">벤더를 추가하여 RFQ를 시작하세요</p>
            <Button
              variant="outline"
              size="sm"
              onClick={handleAddVendor}
              disabled={isAdddialogLoading || selectedRfq?.status === "Closed"}
              className="mt-4 gap-2"
              title={selectedRfq?.status === "Closed" ? "마감된 RFQ는 벤더를 추가할 수 없습니다." : undefined}
            >
              {isAdddialogLoading ? (
                <Loader2 className="size-4 animate-spin" aria-hidden="true" />
              ) : (
                <UserPlus className="size-4" aria-hidden="true" />
              )}
              <span>벤더 추가</span>
          </Button>
        </div>
      </div>
      )}

      {/* 다이얼로그들 */}
      <AddVendorDialog
        open={vendorDialogOpen}
        onOpenChange={setVendorDialogOpen}
        selectedRfq={selectedRfq as unknown as TechSalesRfq}
        existingVendorIds={existingVendorIds}
        onSuccess={handleRefreshData}
      />

      {/* 벤더 커뮤니케이션 드로어 */}
      <VendorCommunicationDrawer
        open={communicationDrawerOpen}
        onOpenChange={handleCommunicationDrawerChange}
        selectedRfq={selectedRfq}
        selectedVendor={selectedVendor}
        onSuccess={handleRefreshData}
      />

      {/* 다중 벤더 삭제 확인 다이얼로그 */}
      {/* <DeleteVendorDialog
        open={deleteConfirmDialogOpen}
        onOpenChange={setDeleteConfirmDialogOpen}
        vendors={selectedRows}
        onConfirm={executeDeleteVendors}
        isLoading={isDeletingVendors}
      /> */}

      {/* 견적 히스토리 다이얼로그 */}
      <QuotationHistoryDialog
        open={historyDialogOpen}
        onOpenChange={setHistoryDialogOpen}
        quotationId={selectedQuotationId}
        isInternal={true}
      />

      {/* 견적서 첨부파일 Sheet */}
      <TechSalesQuotationAttachmentsSheet
        open={quotationAttachmentsSheetOpen}
        onOpenChange={setQuotationAttachmentsSheetOpen}
        quotation={selectedQuotationInfo}
        attachments={quotationAttachments}
        isLoading={isLoadingAttachments}
      />

      {/* 벤더 contact 선택 다이얼로그 */}
      <VendorContactSelectionDialog
        open={contactSelectionDialogOpen}
        onOpenChange={setContactSelectionDialogOpen}
        vendorIds={selectedRows.map(row => row.vendorId).filter(Boolean) as number[]}
        rfqId={selectedRfqId}
        onSendRfq={handleSendRfqWithContacts}
      />

      {/* 담당자 조회 다이얼로그 */}
      <QuotationContactsViewDialog
        open={contactsDialogOpen}
        onOpenChange={setContactsDialogOpen}
        quotationId={selectedQuotationForContacts?.id || null}
        vendorName={selectedQuotationForContacts?.vendorName}
      />

      {/* 신청사유 입력 다이얼로그 */}
      {approvalPreviewData && (
        <ApplicationReasonDialog
          open={showApplicationReasonDialog}
          onOpenChange={setShowApplicationReasonDialog}
          onConfirm={handleApplicationReasonConfirm}
          vendorCount={approvalPreviewData.vendors.length}
          attachmentCount={approvalPreviewData.drmAttachmentIds.length}
        />
      )}

      {/* 결재 미리보기 다이얼로그 */}
      {approvalPreviewData && approvalPreviewData.templateVariables && (
        <ApprovalPreviewDialog
          open={showApprovalPreview}
          onOpenChange={setShowApprovalPreview}
          templateName="암호화해제 신청"
          variables={approvalPreviewData.templateVariables}
          title={`암호화해제 신청 - ${selectedRfq?.rfqCode || 'RFQ'}`}
          currentUser={{
            id: Number(session.data.user.id),
            epId: session.data.user.epId,
            name: session.data.user.name || undefined,
            email: session.data.user.email || undefined,
          }}
          onConfirm={handleApprovalConfirm}
          allowTitleEdit={false}
          allowDescriptionEdit={false}
        />
      )}
    </div>
  )
}