summaryrefslogtreecommitdiff
path: root/components/form-data/var-list-download-btn.tsx
blob: 9d09ab8ca3e6bfc76998aa8b05c4bd2d06c2978b (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
"use client";

import React, { FC } from "react";
import Image from "next/image";
import { useToast } from "@/hooks/use-toast";
import { toast as toastMessage } from "sonner";
import ExcelJS from "exceljs";
import { saveAs } from "file-saver";
import { Button } from "@/components/ui/button";
import { DataTableColumnJSON } from "./form-data-table-columns";
import { useParams } from "next/navigation";
import { useTranslation } from "@/i18n/client";

interface VarListDownloadBtnProps {
  columnsJSON: DataTableColumnJSON[];
  formCode: string;
}

export const VarListDownloadBtn: FC<VarListDownloadBtnProps> = ({
  columnsJSON,
  formCode,
}) => {
  const { toast } = useToast();
  
  const params = useParams();
  const lng = (params?.lng as string) || "ko";
  const { t } = useTranslation(lng, "engineering");

  const downloadReportVarList = async () => {
    try {
      // Create a new workbook
      const workbook = new ExcelJS.Workbook();

      // 데이터 시트 생성
      const worksheet = workbook.addWorksheet("Data");

      // 유효성 검사용 숨김 시트 생성
      const validationSheet = workbook.addWorksheet("ValidationData");
      validationSheet.state = "hidden"; // 시트 숨김 처리

      // 1. 데이터 시트에 헤더 추가
      const headers = [
        t("varListDownload.headers.tableColumnLabel"),
        t("varListDownload.headers.reportVariable")
      ];
      worksheet.addRow(headers);

      // 헤더 스타일 적용
      const headerRow = worksheet.getRow(1);
      headerRow.font = { bold: true };
      headerRow.alignment = { horizontal: "center" };
      headerRow.eachCell((cell) => {
        cell.fill = {
          type: "pattern",
          pattern: "solid",
          fgColor: { argb: "FFCCCCCC" },
        };
      });

      // 2. 데이터 행 추가
      columnsJSON.forEach((row) => {
        console.log(row);
        const { displayLabel, key } = row;

        // const labelConvert = label.replaceAll(" ", "_");

        worksheet.addRow([displayLabel, key]);
      });

      // 3. 컬럼 너비 자동 조정
      headers.forEach((col, idx) => {
        const column = worksheet.getColumn(idx + 1);

        // 최적 너비 계산
        let maxLength = col.length;
        columnsJSON.forEach((row) => {
          const valueKey = idx === 0 ? "displayLabel" : "label";

          const value = row[valueKey];
          if (value !== undefined && value !== null) {
            const valueLength = String(value).length;
            if (valueLength > maxLength) {
              maxLength = valueLength;
            }
          }
        });

        // 너비 설정 (최소 10, 최대 50)
        column.width = Math.min(Math.max(maxLength + 2, 10), 50);
      });

      const buffer = await workbook.xlsx.writeBuffer();
      const fileName = `${formCode}${t("varListDownload.fileNameSuffix")}`;
      saveAs(new Blob([buffer]), fileName);
      toastMessage.success(t("varListDownload.messages.downloadComplete"));
    } catch (err) {
      console.log(err);
      toast({
        title: t("varListDownload.messages.errorTitle"),
        description: t("varListDownload.messages.errorDescription"),
        variant: "destructive",
      });
    }
  };

  return (
    <Button
      variant="outline"
      className="relative px-[8px] py-[6px] flex-1"
      aria-label={t("varListDownload.buttonAriaLabel")}
      onClick={downloadReportVarList}
    >
      <Image
        src="/icons/var_list_icon.svg"
        alt={t("varListDownload.iconAltText")}
        width={16}
        height={16}
      />
      <div className="text-[12px]">{t("varListDownload.buttonText")}</div>
    </Button>
  );
};