package com.dbnt.faisp.equip;


import com.dbnt.faisp.authMgt.service.AuthMgtService;
import com.dbnt.faisp.equip.model.Equip;
import com.dbnt.faisp.equip.model.EquipLog;
import com.dbnt.faisp.equip.service.EquipService;
import com.dbnt.faisp.userInfo.model.UserInfo;
import com.dbnt.faisp.util.ParamMap;
import com.dbnt.faisp.util.Utils;

import lombok.RequiredArgsConstructor;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;


@RestController
@RequiredArgsConstructor
@RequestMapping("/equip")
public class EquipController {

  private final EquipService equipService;
  private final AuthMgtService authMgtService;
  
  @GetMapping("/equipStatus")
  public ModelAndView equipStatus(@AuthenticationPrincipal UserInfo loginUser, Equip equip) {
    ModelAndView mav = new ModelAndView("equip/equipStatus");
    
    //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/equip/equipStatus").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);
    mav.addObject("equipList", equipService.selectEquipStatus(equip));  
    return mav;
  }
  
  @GetMapping("/equipEditModal")
  public ModelAndView equipEditModal(@AuthenticationPrincipal UserInfo loginUser) {
    ModelAndView mav = new ModelAndView("equip/equipEditModal");
  //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/equip/equipStatus").get(0).getAccessAuth();
    mav.addObject("mgtOrganList", loginUser.getDownOrganCdList());
    mav.addObject("userOrgan", loginUser.getOgCd());
    mav.addObject("accessAuth", accessAuth);
    
    return mav;
  }
  
  
  @GetMapping("/equipTypeSelecBox")
  public ModelAndView equipTypeSelecBox(String equType) {
    ModelAndView mav = new ModelAndView("equip/equipTypeSelecBox");
    mav.addObject("equType", equType);
    return mav;
  }
  
  @PostMapping("/saveEquip")
  public void saveEquip(@AuthenticationPrincipal UserInfo loginUser,Equip equip, MultipartHttpServletRequest request){
	  equip.setWrtNm(loginUser.getUserId());
	  equip.setWrtOrgan(loginUser.getOgCd());
	  equip.setWrtDt(LocalDateTime.now());
	  equipService.saveEquip(equip,request);
  }
  
  @GetMapping("/List")
  public ModelAndView equipList(@AuthenticationPrincipal UserInfo loginUser,Equip equip) {
    ModelAndView mav = new ModelAndView("equip/equipList");
    
    //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/equip/equipStatus").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);
    equip.setDownOrganCdList(loginUser.getDownOrganCdList());
    ParamMap equType =  equipService.selectEduType(equip);
    mav.addObject("equType", equType.get("equ_type"));
    mav.addObject("detailType", equType.get("detail_type"));
    equip.setQueryInfo();
    mav.addObject("equipList", equipService.selectEquipList(equip));
    equip.setContentCnt(equipService.selectEquipListCnt(equip));
    equip.setPaginationInfo();
    mav.addObject("searchParams", equip);
    
    return mav;
  }
  
  @GetMapping("/updatePage")
  public ModelAndView equipUpdatePage(@AuthenticationPrincipal UserInfo loginUser, Equip equip) {
    ModelAndView mav = new ModelAndView("equip/equipModifyModal");
    //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/equip/equipStatus").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);
    mav.addObject("userId", loginUser.getUserId());
    mav.addObject("wrtId", equipService.selectEquipFirstId(equip));
    mav.addObject("equInfo", equipService.selectEquipInfo(equip));
    return mav;
  }
  
  @PostMapping("/updateEquip")
  @ResponseBody
  public int updateEquip(@AuthenticationPrincipal UserInfo loginUser,Equip equip, MultipartHttpServletRequest request){
	  equip.setWrtNm(loginUser.getUserId());
	  equip.setWrtOrgan(loginUser.getOgCd());
	  equip.setWrtDt(LocalDateTime.now());
	  int result = equipService.updateEquip(equip,request);
	  return result;
  }
  
  @GetMapping("/historyView")
  public ModelAndView historyView(Equip equip) {
    ModelAndView mav = new ModelAndView("equip/equipHistory");
    mav.addObject("equList", equipService.selectHistoryView(equip));
    return mav;
  }
  
  @GetMapping("/HistoryDetail")
  @ResponseBody
  public Equip HistoryDetail(Equip equip){
    return equipService.selectHistoryDetail(equip);
  }
  
  @PostMapping("/epuipDelete")
  public void epuipDelete(@AuthenticationPrincipal UserInfo loginUser, @RequestBody List<Equip> equip){
	  equipService.equipDelete(equip,loginUser);

  }
  
  @GetMapping("/getEquipImg")
  public void getThumbImage(Equip equip , HttpServletResponse response) throws Exception {
		
	    Equip dbImg = equipService.selectEquipInfo(equip);
		
		String realFile = dbImg.getFilePath()+"/"+ dbImg.getConvNm();
		String fileNm = dbImg.getConvNm();
		
		
		BufferedOutputStream out = null;
		InputStream in = null;
	
		try {
			response.setContentType("image/jpeg;charset=UTF-8");
			response.setHeader("Content-Disposition", "inline;filename=" + fileNm);
			File file = new File(realFile);
//			File file = new File(realFile + "/" + fileNm);
			if(file.exists()){
				in = new FileInputStream(file);
				out = new BufferedOutputStream(response.getOutputStream());
				int len;
				byte[] buf = new byte[1024];
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
			}
		} catch (Exception e) {

		} finally {
			if(out != null){ out.flush(); }
			if(out != null){ out.close(); }
			if(in != null){ in.close(); }
		}
	}
  
  @GetMapping("/Log")
  public ModelAndView equipLog(@AuthenticationPrincipal UserInfo loginUser,EquipLog equipLog) {
    ModelAndView mav = new ModelAndView("equip/equipLogList");
    equipLog.setDownOrganCdList(loginUser.getDownOrganCdList());
    equipLog.setQueryInfo();
    mav.addObject("logList", equipService.selectEquipLogList(equipLog));
    equipLog.setContentCnt(equipService.selectEquipLogListCnt(equipLog));
    equipLog.setPaginationInfo();
    mav.addObject("searchParams", equipLog);
    
    return mav;
  }
  
  @GetMapping("/statusExcelDown")
  public void statisticsExcelDown(Model model,HttpServletResponse response, Equip equip) {
	    String[] headers = { "rownum","equ_type", "item_value", "total", "cnt_bon", "cnt_center", "cnt_incheon", "cnt_pyeongtaek", "cnt_taean","cnt_boryeong","cnt_west","cnt_mokpo","cnt_buan",
	    					 "cnt_gunsan","cnt_yusu","cnt_wando","cnt_south","cnt_ulsan","cnt_busan","cnt_changwon","cnt_tongyong","cnt_sacheon","cnt_east","cnt_sokcho","cnt_donghe",
	    					 "cnt_ulgin","cnt_pohang","cnt_jeju","cnt_jejuseo","cnt_seoguipo"};
		String[] headerNames = { "", "", "", "", "", "중부", "", "","","","서해","","","","","","남해","","","","","","동해","","","","","제주","",""};
		String[] headerNames2 = { "연번", "분류", "세부분류", "총계", "본청", "청", "인천서", "평택서","태안서","보령서","청","목포서","부안서","군산서","여수서","완도서","청","울산서","부산서","창원서","통영서","서천서","청","속초서","동해서","울진서","포항서","청","제주서","서귀포서"};
		String[] columnType = { "int", "String", "String", "int", "int", "int", "int", "int","int","int","int","int","int","int","int","int","int","int","int","int",
				                "int","int","int","int","int","int","int","int","int","int"};
		String sheetName = "외사장비현황";
		String excelFileName = "외사장비현황";
		List<ParamMap> equStatusList =  equipService.selectEquipStatus(equip);

		try { 
			Utils.downEquipStatusExcel(equStatusList, response, headers, headerNames,headerNames2, columnType, sheetName, excelFileName);
		} catch (IOException e) {
			model.addAttribute("message", "엑셀다운로드 중 오류가 발생했습니다.");
		}
  }
  
 
  
  
  

}
