summaryrefslogtreecommitdiff
path: root/lib/avl/table/avl-detail-virtual-table.tsx
blob: 60d98c69ae64bfcb1789239128124a9d0fc6eeff (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
"use client"

import * as React from "react"
import {
  useReactTable,
  getCoreRowModel,
  getSortedRowModel,
  getFilteredRowModel,
  type SortingState,
  type ColumnFiltersState,
  flexRender,
  type Column,
} from "@tanstack/react-table"
import { useVirtualizer } from "@tanstack/react-virtual"
import { toast } from "sonner"
import { ChevronDown, ChevronUp, Search, Download } from "lucide-react"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { BackButton } from "@/components/ui/back-button"
import { virtualColumns } from "./avl-detail-virtual-columns"
import type { AvlDetailItem } from "../types"
import { exportTableToExcel } from "@/lib/export_all"

interface AvlDetailVirtualTableProps {
  data: AvlDetailItem[]
  avlListId: number
  avlType?: '프로젝트AVL' | '선종별표준AVL' | string
  projectInfo?: {
    code?: string
    pspid?: string
    OWN_NM?: string
    kunnrNm?: string
  }
  shipOwnerName?: string
  businessType?: string
}

function Filter({ column }: { column: Column<any, unknown> }) {
  const columnFilterValue = column.getFilterValue()
  const id = column.id

  // Boolean 필터 (faTarget, shiBlacklist, shiBcc)
  if (id === 'faTarget' || id === 'shiBlacklist' || id === 'shiBcc' || id === 'shiAvl') {
    return (
      <div onClick={(e) => e.stopPropagation()} className="mt-2">
        <Select
          value={(columnFilterValue as string) ?? "all"}
          onValueChange={(value) => column.setFilterValue(value === "all" ? undefined : value === "true")}
        >
          <SelectTrigger className="h-8 w-full">
            <SelectValue placeholder="All" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All</SelectItem>
            <SelectItem value="true">Yes</SelectItem>
            <SelectItem value="false">No</SelectItem>
          </SelectContent>
        </Select>
      </div>
    )
  }

  // FA Status 필터 (O 또는 빈 값 - 데이터에 따라 조정 필요)
  if (id === 'faStatus') {
    return (
      <div onClick={(e) => e.stopPropagation()} className="mt-2">
        <Select
          value={(columnFilterValue as string) ?? "all"}
          onValueChange={(value) => column.setFilterValue(value === "all" ? undefined : value)}
        >
          <SelectTrigger className="h-8 w-full">
            <SelectValue placeholder="All" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All</SelectItem>
            <SelectItem value="O">YES</SelectItem>
            <SelectItem value="X">NO</SelectItem>
          </SelectContent>
        </Select>
      </div>
    )
  }

  // 일반 텍스트 검색
  return (
    <div onClick={(e) => e.stopPropagation()} className="mt-2">
      <Input
        type="text"
        value={(columnFilterValue ?? '') as string}
        onChange={(e) => column.setFilterValue(e.target.value)}
        placeholder="Search..."
        className="h-8 w-full font-normal bg-background"
      />
    </div>
  )
}

export function AvlDetailVirtualTable({
  data,
  avlType,
  projectInfo,
  businessType,
}: AvlDetailVirtualTableProps) {
  // 상태 관리
  const [sorting, setSorting] = React.useState<SortingState>([])
  const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
  const [globalFilter, setGlobalFilter] = React.useState("")

  // 액션 핸들러
  const handleAction = React.useCallback(async (action: string) => {
    try {
      switch (action) {
        case 'vendor-pool':
          window.open('/evcp/vendor-pool', '_blank')
          break

        case 'excel-export':
          try {
            toast.info("엑셀 파일을 생성 중입니다...")
            await exportTableToExcel(table, {
              filename: `AVL_상세내역_${new Date().toISOString().split('T')[0]}`,
              allPages: true,
              excludeColumns: ["select", "actions"],
              useGroupHeader: true,
            })
            toast.success('Excel 파일이 다운로드되었습니다.')
          } catch (error) {
            console.error('Excel export 실패:', error)
            toast.error('Excel 내보내기에 실패했습니다.')
          }
          break

        default:
          console.log('알 수 없는 액션:', action)
          toast.error('알 수 없는 액션입니다.')
      }
    } catch (error) {
      console.error('액션 처리 실패:', error)
      toast.error('액션 처리 중 오류가 발생했습니다.')
    }
  }, [])

  // TanStack Table 설정
  const table = useReactTable({
    data,
    columns: virtualColumns,
    state: {
      sorting,
      columnFilters,
      globalFilter,
    },
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    onGlobalFilterChange: setGlobalFilter,
    columnResizeMode: "onChange",
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getRowId: (originalRow) => String(originalRow.id),
  })

  // Virtual Scrolling 설정
  const tableContainerRef = React.useRef<HTMLDivElement>(null)

  const { rows } = table.getRowModel()

  const rowVirtualizer = useVirtualizer({
    count: rows.length,
    getScrollElement: () => tableContainerRef.current,
    estimateSize: () => 50, // 행 높이 추정값
    overscan: 10, // 화면 밖 렌더링할 행 수
  })

  const virtualRows = rowVirtualizer.getVirtualItems()
  const totalSize = rowVirtualizer.getTotalSize()

  const paddingTop = virtualRows.length > 0 ? virtualRows?.[0]?.start || 0 : 0
  const paddingBottom = virtualRows.length > 0
    ? totalSize - (virtualRows?.[virtualRows.length - 1]?.end || 0)
    : 0

  return (
    <div className="flex flex-col h-full space-y-4">
      {/* 상단 정보 표시 영역 */}
      <div className="flex items-center justify-between p-4 border rounded-md bg-background">
        <div className="flex items-center gap-4">
          <h2 className="text-lg font-semibold">AVL 상세내역</h2>
          <span className="px-3 py-1 bg-secondary-foreground text-secondary-foreground-foreground rounded-full text-sm font-medium">
            {avlType}
          </span>
          
          <span className="text-sm text-muted-foreground">
            [{businessType}] {projectInfo?.code || projectInfo?.pspid || '코드정보없음(표준AVL)'} ({projectInfo?.OWN_NM || projectInfo?.kunnrNm || '선주정보 없음'})
          </span>
        </div>

        <div className="justify-end">
          <BackButton>목록으로</BackButton>
        </div>
      </div>

      {/* 툴바 */}
      <div className="flex items-center justify-between gap-4">
        <div className="flex items-center gap-2 flex-1">
          <div className="relative flex-1 max-w-sm">
            <Search className="absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder="전체 검색..."
              value={globalFilter ?? ""}
              onChange={(e) => setGlobalFilter(e.target.value)}
              className="pl-8"
            />
          </div>
          <div className="text-sm text-muted-foreground">
            전체 {data.length}건 중 {rows.length}건 표시
          </div>
        </div>

        <div className="flex items-center gap-2">
          <Button
            onClick={() => handleAction('vendor-pool')}
            variant="outline"
            size="sm"
          >
            Vendor Pool
          </Button>

          <Button
            onClick={() => handleAction('excel-export')}
            variant="outline"
            size="sm"
          >
            <Download className="mr-2 h-4 w-4" />
            Excel Export
          </Button>
        </div>
      </div>

      {/* 테이블 */}
      <div
        ref={tableContainerRef}
        className="relative flex-1 overflow-auto border rounded-md"
      >
        <table
          className="table-fixed border-collapse"
          style={{ width: table.getTotalSize() }}
        >
          {/* GroupHeader를 사용할 때 table-layout: fixed에서 열 너비가 올바르게 적용되도록 colgroup 추가 */}
          <colgroup>
            {table.getLeafHeaders().map((header) => (
              <col key={header.id} style={{ width: header.getSize() }} />
            ))}
          </colgroup>
          <thead className="sticky top-0 z-10 bg-muted">
            {table.getHeaderGroups().map((headerGroup) => (
              <tr key={headerGroup.id}>
                {headerGroup.headers.map((header) => (
                  <th
                    key={header.id}
                    colSpan={header.colSpan}
                    className="border-b px-4 py-2 text-left text-sm font-medium relative group"
                    style={{ width: header.getSize() }}
                  >
                    {header.isPlaceholder ? null : (
                      <>
                        <div
                          className={
                            header.column.getCanSort()
                            ? "flex items-center gap-2 cursor-pointer select-none"
                            : ""
                          }
                          onClick={header.column.getToggleSortingHandler()}
                        >
                          {flexRender(
                            header.column.columnDef.header,
                            header.getContext()
                          )}
                          {header.column.getCanSort() && (
                            <div className="flex flex-col">
                              {header.column.getIsSorted() === "asc" ? (
                                <ChevronUp className="h-4 w-4" />
                              ) : header.column.getIsSorted() === "desc" ? (
                                <ChevronDown className="h-4 w-4" />
                              ) : (
                                <div className="h-4 w-4" />
                              )}
                            </div>
                          )}
                        </div>
                        {header.column.getCanFilter() && (
                          <Filter column={header.column} />
                        )}
                        <div
                          onMouseDown={header.getResizeHandler()}
                          onTouchStart={header.getResizeHandler()}
                          className={`absolute right-0 top-0 h-full w-1 cursor-col-resize select-none touch-none hover:bg-primary/50 ${
                            header.column.getIsResizing() ? 'bg-primary' : 'bg-transparent'
                          }`}
                        />
                      </>
                    )}
                  </th>
                ))}
              </tr>
            ))}
          </thead>
          <tbody>
            {paddingTop > 0 && (
              <tr>
                <td style={{ height: `${paddingTop}px` }} />
              </tr>
            )}
            {virtualRows.map((virtualRow) => {
              const row = rows[virtualRow.index]
              
              return (
                <tr
                  key={row.id}
                  data-index={virtualRow.index}
                  ref={rowVirtualizer.measureElement}
                  data-row-id={row.id}
                  className="hover:bg-muted/50"
                >
                  {row.getVisibleCells().map((cell) => (
                    <td
                      key={cell.id}
                      className="border-b px-4 py-2 text-sm whitespace-normal break-words"
                      style={{ width: cell.column.getSize() }}
                    >
                      {flexRender(
                        cell.column.columnDef.cell,
                        cell.getContext()
                      )}
                    </td>
                  ))}
                </tr>
              )
            })}
            {paddingBottom > 0 && (
              <tr>
                <td style={{ height: `${paddingBottom}px` }} />
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}