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.BorderStyle;
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 WebAttendanceView 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("selectListAttendance");
		List<Map<String, Object>> dateList   = (List<Map<String, Object>>)maps.get("dateRows");
		List<Map<String, Object>> memberList = (List<Map<String, Object>>)maps.get("memberRows");
		List<Map<String, Object>> attendList = (List<Map<String, Object>>)maps.get("rows");
		
		int rowCount = 0;   // row
		int colCount = 0;   // col

		//1차로 workbook을 생성
		XSSFWorkbook workbook = new XSSFWorkbook();
		
		setContentType(CONTENT_TYPE_XLSX);
		
		//2차는 sheet생성
		Sheet sheet = workbook.createSheet("근태관리 정보");
		XSSFCellStyle headerStyle = workbook.createCellStyle();
		headerStyle.setAlignment(HorizontalAlignment.CENTER);
		headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		/*headerStyle.setBorderRight(BorderStyle.THIN);
		headerStyle.setBorderLeft(BorderStyle.THIN);
		headerStyle.setBorderTop(BorderStyle.THIN);
		headerStyle.setBorderBottom(BorderStyle.THIN);*/
		
		// cell 스타일1 (가로 왼쪽, 세로 가운데 정렬)
		CellStyle cellStyle = workbook.createCellStyle();
		cellStyle.setWrapText( true );
		cellStyle.setAlignment(HorizontalAlignment.LEFT);
		cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		/*cellStyle.setBorderRight(BorderStyle.THIN);
		cellStyle.setBorderLeft(BorderStyle.THIN);
		cellStyle.setBorderTop(BorderStyle.THIN);
		cellStyle.setBorderBottom(BorderStyle.THIN);*/
		
		// cell 스타일2 (가로 왼쪽, 세로 가운데 정렬, 배경색)
		CellStyle cellStyle2 = workbook.createCellStyle();
		cellStyle2.setWrapText( true );
		cellStyle2.setAlignment(HorizontalAlignment.LEFT);
		cellStyle2.setVerticalAlignment(VerticalAlignment.CENTER);
		cellStyle2.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); // 배경색
		cellStyle2.setFillPattern(FillPatternType.SOLID_FOREGROUND);	//채우기 적용
		/*cellStyle2.setBorderRight(BorderStyle.THIN);
		cellStyle2.setBorderLeft(BorderStyle.THIN);
		cellStyle2.setBorderTop(BorderStyle.THIN);
		cellStyle2.setBorderBottom(BorderStyle.THIN);*/
		
		// cell 스타일3 (가로 세로 가운데 정렬, 배경색)
		CellStyle cellStyle3 = workbook.createCellStyle();
		cellStyle3.setWrapText( true );
		cellStyle3.setAlignment(HorizontalAlignment.CENTER);
		cellStyle3.setVerticalAlignment(VerticalAlignment.CENTER);
		cellStyle3.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex()); // 배경색
		cellStyle3.setFillPattern(FillPatternType.SOLID_FOREGROUND);	//채우기 적용
		/*cellStyle3.setBorderRight(BorderStyle.THIN);
		cellStyle3.setBorderLeft(BorderStyle.THIN);
		cellStyle3.setBorderTop(BorderStyle.THIN);
		cellStyle3.setBorderBottom(BorderStyle.THIN);*/
		
		
		Row header = sheet.createRow(rowCount++);
			

		sheet.setColumnWidth(colCount, 4000);
		createHeaderCell(colCount++, header, headerStyle, "직원");
		
		int dateListSize = dateList.size();
		
		for (int i = 0; i < dateListSize; i++) {
			String day        = String.valueOf(dateList.get(i).get("day"));
			String dayOfWeek  = String.valueOf(dateList.get(i).get("dayOfWeek"));
			
			sheet.setColumnWidth(colCount, 4000);
			createHeaderCell(colCount++, header, headerStyle, day+"/"+dayOfWeek);

		}
		
		// 엑셀에 데이터 입력
		for(Map<String, Object> e:memberList){
			Row row = sheet.createRow(rowCount++);
			row.setHeight((short)1000);

			String muMemberId = ConvertStringUtil.ifNullToString(e.get("muMemberId"));
			String memberName = ConvertStringUtil.ifNullToString(e.get("memberName"));
			String loginId    = ConvertStringUtil.ifNullToString(e.get("loginId"));
			String groupName  = ConvertStringUtil.ifNullToString(e.get("groupName"));
			String dutyName   = ConvertStringUtil.ifNullToString(e.get("dutyName"));
			

			createCell(0, row, cellStyle, groupName+" "+dutyName+"\r\n"+memberName+" ("+loginId+")");
			
			int subCellCount = 1;
			for(Map<String, Object> z:attendList){
				String memberId = ConvertStringUtil.ifNullToString(z.get("muMemberId"));
				List<Map<String, Object>> attendanceListMap = (List<Map<String, Object>>)z.get("attendanceListMap");
				
				if(muMemberId==memberId){
					if(attendanceListMap==null){
						// 근태 정보 없을 경우
						createCell(subCellCount++, row, cellStyle, "");
					}
					else {
						
						// 근태 정보 있을 경우
						String subAttendanceType  = ConvertStringUtil.ifNullToString(attendanceListMap.get(0).get("attendanceType"));
						String subStartTime       = ConvertStringUtil.ifNullToString(attendanceListMap.get(0).get("startTime"));
						String subEndTime         = ConvertStringUtil.ifNullToString(attendanceListMap.get(0).get("endTime"));
						String subTotalWorkHour   = ConvertStringUtil.ifNullToString(attendanceListMap.get(0).get("totalWorkHour"));
						
						if(("A").equals(subAttendanceType)){
							// 출/퇴근
							createCell(subCellCount++, row, cellStyle2, "출근 : "+subStartTime+"\r\n"+"퇴근 : "+subEndTime+"\r\n"+"근무 : "+subTotalWorkHour);
							
						}
						else if(("C").equals(subAttendanceType)){
							// 휴무
							createCell(subCellCount++, row, cellStyle3, "휴무");
						}
						else if(("D").equals(subAttendanceType)){
							// 연차
							createCell(subCellCount++, row, cellStyle3, "연차");
						}
						else if(("E").equals(subAttendanceType)){
							String title = "";
							
							// 반차
							if(null==subStartTime||("").equals(subStartTime)) {
								title = "반차";
							}
							else {
								String [] startTimeArr = subStartTime.split(":");
								int startHour = Integer.parseInt(startTimeArr[0]);
								
								title = "반차(오후)";
								
								if(startHour<12){
									title = "반차(오전)";
								}
							}
							
							createCell(subCellCount++, row, cellStyle3, title);
						}
					}
				}
			}
		}

		
		//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);
	}
}