package com.madeu.view.web;

import java.io.File;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.madeu.util.ConvertStringUtil;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.servlet.view.AbstractView;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WebVacationManagementInsertView extends AbstractView {

    private static final String CONTENT_TYPE_XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        // 출력 데이터
        Map<String, Object> map = (Map<String, Object>) model.get("map");
        String filename = (String) map.get("name");
        List<Map<String, Object>> additionalList = (List<Map<String, Object>>) map.get("additionalList");
        File file = (File) map.get("file");

        try {
            XSSFWorkbook workbook = new XSSFWorkbook(file);
            Sheet sheet = workbook.getSheet("직원 정보");
            if (sheet != null) {
                workbook.removeSheetAt(workbook.getSheetIndex(sheet));
            }
            sheet = workbook.createSheet("직원 정보");
            XSSFCellStyle headerStyle = workbook.createCellStyle();
            headerStyle.setAlignment(HorizontalAlignment.CENTER);
            headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            // 헤더 생성
            int rowCount = 0;
            Row header = sheet.createRow(rowCount++);

            createHeaderCell(0, header, headerStyle, "번호");
            createHeaderCell(1, header, headerStyle, "직원명");
            createHeaderCell(2, header, headerStyle, "아이디");

            for (Map<String, Object> e : additionalList) {
                Row row = sheet.createRow(rowCount++);
                row.setHeight((short) 350);
                row.createCell(0).setCellValue(ConvertStringUtil.ifNullToString(rowCount-1));
                row.createCell(1).setCellValue(ConvertStringUtil.ifNullToString(e.get("memberName")));
                row.createCell(2).setCellValue(ConvertStringUtil.ifNullToString(e.get("loginId")));
            }
            response.setContentType(CONTENT_TYPE_XLSX);
            Date toDay = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String nowDateTime = dateFormat.format(toDay);
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));

            try (ServletOutputStream out = response.getOutputStream()) {
                    workbook.write(out);
                    out.flush();
            }

        } catch (Exception e) {
            log.error("Error occurred while generating Excel file", e);
            throw e;
        }

        log.debug("WebReserveController downloadVacationManagementInsertExcel END");
    }

    private void createHeaderCell(int col, Row row, CellStyle cellStyle, String value) {
        Cell cell = row.createCell(col);
        cell.setCellStyle(cellStyle);
        cell.setCellValue(value);
    }
}
