package com.dbnt.sims.equip;


import com.dbnt.sims.authMgt.service.AuthMgtService;
import com.dbnt.sims.equip.model.CellPhone;
import com.dbnt.sims.equip.model.Equip;
import com.dbnt.sims.equip.model.EquipLog;
import com.dbnt.sims.equip.model.UseList;
import com.dbnt.sims.equip.service.EquipService;
import com.dbnt.sims.organMgt.service.OrganConfigService;
import com.dbnt.sims.userInfo.model.UserInfo;
import com.dbnt.sims.userInfo.service.UserInfoService;
import com.dbnt.sims.util.ParamMap;
import com.dbnt.sims.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;
  private final OrganConfigService organConfigService;
  private final UserInfoService userInfoService;
  
  @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", "엑셀다운로드 중 오류가 발생했습니다.");
		}
  }
  
  @GetMapping("/cellPhoneList")
  public ModelAndView cellPhoneList(@AuthenticationPrincipal UserInfo loginUser,CellPhone cellPhone,HttpServletResponse response) {
    ModelAndView mav = new ModelAndView("equip/cellPhoneList");
    cellPhone.setDownOrganCdList(loginUser.getDownOrganCdList());
  //엑셀다운
    if(cellPhone.getExcel() != null && cellPhone.getExcel().equals("Y")){
    	String[] headers = { "phone_key", "sosok", "tel_no", "user_nm", "ext_mail", "webex_no", "katalk_id"};
		String[] headerNames = { "연번", "소속","전화번호", "사용자(관리자)", "등록 외부메일", "웹엑스 미팅번호", "카카오톡 ID"};
		String[] columnType = { "int", "String","String", "String", "String", "String", "String", "Stiring"};
		String sheetName = "업무용 휴대전화 현황";
		String excelFileName = "업무용 휴대전화 현황";
		List<CellPhone> cellPhoneList= equipService.selectCellPhoneList(cellPhone);

		try { 
			Utils.cellPhoneListToExcel(cellPhoneList, response, headers, headerNames, columnType, sheetName, excelFileName);
		} catch (IOException e) {
			
		}
		return null;
    }
    //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/equip/cellPhoneList").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);   
    cellPhone.setQueryInfo();
    mav.addObject("cellPhoneList", equipService.selectCellPhoneList(cellPhone));
    cellPhone.setContentCnt(equipService.selectCellPhoneListCnt(cellPhone));
    cellPhone.setPaginationInfo();
    mav.addObject("searchParams", cellPhone);
    
    return mav;
  }
  
  @GetMapping("/cellPhoneEditModal")
  public ModelAndView cellPhoneEditModal(@AuthenticationPrincipal UserInfo loginUser,CellPhone cellPhone) {
    ModelAndView mav = new ModelAndView("equip/cellPhoneEditModal");
    if(cellPhone.getPhoneKey() != null) {
    	cellPhone = equipService.selectCellPhoneInfo(cellPhone.getPhoneKey());
    	ParamMap param = new ParamMap();    
        param.put("downOrganCdList", organConfigService.selectDownOrganListWhereUserOgCd(cellPhone.getMgtOrgan()));
        mav.addObject("managerList", userInfoService.selectManagerList(param));
    }
    
    if (cellPhone.getPhoneKey() == null) {
    	cellPhone.setWrtOrgan(loginUser.getOgCd());
    	cellPhone.setWrtPart(loginUser.getOfcCd());
    	cellPhone.setWrtUserSeq(loginUser.getUserSeq());
    	cellPhone.setWrtNm(loginUser.getUserNm());
    }
  //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/equip/cellPhoneList").get(0).getAccessAuth();
    mav.addObject("mgtOrganList", loginUser.getDownOrganCdList());
    mav.addObject("userOrgan", loginUser.getOgCd());
    mav.addObject("accessAuth", accessAuth);
    mav.addObject("info", cellPhone);
    return mav;
  }
  
  @GetMapping("/cellPhoneSelecBox")
  public ModelAndView cellPhoneSelecBox(String ogCd) {
    ModelAndView mav = new ModelAndView("equip/cellPhoneSelecBox");
    ParamMap param = new ParamMap();    
    param.put("downOrganCdList", organConfigService.selectDownOrganListWhereUserOgCd(ogCd));
    mav.addObject("managerList", userInfoService.selectManagerList(param));
    return mav;
  }
  
  @PostMapping("/saveCellPhone")
  public Integer saveCellPhone (@AuthenticationPrincipal UserInfo loginUser,CellPhone cellPhone){
	  cellPhone.setWrtDt(LocalDateTime.now());
	  return equipService.saveCellPhone(cellPhone);
  }
  
  @PostMapping("/deleteCellPhone")
  public void deleteCellPhone(@RequestBody List<CellPhone> cellPhone){
	  equipService.deleteCellPhone(cellPhone);

  }
  
  @GetMapping("/pvreUseList")
  public ModelAndView pvreUseList(@AuthenticationPrincipal UserInfo loginUser,UseList useList,HttpServletResponse response) {
    ModelAndView mav = new ModelAndView("equip/pvreUseList");
    useList.setDownOrganCdList(loginUser.getDownOrganCdList());
    useList.setUseType("PVRE");
    //엑셀다운
    if(useList.getExcel() != null && useList.getExcel().equals("Y")){
    	String[] headers = { "use_no", "sosok", "use_dt", "detail_type_name", "people_cnt", "description", "wrt_dt"};
		String[] headerNames = { "연번", "경찰서","사용일시", "사용사유", "사용인원", "비고", "최종수정일"};
		String[] columnType = { "String", "String","String", "String", "int", "String", "String"};
		String sheetName = "휴대용 녹화장비 사용 대장";
		String excelFileName = "휴대용 녹화장비 사용 대장";
		List<UseList> useExcelList= equipService.selectUseList(useList);

		try { 
			Utils.useListToExcel(useExcelList, response, headers, headerNames, columnType, sheetName, excelFileName);
		} catch (IOException e) {
			
		}
		return null;
    }
    //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/equip/pvreUseList").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);   
    useList.setQueryInfo();
    mav.addObject("useList", equipService.selectUseList(useList));
    useList.setContentCnt(equipService.selectUseListCnt(useList));
    useList.setPaginationInfo();
    mav.addObject("organList", equipService.selectOrganList(useList));
    mav.addObject("searchParams", useList);
    return mav;
  }
  
  @GetMapping("/useEditModal")
  public ModelAndView useEditModal(@AuthenticationPrincipal UserInfo loginUser,UseList useList) {
    ModelAndView mav = new ModelAndView("equip/useEditModal");
    useList.setDownOrganCdList(loginUser.getDownOrganCdList());
    mav.addObject("organList", equipService.selectOrganList(useList));
    mav.addObject("userOrgan", loginUser.getOgCd());
    mav.addObject("useType", useList.getUseType());
  //메뉴권한 확인
    String accessAuth;
    if(useList.getUseType().equals("PVRE")) {
    	accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/equip/pvreUseList").get(0).getAccessAuth();
    	mav.addObject("accessAuth", accessAuth);
    }else if(useList.getUseType().equals("QIR")) {
    	accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/equip/qirUseList").get(0).getAccessAuth();
    	mav.addObject("accessAuth", accessAuth);
    }
    return mav;
  }
  
  @PostMapping("/saveUse")
  public void saveUse(@AuthenticationPrincipal UserInfo loginUser,UseList useList){
	  useList.setWrtOrgan(loginUser.getOgCd());
	  useList.setWrtPart(loginUser.getOfcCd());
	  useList.setWrtUserSeq(loginUser.getUserSeq());
	  useList.setWrtNm(loginUser.getUserId());
	  useList.setWrtDt(LocalDateTime.now());
	  equipService.saveUse(useList);
  }
  
  @GetMapping("/useModifyModal")
  public ModelAndView useModifyModal(@AuthenticationPrincipal UserInfo loginUser,UseList useList) {
    ModelAndView mav = new ModelAndView("equip/useModifyModal");
    useList.setDownOrganCdList(loginUser.getDownOrganCdList());
    mav.addObject("organList", equipService.selectOrganList(useList));
    mav.addObject("info", equipService.selectUseInfo(useList));
  //메뉴권한 확인
    String accessAuth;
    if(useList.getUseType().equals("PVRE")) {
    	accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/equip/pvreUseList").get(0).getAccessAuth();
    	mav.addObject("accessAuth", accessAuth);
    }else if(useList.getUseType().equals("QIR")) {
    	accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/equip/qirUseList").get(0).getAccessAuth();
    	mav.addObject("accessAuth", accessAuth);
    }
    return mav;
  }
  
  @PostMapping("/updateUse")
  public UseList uadateUse(@AuthenticationPrincipal UserInfo loginUser,UseList useList){
	  useList.setWrtOrgan(loginUser.getOgCd());
	  useList.setWrtPart(loginUser.getOfcCd());
	  useList.setWrtUserSeq(loginUser.getUserSeq());
	  useList.setWrtNm(loginUser.getUserId());
	  useList.setWrtDt(LocalDateTime.now());
	  return equipService.updateUse(useList);
  }
  
  @GetMapping("/useHistory")
  public ModelAndView useHistory(@AuthenticationPrincipal UserInfo loginUser,UseList useList) {
    ModelAndView mav = new ModelAndView("equip/useHistory");
    mav.addObject("infoList", equipService.selectUseInfoList(useList));
    return mav;
  }
  
  @GetMapping("/HistoryView")
  @ResponseBody
  public UseList HistoryView(UseList useList){
    return equipService.selectUseInfo(useList);
  }
  
  @PostMapping("/useDelete")
  public void useDelete(@RequestBody List<UseList> useList){
	  equipService.useDelete(useList);
  }
  
  @GetMapping("/qirUseList")
  public ModelAndView qirUseList(@AuthenticationPrincipal UserInfo loginUser,UseList useList,HttpServletResponse response) {
    ModelAndView mav = new ModelAndView("equip/qirUseList");
    useList.setDownOrganCdList(loginUser.getDownOrganCdList());
    useList.setUseType("QIR");
    //엑셀다운
    if(useList.getExcel() != null && useList.getExcel().equals("Y")){
    	String[] headers = { "use_no", "sosok", "use_dt", "detail_type_name", "people_cnt", "description", "wrt_dt"};
		String[] headerNames = { "연번", "경찰서","사용일시", "사용사유", "사용인원", "비고", "최종수정일"};
		String[] columnType = { "String", "String","String", "String", "int", "String", "String"};
		String sheetName = "방역조사실 사용대장";
		String excelFileName = "방역조사실 사용대장";
		List<UseList> useExcelList= equipService.selectUseList(useList);

		try { 
			Utils.useListToExcel(useExcelList, response, headers, headerNames, columnType, sheetName, excelFileName);
		} catch (IOException e) {
			
		}
		return null;
    }
    //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/equip/qirUseList").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);   
    useList.setQueryInfo();
    mav.addObject("useList", equipService.selectUseList(useList));
    useList.setContentCnt(equipService.selectUseListCnt(useList));
    useList.setPaginationInfo();
    mav.addObject("searchParams", useList);
    mav.addObject("organList", equipService.selectOrganList(useList));
    return mav;
  }
 
  
  
  

}
