summaryrefslogtreecommitdiff
path: root/lib/items-tech/table/top/offshore-top-table-toolbar-actions.tsx
blob: f91adf964d6917df74f6f25553b4ea6867f1e419 (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
"use client"

import * as React from "react"
import { type Table } from "@tanstack/react-table"
import { Download, FileDown } from "lucide-react"
import * as ExcelJS from 'exceljs'
import { saveAs } from "file-saver"

import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"

import { DeleteItemsDialog } from "../delete-items-dialog"
import { AddItemDialog } from "../add-items-dialog"
import { exportTopItemTemplate } from "./item-excel-template"
import { ImportItemButton } from "../import-excel-button"

// 해양 TOP 아이템 타입 정의
interface OffshoreTopItem {
  id: number;
  itemId: number;
  workType: "TM" | "TS" | "TE" | "TP";
  itemList: string | null;
  subItemList: string | null;
  itemCode: string;
  itemName: string;
  description: string | null;
  createdAt: Date;
  updatedAt: Date;
}

interface OffshoreTopTableToolbarActionsProps {
  table: Table<OffshoreTopItem>
}

export function OffshoreTopTableToolbarActions({ table }: OffshoreTopTableToolbarActionsProps) {
  const [refreshKey, setRefreshKey] = React.useState(0)

  // 가져오기 성공 후 테이블 갱신
  const handleImportSuccess = () => {
    setRefreshKey(prev => prev + 1)
  }

  // Excel 내보내기 함수
  const exportTableToExcel = async (
    table: Table<OffshoreTopItem>,
    options: {
      filename: string;
      excludeColumns?: string[];
      sheetName?: string;
    }
  ) => {
    const { filename, excludeColumns = [], sheetName = "해양 TOP 아이템 목록" } = options;
    
    // 워크북 생성
    const workbook = new ExcelJS.Workbook();
    workbook.creator = 'Offshore Item Management System';
    workbook.created = new Date();
    
    // 워크시트 생성
    const worksheet = workbook.addWorksheet(sheetName);
    
    // 테이블 데이터 가져오기
    const data = table.getFilteredRowModel().rows.map(row => row.original);
    console.log("내보내기 데이터:", data);
    
    // 필요한 헤더 직접 정의 (필터링 문제 해결)
    const headers = [
      { key: 'itemCode', header: '아이템 코드' },
      { key: 'itemName', header: '아이템 명' },
      { key: 'description', header: '설명' },
      { key: 'workType', header: '기능(공종)' },
      { key: 'itemList', header: '아이템 리스트' },
      { key: 'subItemList', header: '서브 아이템 리스트' },
    ].filter(header => !excludeColumns.includes(header.key));
    
    console.log("내보내기 헤더:", headers);
    // 컬럼 정의
    worksheet.columns = headers.map(header => ({
      header: header.header,
      key: header.key,
      width: 20 // 기본 너비
    }));
    
    // 스타일 적용
    const headerRow = worksheet.getRow(1);
    headerRow.font = { bold: true };
    headerRow.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFE0E0E0' }
    };
    headerRow.alignment = { vertical: 'middle', horizontal: 'center' };
    
    // 데이터 행 추가
    data.forEach(item => {
      const row: Record<string, any> = {};
      headers.forEach(header => {
        row[header.key] = item[header.key as keyof OffshoreTopItem];
      });
      worksheet.addRow(row);
    });
    
    // 전체 셀에 테두리 추가
    worksheet.eachRow((row) => {
      row.eachCell((cell) => {
        cell.border = {
          top: { style: 'thin' },
          left: { style: 'thin' },
          bottom: { style: 'thin' },
          right: { style: 'thin' }
        };
      });
    });
    
    try {
      // 워크북을 Blob으로 변환
      const buffer = await workbook.xlsx.writeBuffer();
      const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      saveAs(blob, `${filename}.xlsx`);
      return true;
    } catch (error) {
      console.error("Excel 내보내기 오류:", error);
      return false;
    }
  }

  return (
    <div className="flex items-center gap-2">
      {/* 선택된 로우가 있으면 삭제 다이얼로그 */}
      {table.getFilteredSelectedRowModel().rows.length > 0 ? (
        <DeleteItemsDialog
          items={table
            .getFilteredSelectedRowModel()
            .rows.map((row) => row.original)}
          onSuccess={() => table.toggleAllRowsSelected(false)}
          itemType="offshoreTop"
        />
      ) : null}

      {/* 새 아이템 추가 다이얼로그 */}
      <AddItemDialog itemType="offshoreTop" />

      {/* Import 버튼 */}
      <ImportItemButton itemType="top" onSuccess={handleImportSuccess} />

      {/* Export 드롭다운 메뉴 */}
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="outline" size="sm" className="gap-2">
            <Download className="size-4" aria-hidden="true" />
            <span className="hidden sm:inline">Export</span>
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end">
          <DropdownMenuItem
            onClick={() =>
              exportTableToExcel(table, {
                filename: "offshore_top_items",
                excludeColumns: ["select", "actions"],
                sheetName: "해양 TOP 아이템 목록"
              })
            }
          >
            <FileDown className="mr-2 h-4 w-4" />
            <span>현재 데이터 내보내기</span>
          </DropdownMenuItem>
          <DropdownMenuItem onClick={() => exportTopItemTemplate()}>
            <FileDown className="mr-2 h-4 w-4" />
            <span>템플릿 다운로드</span>
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  )
}