package itn.let.fax.addr.web;

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import egovframework.rte.fdl.security.userdetails.util.EgovUserDetailsHelper;
import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
import itn.com.cmm.LoginVO;
import itn.com.utl.fcc.service.EgovStringUtil;
import itn.let.fax.addr.service.FaxAddrTransHistService;
import itn.let.fax.addr.service.FaxAddrTransHistVO;

@Controller
public class FaxAddrTransHistController {

	@Resource (name = "FaxAddrTransHistService")
	private FaxAddrTransHistService faxAddrTransHistService;
	
	
	/**
	 * 주소록 리스트
	 * @param addrVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/mjon/fax/addr/selectFaxAddrTransHistListAjax.do")
	public String selectFaxAddrTransHistListAjax(@ModelAttribute("searchVO") FaxAddrTransHistVO addrTransHistVO
			,ModelMap model) throws Exception {
		
		//로그인 권한정보 불러오기
		LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
		String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
		
		if(userId != "") {
			addrTransHistVO.setSendMberId(userId);
		} 
		
		addrTransHistVO.setPageUnit(5);
		
		/** paging */
		PaginationInfo paginationInfo = new PaginationInfo();
		paginationInfo.setCurrentPageNo(addrTransHistVO.getPageIndex());
		paginationInfo.setRecordCountPerPage(addrTransHistVO.getPageUnit());
		paginationInfo.setPageSize(addrTransHistVO.getPageSize());
		
		addrTransHistVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		addrTransHistVO.setLastIndex(paginationInfo.getLastRecordIndex());
		addrTransHistVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
		
		addrTransHistVO.setSearchSortCnd("sendDate");
		addrTransHistVO.setSearchSortOrd("desc");
		
		
		List<FaxAddrTransHistVO> addrTransHistList = faxAddrTransHistService.selectFaxAddrTransHistList(addrTransHistVO);
		
		int totCnt = 0;
		 if(addrTransHistList.size() > 0) {
 			totCnt = addrTransHistList.get(0).getTotcnt();
 		}
		 
		paginationInfo.setTotalRecordCount(totCnt);
		model.addAttribute("addrTransHistList", addrTransHistList);
		model.addAttribute("paginationInfo", paginationInfo);
		model.addAttribute("totCnt", totCnt);
		
		return "/web/fax/addr/FaxAddrTransHistListAjax";
	}
	
	
	
	
	
	/**
	 * 주소록 리스트 인쇄페이지
	 * @param addrVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/mjon/fax/addr/selectFaxAddrTransHistPrint.do")
	public String selectFaxAddrTransHistPrint(@ModelAttribute("searchVO") FaxAddrTransHistVO addrTransHistVO
			,ModelMap model) throws Exception {
		
		//로그인 권한정보 불러오기
		LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
		String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
		
		if(userId != "") {
			addrTransHistVO.setSendMberId(userId);
		} 
		addrTransHistVO.setRecordCountPerPage(100000);
		addrTransHistVO.setFirstIndex(0);
		
		List<FaxAddrTransHistVO> addrTransHistList = faxAddrTransHistService.selectFaxAddrTransHistList(addrTransHistVO);
		
		model.addAttribute("addrTransHistList", addrTransHistList);
		
		return "/web/fax/addr/FaxAddrTransHistPrint";
	}
	
	
	
	
	
	

	//주소록 엑셀 다운로드 
	@RequestMapping("/web/mjon/fax/addr/faxAddrTransHistExcelDownload.do")
	public void faxAddrTransHistExcelDownload(FaxAddrTransHistVO addrTransHistVO, 
		HttpServletRequest request,
		HttpServletResponse response ,
		ModelMap model) throws Exception {
		
		addrTransHistVO.setRecordCountPerPage(100000);
		addrTransHistVO.setFirstIndex(0);
		LoginVO loginVO = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
	
		// 메모리에 100개의 행을 유지합니다. 행의 수가 넘으면 디스크에 적습니다.
		SXSSFWorkbook wb = new SXSSFWorkbook(100);
		CellStyle style = wb.createCellStyle();
		style.setBorderBottom(CellStyle.BORDER_THIN); //테두리 두껍게 
		style.setBorderLeft(CellStyle.BORDER_THIN);
		style.setBorderRight(CellStyle.BORDER_THIN);
		style.setBorderTop(CellStyle.BORDER_THIN);
		Font font = wb.createFont();
		font.setBoldweight(Font.BOLDWEIGHT_BOLD);  //글씨 bold
		
		Cell cell = null;
		Row row = null;
		
		String fileName ="주소록 내보내기 관리";
		
		String sheetTitle = ""; 
		try{
			if("".equals(addrTransHistVO.getSearchSortCnd())){ //최초조회시 최신것 조회List
				addrTransHistVO.setSearchSortOrd("desc");
			}
			addrTransHistVO.setSendMberId(loginVO.getId());
			List<FaxAddrTransHistVO> addrTransHistList = faxAddrTransHistService.selectFaxAddrTransHistList(addrTransHistVO);
			
			{ 
				// row, cell 개수 순서대로 증가용 필드
				int rowNumber = 0;
				int celNumber = 0;
				//화면 리스트
				sheetTitle = "주소록" ; //제목
				Sheet sheet = wb.createSheet(sheetTitle);
				row = sheet.createRow(rowNumber++);
	
				cell = row.createCell(celNumber++);
				cell.setCellValue("번호");
				cell.setCellStyle(style);

				cell = row.createCell(celNumber++);
				cell.setCellValue("보낸주소록(그룹)명");
				cell.setCellStyle(style);
	
				cell = row.createCell(celNumber++);
				cell.setCellValue("보낸날짜");
				cell.setCellStyle(style);
				
				cell = row.createCell(celNumber++);
				cell.setCellValue("수신날짜");
				cell.setCellStyle(style);
				
				cell = row.createCell(celNumber++);
				cell.setCellValue("수신인ID");
				cell.setCellStyle(style);
				
				cell = row.createCell(celNumber++);
				cell.setCellValue("수신상태");
				cell.setCellStyle(style);
	
	
				for(int i=0; i < addrTransHistList.size(); i++){
					row = sheet.createRow(rowNumber++);		//줄추가
					celNumber = 0;
					cell = row.createCell(celNumber++);
					cell.setCellStyle(style);
					cell.setCellValue(i+1); //번호

					cell = row.createCell(celNumber++);
					cell.setCellStyle(style);
					cell.setCellValue(((FaxAddrTransHistVO)addrTransHistList.get(i)).getAddrGrpNm()); // 보낸주소록 그룹명
					
					cell = row.createCell(celNumber++);
					cell.setCellStyle(style);
					cell.setCellValue(((FaxAddrTransHistVO)addrTransHistList.get(i)).getSendDate()); // 보낸주소록 그룹명
					
					cell = row.createCell(celNumber++);
					cell.setCellStyle(style);
					cell.setCellValue(((FaxAddrTransHistVO)addrTransHistList.get(i)).getRecvDate()); // 수신날짜
					
					cell = row.createCell(celNumber++);
					cell.setCellStyle(style);
					cell.setCellValue(((FaxAddrTransHistVO)addrTransHistList.get(i)).getRecvMberId()); // 수신인
					
					cell = row.createCell(celNumber++);
					cell.setCellStyle(style);
					String recvStatus = "";
					if("Y".equals(((FaxAddrTransHistVO)addrTransHistList.get(i)).getRecvStatus())) {
						recvStatus = "수신완료";
					} else if("W".equals(((FaxAddrTransHistVO)addrTransHistList.get(i)).getRecvStatus())) {
						recvStatus = "수신대기";	
					} else if("N".equals(((FaxAddrTransHistVO)addrTransHistList.get(i)).getRecvStatus())) {
						recvStatus = "수신거부";
					} else {
						recvStatus = "-";
					}
					cell.setCellValue(recvStatus); // 수신상태
				
				}
				
			}
			
			response.setHeader("Set-Cookie", "fileDownload=true; path=/");
			SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat ( "yyyy_MM_dd_HH_mm_ss", Locale.KOREA );
			Date currentTime = new Date ();
			String mTime = mSimpleDateFormat.format ( currentTime );
			fileName = fileName+"("+mTime+")";
			
			response.setHeader("Content-Disposition", String.format("attachment; filename=\""+new String((fileName).getBytes("KSC5601"),"8859_1")+".xlsx"));
			wb.write(response.getOutputStream());

		}catch(Exception e) {
			response.setHeader("Set-Cookie", "fileDownload=false; path=/");
			response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
			response.setHeader("Content-Type","text/html; charset=utf-8");
			OutputStream out = null;
			try {
				out = response.getOutputStream();
				byte[] data = new String("fail..").getBytes();
				out.write(data, 0, data.length);
			} catch(Exception ignore) {
				ignore.printStackTrace();
			} finally {
				if(out != null) try { out.close(); } catch(Exception ignore) {}
			}
		}finally {
			// 디스크 적었던 임시파일을 제거합니다.
			wb.dispose();
			try { wb.close(); } catch(Exception ignore) {}
		}
	}
	
}
