package com.madeu.view.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.servlet.view.AbstractView;

import com.madeu.util.ConvertStringUtil;

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

@Slf4j
public class WebReserveColumnView 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");
		Map<String, Object> maps = (Map<String, Object>) map.get("selectListReserveColumn");
		List<Map<String, Object>> channelList            = (List<Map<String, Object>>)maps.get("channelRows");
		List<Map<String, Object>> nationalityList        = (List<Map<String, Object>>)maps.get("nationalityRows");
		List<Map<String, Object>> treatmentProcedureList = (List<Map<String, Object>>)maps.get("treatmentProcedureRows");
		List<Map<String, Object>> memberList             = (List<Map<String, Object>>)maps.get("memberRows");
		
		int rowCount = 0;   // row
		int colCount = 0;   // col

		//1차로 workbook을 생성
		XSSFWorkbook workbook = new XSSFWorkbook();
		
		setContentType(CONTENT_TYPE_XLSX);
		
		//2차는 sheet생성
		
	
		// sheet 1 생성
		Sheet sheet = workbook.createSheet("예약경로");
		
		// sheet 2 생성
		Sheet sheet2 = workbook.createSheet("국가");
		
		// sheet 3 생성
		Sheet sheet3 = workbook.createSheet("진료유형");
		
		// sheet 4 생성
		Sheet sheet4 = workbook.createSheet("닥터상담");
		
		
		XSSFCellStyle headerStyle = workbook.createCellStyle();
		headerStyle.setAlignment(HorizontalAlignment.CENTER);
		headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		
		// cell 스타일 (참고값 표시)
		XSSFCellStyle headerStyle2 = workbook.createCellStyle();
		headerStyle2.setAlignment(HorizontalAlignment.CENTER);
		headerStyle2.setVerticalAlignment(VerticalAlignment.CENTER);
		headerStyle2.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); // 배경색
		headerStyle2.setFillPattern(FillPatternType.SOLID_FOREGROUND);	//채우기 적용

		// cell 스타일 (기본값)
		CellStyle cellStyle = workbook.createCellStyle();
		cellStyle.setWrapText( true );
		cellStyle.setAlignment(HorizontalAlignment.LEFT);
		
		// cell 스타일 (참고값 표시)
		CellStyle cellStyle2 = workbook.createCellStyle();
		cellStyle2.setWrapText( true );
		cellStyle2.setAlignment(HorizontalAlignment.LEFT);
		cellStyle2.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); // 배경색
		cellStyle2.setFillPattern(FillPatternType.SOLID_FOREGROUND);	//채우기 적용
		
		// sheet 1 처리 시작
		Row header = sheet.createRow(rowCount++);
		
//		sheet.addMergedRegion(new CellRangeAddress(0,1,0,0));
		createHeaderCell(0, header, headerStyle, "번호");
//		sheet.addMergedRegion(new CellRangeAddress(0,1,1,1));
		createHeaderCell(1, header, headerStyle2, "예약경로 코드");
//		sheet.addMergedRegion(new CellRangeAddress(0,1,2,2));
		createHeaderCell(2, header, headerStyle, "예약경로명");
		
		// 엑셀에 데이터 입력
		for(Map<String, Object> e:channelList){
			Row row = sheet.createRow(rowCount++);
			row.setHeight((short)350);
			
			String rowNumber        = ConvertStringUtil.ifNullToString(rowCount-1);
			String categoryItemCode = ConvertStringUtil.ifNullToString(e.get("categoryItemCode"));
			String categoryItemName = ConvertStringUtil.ifNullToString(e.get("categoryItemName"));
			
			createCell(0, row, cellStyle, rowNumber);
			createCell(1, row, cellStyle2, categoryItemCode);
			createCell(2, row, cellStyle, categoryItemName);
			
		}
		
		sheet.setColumnWidth(1, 4000);
		sheet.setColumnWidth(2, 6000);
		
		// sheet 1 처리 종료
		
		
		
		// sheet 2 처리 시작
		rowCount = 0;
		Row header2 = sheet2.createRow(rowCount++);
		
//		sheet.addMergedRegion(new CellRangeAddress(0,1,0,0));
		createHeaderCell(0, header2, headerStyle, "번호");
//		sheet.addMergedRegion(new CellRangeAddress(0,1,1,1));
		createHeaderCell(1, header2, headerStyle2, "국가 코드");
//		sheet.addMergedRegion(new CellRangeAddress(0,1,2,2));
		createHeaderCell(2, header2, headerStyle, "국가명");
		
		// 엑셀에 데이터 입력
		for(Map<String, Object> e:nationalityList){
			Row row = sheet2.createRow(rowCount++);
			row.setHeight((short)350);
			
			String rowNumber        = ConvertStringUtil.ifNullToString(rowCount-1);
			String categoryItemCode = ConvertStringUtil.ifNullToString(e.get("categoryItemCode"));
			String categoryItemName = ConvertStringUtil.ifNullToString(e.get("categoryItemName"));
			
			createCell(0, row, cellStyle, rowNumber);
			createCell(1, row, cellStyle2, categoryItemCode);
			createCell(2, row, cellStyle, categoryItemName);
			
		}
		
		sheet2.setColumnWidth(1, 4000);
		sheet2.setColumnWidth(2, 8000);
		
		// sheet 2 처리 종료
		
		
		
		// sheet 3 처리 시작
		rowCount = 0;
		Row header3 = sheet3.createRow(rowCount++);
		
//		sheet.addMergedRegion(new CellRangeAddress(0,1,0,0));
		createHeaderCell(0, header3, headerStyle, "번호");
//		sheet.addMergedRegion(new CellRangeAddress(0,1,1,1));
		createHeaderCell(1, header3, headerStyle, "진료명");
//		sheet.addMergedRegion(new CellRangeAddress(0,1,2,2));
		createHeaderCell(2, header3, headerStyle2, "진료 유형(시술) 식별자");
//		sheet.addMergedRegion(new CellRangeAddress(0,1,3,3));
		createHeaderCell(3, header3, headerStyle, "진료 유형(시술)명");
		
		// 엑셀에 데이터 입력
		for(Map<String, Object> e:treatmentProcedureList){
			Row row = sheet3.createRow(rowCount++);
			row.setHeight((short)350);
			
			String rowNumber              = ConvertStringUtil.ifNullToString(rowCount-1);
			String treatmentName          = ConvertStringUtil.ifNullToString(e.get("treatmentName"));
			String muTreatmentProcedureId = ConvertStringUtil.ifNullToString(e.get("muTreatmentProcedureId"));
			String treatmentProcedureName = ConvertStringUtil.ifNullToString(e.get("treatmentProcedureName"));
			
			createCell(0, row, cellStyle, rowNumber);
			createCell(1, row, cellStyle, treatmentName);
			createCell(2, row, cellStyle2, muTreatmentProcedureId);
			createCell(3, row, cellStyle, treatmentProcedureName);
		}
		
		sheet3.setColumnWidth(1, 4000);
		sheet3.setColumnWidth(2, 8000);
		sheet3.setColumnWidth(3, 10000);
		
		// sheet 3 처리 종료
		
		
		
		// sheet 4 처리 시작
		rowCount = 0;
		Row header4 = sheet4.createRow(rowCount++);
		
//		sheet.addMergedRegion(new CellRangeAddress(0,1,0,0));
		createHeaderCell(0, header4, headerStyle, "번호");
//		sheet.addMergedRegion(new CellRangeAddress(0,1,1,1));
		createHeaderCell(1, header4, headerStyle2, "사번 코드");
//		sheet.addMergedRegion(new CellRangeAddress(0,1,2,2));
		createHeaderCell(2, header4, headerStyle, "닥터/상담");
//		sheet.addMergedRegion(new CellRangeAddress(0,1,3,3));
		createHeaderCell(3, header4, headerStyle, "직원명");
		
		// 엑셀에 데이터 입력
		for(Map<String, Object> e:memberList){
			Row row = sheet4.createRow(rowCount++);
			row.setHeight((short)350);
			
			String rowNumber  = ConvertStringUtil.ifNullToString(rowCount-1);
			String memberCode = ConvertStringUtil.ifNullToString(e.get("memberCode"));
			String typeName   = ConvertStringUtil.ifNullToString(e.get("typeName"));
			String memberName = ConvertStringUtil.ifNullToString(e.get("memberName"));
			
			createCell(0, row, cellStyle, rowNumber);
			createCell(1, row, cellStyle2, memberCode);
			createCell(2, row, cellStyle, typeName);
			createCell(3, row, cellStyle, memberName);
		}
		
		sheet4.setColumnWidth(1, 4000);
		sheet4.setColumnWidth(2, 4000);
		sheet4.setColumnWidth(3, 4000);
		
		// sheet 4 처리 종료
		

		
		//response.setContentType("Application/Msexcel");
		response.setContentType(getContentType());
		Date toDay = new Date();        
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String nowDateTime = dateFormat.format(toDay);
		log.debug("1. 현재날짜                                : "+ nowDateTime);
		response.setHeader("Content-Disposition", "ATTachment; Filename=".concat(new String(filename.getBytes("euc-kr"),"8859_1")).concat("_").concat(nowDateTime).concat(".xlsx"));
		
		ServletOutputStream out = response.getOutputStream();
		out.flush();
		workbook.write(out);
		out.flush();
		
	}
	
	private void createHeaderCell(int col, Row row, CellStyle cellStyle, String value){
		Cell cell = row.createCell(col);
		cellStyle.setWrapText(true);
		cell.setCellStyle(cellStyle);
		cell.setCellValue(value);
	}
	private void createCell(int col, Row row, CellStyle cellStyle, String value){
		Cell cell = row.createCell(col);
		cellStyle.setWrapText(true);
		cell.setCellStyle(cellStyle);
		cell.setCellValue(value);
	}
}