package com.dbnt.sims.fipTarget;


import com.dbnt.sims.authMgt.service.AuthMgtService;
import com.dbnt.sims.fipTarget.model.PartInfo;
import com.dbnt.sims.fipTarget.model.PartInfoFile;
import com.dbnt.sims.fipTarget.model.PartWork;
import com.dbnt.sims.fipTarget.model.PartWorkFile;
import com.dbnt.sims.fipTarget.model.VulnFile;
import com.dbnt.sims.fipTarget.model.Vulnerable;
import com.dbnt.sims.fipTarget.service.FipTargetService;
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.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

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

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


@RestController
@RequiredArgsConstructor
@RequestMapping("/target")
public class FipTargetController {

  private final OrganConfigService organConfigService;
  private final AuthMgtService authMgtService;
  private final FipTargetService fipTargetService;
  private final UserInfoService userInfoService;
  
  // 외사분실운영현황 시작
  @GetMapping("/partInfoList")
  public ModelAndView partInfoList(@AuthenticationPrincipal UserInfo loginUser,PartInfo partInfo, HttpServletResponse response) {
    ModelAndView mav = new ModelAndView("fipTarget/partInfoList");
    partInfo.setDownOrganCdList(loginUser.getDownOrganCdList());
  //엑셀다운
    if(partInfo.getExcel() != null && partInfo.getExcel().equals("Y")){
    	ParamMap header = fipTargetService.selectWorkTypeTotal(partInfo);
    	String[] headers = { "mgt_organ", "land_police", "terminal_nm", "mp_work_type", "mp_people_cnt", "mp_description", "pl_work_type", "pl_people_cnt", "pl_description", "pi_manager_name", "rent_price", "utility_price", "wrt_dt"};
		String[] headerNames = { "해경서", "육경서","터미넡명", "해경", "", "", "육경", "", "", "", "", "",""};
		String[] headerNames2 = null;
		if(header != null) {
			headerNames2 = new String[] { "", "", "", "상주 "+header.getString("mp_sangju")+"개소 "+header.getString("mp_sangju_total")+"명"
									 ,"비상주 "+header.getString("mp_bsangju")+"개소 "+header.getString("mp_bsangju_total")+"명"
									 ,"폐쇄 "+header.getString("mp_closure")+"개소 "+header.getString("mp_closure_total")+"명"
									 ,"상주 "+header.getString("pl_sangju")+"개소 "+header.getString("pl_sangju_total")+"명"
									 ,"비상주 "+header.getString("pl_bsangju")+"개소 "+header.getString("pl_bsangju_total")+"명"
									 ,"폐쇄 "+header.getString("pl_closure")+"개소 "+header.getString("pl_closure_total")+"명"
									 , "", "", "", "" };
		}else {
			headerNames2 = new String[] { "", "","", "상주 0개소 0명","비상주 0개소 0명","폐쇄 0개소 0명","상주 0개소 0명","비상주 0개소 0명","폐쇄 0개소 0명", "", "", "", "" };
		}
		String[] headerNames3 = { "", "","", "근무방법", "명", "비고", "근무방법", "명", "비고", "담당자", "임차료", "공공요금", "최종수정일" };
		String[] columnType = { "String", "String","String", "String", "int", "String", "String", "int", "String", "String", "String","String", "String"};
		String sheetName = "외사 분실 현황";
		String excelFileName = "외사 분실 현황";
		List<PartInfo> partInfoList= fipTargetService.selectPartInfoList(partInfo);

		try { 
			Utils.partInfolistToExcel(partInfoList, response, headers, headerNames,headerNames2,headerNames3, columnType, sheetName, excelFileName);
		} catch (IOException e) {
			
		}
		return null;
    }
  //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/target/partInfoList").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);
    partInfo.setQueryInfo();
    mav.addObject("total", fipTargetService.selectWorkTypeTotal(partInfo));
    mav.addObject("partInfoList", fipTargetService.selectPartInfoList(partInfo));
    partInfo.setContentCnt(fipTargetService.selectPartInfoListCnt(partInfo));
    partInfo.setPaginationInfo();
    mav.addObject("mgtOrganList", loginUser.getDownOrganCdList());
    mav.addObject("searchParams", partInfo);
    return mav;
  }
  
  @GetMapping("/partInfoEditModal")
  public ModelAndView partInfoEditModal(@AuthenticationPrincipal UserInfo loginUser,PartInfo partInfo) {
    ModelAndView mav = new ModelAndView("fipTarget/partInfoEditModal");
  //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/target/partInfoList").get(0).getAccessAuth();
    mav.addObject("userOrgan", loginUser.getOgCd());
    mav.addObject("mgtOrganList", loginUser.getDownOrganCdList());
    mav.addObject("accessAuth", accessAuth);
   
    return mav;
  }
  
  @GetMapping("/partInfoSelecBox")
  public ModelAndView equipTypeSelecBox(String ogCd) {
    ModelAndView mav = new ModelAndView("fipTarget/partInfoSelecBox");
    ParamMap param = new ParamMap();    
    param.put("downOrganCdList", organConfigService.selectDownOrganListWhereUserOgCd(ogCd));
    mav.addObject("managerList", userInfoService.selectManagerList(param));
    return mav;
  }
  
  @PostMapping("/savePartInfo")
  public void savePartInfo (@AuthenticationPrincipal UserInfo loginUser, PartInfo partInfo,MultipartHttpServletRequest request){
	  partInfo.setMultipartFileList(request.getMultiFileMap().get("uploadFiles"));
	  partInfo.setWrtNm(loginUser.getUserId());
	  partInfo.setWrtPart(loginUser.getOfcCd());
	  partInfo.setWrtUserSeq(loginUser.getUserSeq());
	  partInfo.setWrtOrgan(loginUser.getOgCd());
	  partInfo.setWrtDt(LocalDateTime.now());
      fipTargetService.savePartInfo(partInfo);
  }
  
  @GetMapping("/updatePartInfoPage")
  public ModelAndView updatePartInfoPage(@AuthenticationPrincipal UserInfo loginUser,PartInfo partInfo) {
    ModelAndView mav = new ModelAndView("fipTarget/partInfoModifyModal");
    mav.addObject("mgtOrganList", loginUser.getDownOrganCdList());
    PartInfo partInfoView = fipTargetService.selectPartInfo(partInfo);
    ParamMap param = new ParamMap();    
    param.put("downOrganCdList", organConfigService.selectDownOrganListWhereUserOgCd(partInfoView.getMgtOrgan()));
    mav.addObject("managerList", userInfoService.selectManagerList(param));
    partInfoView.setFileList(fipTargetService.selectPartInfoFile(partInfo));
    mav.addObject("partInfo", partInfoView);
  //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/target/partInfoList").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);
    mav.addObject("userId", loginUser.getUserId());
    mav.addObject("wrtId", fipTargetService.selectPartInfoFirstId(partInfo));
    return mav;
  }
  
  @PostMapping("/updatePartInfo")
  public int updatePartInfo (@AuthenticationPrincipal UserInfo loginUser,PartInfo partInfo,
      MultipartHttpServletRequest request,
      @RequestParam(value = "fileSeq", required = false) List < Integer > deleteFileSeq){
	  partInfo.setMultipartFileList(request.getMultiFileMap().get("uploadFiles"));
	  partInfo.setWrtUserSeq(loginUser.getUserSeq());
	  partInfo.setWrtNm(loginUser.getUserId());
	  partInfo.setWrtOrgan(loginUser.getOgCd());
	  partInfo.setWrtPart(loginUser.getOfcCd());
	  partInfo.setWrtDt(LocalDateTime.now());
	  fipTargetService.updatePartInfo(partInfo,deleteFileSeq);
	return partInfo.getPiSeq();
  }
  
  @GetMapping("/PartInfoHistoryPage")
  public ModelAndView PartInfoHistoryPage(PartInfo partInfo) {
    ModelAndView mav = new ModelAndView("fipTarget/partInfoHistory");
    mav.addObject("partInfoList", fipTargetService.selectPartInfoSeq(partInfo));
    return mav;
  }
  
  @GetMapping("/partInfoHistoryView")
  @ResponseBody
  public PartInfo partInfoHistoryView(PartInfo partInfo){
	  PartInfo partInfoHistory = fipTargetService.selectPartInfoHistoryView(partInfo);
	  partInfoHistory.setFileList(fipTargetService.selectPartInfoFileHistoryView(partInfo));
    return partInfoHistory;
  }
  
  @PostMapping("/deletePartInfo")
  @ResponseBody
  public void deletePartInfo(@RequestBody PartInfo partInfo) {
	  fipTargetService.deletePartInfo(partInfo);
  }
  
  @GetMapping("/partInfoFileDownload")
  public void partInfoFileDownload(HttpServletRequest request,
                           HttpServletResponse response,
                           Integer fileSeq,
                           Integer piSeq,
                           Integer versionNo) {
    PartInfoFile downloadFile = fipTargetService.selectPartInfoFileDown(fileSeq, piSeq,versionNo);

    BufferedInputStream in;
    BufferedOutputStream out;
    try {
      File file = new File(downloadFile.getFilePath(), downloadFile.getConvNm());

      setDisposition(downloadFile.getOrigNm()+'.'+downloadFile.getFileExtn(), request, response);
      in = new BufferedInputStream(new FileInputStream(file));
      out = new BufferedOutputStream(response.getOutputStream());
      FileCopyUtils.copy(in, out);
      out.flush();
      if(out!=null) out.close();
      if(in!=null )in.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  
  private void setDisposition(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
	    String browser = getBrowser(request);

	    String dispositionPrefix = "attachment; filename=";
	    String encodedFilename = null;

	    if (browser.equals("MSIE")) {
	      encodedFilename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
	    } else if (browser.equals("Trident")) { // IE11 문자열 깨짐 방지
	      encodedFilename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
	    } else if (browser.equals("Firefox")) {
	      encodedFilename = "\"" + new String(filename.getBytes("UTF-8"), "8859_1") + "\"";
	    } else if (browser.equals("Opera")) {
	      encodedFilename = "\"" + new String(filename.getBytes("UTF-8"), "8859_1") + "\"";
	    } else if (browser.equals("Chrome")) {
	      StringBuffer sb = new StringBuffer();
	      for (int i = 0; i < filename.length(); i++) {
	        char c = filename.charAt(i);
	        if (c > '~') {
	          sb.append(URLEncoder.encode("" + c, "UTF-8"));
	        } else {
	          sb.append(c);
	        }
	      }
	      encodedFilename = sb.toString();
	    } else {
	      throw new IOException("Not supported browser");
	    }

	    response.setHeader("Content-Disposition", dispositionPrefix + encodedFilename);

	    if ("Opera".equals(browser)) {
	      response.setContentType("application/octet-stream;charset=UTF-8");
	    }
	  }
  
  private String getBrowser(HttpServletRequest request) {
	    String header = request.getHeader("User-Agent");
	    if (header.indexOf("MSIE") > -1) {
	      return "MSIE";
	    } else if (header.indexOf("Trident") > -1) { // IE11 문자열 깨짐 방지
	      return "Trident";
	    } else if (header.indexOf("Chrome") > -1) {
	      return "Chrome";
	    } else if (header.indexOf("Opera") > -1) {
	      return "Opera";
	    }
	    return "Firefox";
	  }
  //외사분실 운영현황 끝
  //외사분실실적 시작
  @GetMapping("/partWorkList")
  public ModelAndView partWorkList(@AuthenticationPrincipal UserInfo loginUser,PartWork partWork, HttpServletResponse response) {
    ModelAndView mav = new ModelAndView("fipTarget/partWorkList");
    partWork.setDownOrganCdList(loginUser.getDownOrganCdList());
  //엑셀다운
    if(partWork.getExcel() != null && partWork.getExcel().equals("Y")){
    	String[] headers = { "terminal_nm", "wrt_nm", "work_dt", "work_type_ch", "work_type_poci", "work_type_sri", "work_type_ji", "work_type_mt", "work_type_etc", "description", "file_cnt","wrt_dt"};
		String[] headerNames = { "외사 터미널명", "작성자","일시", "종류", "", "", "", "", "", "비고", "첨부파일", "최근수정일"};
		String[] headerNames2 = { "", "","", "사건처리", "범죄첩보제공", "SRI", "합동점검", "회의", "기타", "", "", ""};
		String[] columnType = { "String", "String","String", "String", "String", "String", "String", "String", "String", "String", "String","String"};
		String sheetName = "외사분실 실적";
		String excelFileName = "외사분실 실적";
		List<PartWork> partWorkList= fipTargetService.selectPartWorkList(partWork);

		try { 
			Utils.partWorkListToExcel(partWorkList, response, headers, headerNames,headerNames2, columnType, sheetName, excelFileName);
		} catch (IOException e) {
			
		}
		return null;
    } 
    //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/target/partWorkList").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);
    partWork.setQueryInfo();
    mav.addObject("partWorkList", fipTargetService.selectPartWorkList(partWork));
    partWork.setContentCnt(fipTargetService.selectPartWorkListCnt(partWork));
    partWork.setPaginationInfo();  
    mav.addObject("uesrId", loginUser.getUserId());
    mav.addObject("searchParams", partWork);
    return mav;
  }
  
  @GetMapping("/partWorkEditModal")
  public ModelAndView partWorkEditModal(@AuthenticationPrincipal UserInfo loginUser,PartWork partWork) {
    ModelAndView mav = new ModelAndView("fipTarget/partWorkEditModal");
    partWork.setDownOrganCdList(loginUser.getDownOrganCdList());
  //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/target/partWorkList").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);
    mav.addObject("tnList", fipTargetService.selectTerminalName(partWork));
   
    return mav;
  }
  
  @PostMapping("/savePartWork")
  public void savePartWork (@AuthenticationPrincipal UserInfo loginUser, PartWork partWork,MultipartHttpServletRequest request){
	  partWork.setMultipartFileList(request.getMultiFileMap().get("uploadFiles"));
	  partWork.setWrtNm(loginUser.getUserId());
	  partWork.setWrtPart(loginUser.getOfcCd());
	  partWork.setWrtUserSeq(loginUser.getUserSeq());
	  partWork.setWrtOrgan(loginUser.getOgCd());
	  partWork.setWrtDt(LocalDateTime.now());
      fipTargetService.savePartWork(partWork);
  }
  
  @GetMapping("/partWorkView")
  public ModelAndView partWorkView(@AuthenticationPrincipal UserInfo loginUser,PartWork partWork) {
    ModelAndView mav = new ModelAndView("fipTarget/partWorkModifyModal");
    partWork.setDownOrganCdList(loginUser.getDownOrganCdList());
    PartWork partWorkView = fipTargetService.selectPartWorkInfo(partWork);
    partWorkView.setFileList(fipTargetService.selectPartWorkFile(partWork));
    mav.addObject("pwInfo", partWorkView);
  //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/target/partInfoList").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);
    mav.addObject("userId", loginUser.getUserId());
    return mav;
  }
  
  @PostMapping("/updatePartWork")
  public PartWork updatePartWork (@AuthenticationPrincipal UserInfo loginUser, PartWork partWork,
		  					 MultipartHttpServletRequest request,
		  					 @RequestParam(value = "fileSeq", required = false) List < Integer > deleteFileSeq){
	  partWork.setMultipartFileList(request.getMultiFileMap().get("uploadFiles"));
	  partWork.setWrtDt(LocalDateTime.now());
      fipTargetService.updatePartWork(partWork,deleteFileSeq);
	return partWork;
  }
  
  @PostMapping("/deletePartWork")
  @ResponseBody
  public void deletePartWork(@RequestBody PartWork partWork) {
	  fipTargetService.deletePartWork(partWork);
  }
  
  @GetMapping("/partWorkFileDownload")
  public void partWorkFileDownload(HttpServletRequest request,
                           HttpServletResponse response,
                           Integer fileSeq,
                           Integer pwSeq,
                           Integer piSeq) {
    PartWorkFile downloadFile = fipTargetService.selectPartWorkFileDown(fileSeq, pwSeq,piSeq);

    BufferedInputStream in;
    BufferedOutputStream out;
    try {
      File file = new File(downloadFile.getFilePath(), downloadFile.getConvNm());

      setDisposition(downloadFile.getOrigNm()+'.'+downloadFile.getFileExtn(), request, response);
      in = new BufferedInputStream(new FileInputStream(file));
      out = new BufferedOutputStream(response.getOutputStream());
      FileCopyUtils.copy(in, out);
      out.flush();
      if(out!=null) out.close();
      if(in!=null )in.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
//외사분실실적 끝
//외사취약지 시작

  @GetMapping("/vulnerableList")
  public ModelAndView vulnerableList(@AuthenticationPrincipal UserInfo loginUser,Vulnerable vulnerable, HttpServletResponse response) {
    ModelAndView mav = new ModelAndView("fipTarget/vulnerableList");

    mav.addObject("vulnerableList", fipTargetService.selectVulnerableList(vulnerable));
  //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/target/vulnerableList").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);
    mav.addObject("searchParams", vulnerable);
    return mav;
  }
  
  @GetMapping("/vulnEditModal")
  public ModelAndView vulnEditModal(@AuthenticationPrincipal UserInfo loginUser,Vulnerable vulnerable) {
    ModelAndView mav = new ModelAndView("fipTarget/vulnEditModal");
    vulnerable.setDownOrganCdList(loginUser.getDownOrganCdList());
    mav.addObject("organList", fipTargetService.selecetVulnOrganList(vulnerable));
    mav.addObject("userOrgan", loginUser.getOgCd());
    if(vulnerable.getVulnKey() != null) {
    	vulnerable = fipTargetService.selectVulnInfo(vulnerable);
    	vulnerable.setFileList(fipTargetService.selectVulnFile(vulnerable.getVulnKey()));
    	mav.addObject("userId", loginUser.getUserId());
    }
  //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/target/vulnerableList").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);
    vulnerable.setWrtNm(loginUser.getUserId());
	vulnerable.setWrtPart(loginUser.getOfcCd());
	vulnerable.setWrtUserSeq(loginUser.getUserSeq());
	vulnerable.setWrtOrgan(loginUser.getOgCd());
    mav.addObject("info", vulnerable);
    return mav;
  }
  
  @PostMapping("/saveVulnerable")
  public Integer saveVulnerable (@AuthenticationPrincipal UserInfo loginUser, Vulnerable vulnerable,MultipartHttpServletRequest request,
		  					  @RequestParam(value = "fileSeq", required = false) List < Integer > deleteFileSeq){
	  vulnerable.setMultipartFileList(request.getMultiFileMap().get("uploadFiles"));
	  vulnerable.setWrtDt(LocalDateTime.now());
	  Integer result = fipTargetService.saveVulnerable(vulnerable,deleteFileSeq);
	return result;
  }
  
  @GetMapping("/vulnInfoModal")
  public ModelAndView vulnInfoModal(@AuthenticationPrincipal UserInfo loginUser,Vulnerable vulnerable) {
    ModelAndView mav = new ModelAndView("fipTarget/vulnInfoModal");
    vulnerable.setDownOrganCdList(loginUser.getDownOrganCdList());;
    mav.addObject("vulnInfoList", fipTargetService.selectVulnInfoList(vulnerable));
    mav.addObject("organNm", fipTargetService.selectOrganName(vulnerable.getMgtOrgan()));
  //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/target/vulnerableList").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);
   
    return mav;
  }
  
  @GetMapping("/vulnViewModal")
  public ModelAndView vulnViewModal(@AuthenticationPrincipal UserInfo loginUser,Vulnerable vulnerable) {
    ModelAndView mav = new ModelAndView("fipTarget/vulnViewModal");
    Vulnerable vulnInfo = fipTargetService.selectVulnInfo(vulnerable);
    vulnInfo.setFileList(fipTargetService.selectVulnFile(vulnInfo.getVulnKey()));
    mav.addObject("vulnInfo", vulnInfo);
  //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/target/vulnerableList").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);
   
    return mav;
  }
  
  @GetMapping("/vulnFileDownload")
  public void vulnFileDownload(HttpServletRequest request,
                           HttpServletResponse response,
                           Integer fileSeq,
                           Integer vulnKey) {
	  VulnFile downloadFile = fipTargetService.selectVulnInfoFileDown(fileSeq, vulnKey);

    BufferedInputStream in;
    BufferedOutputStream out;
    try {
      File file = new File(downloadFile.getFilePath(), downloadFile.getConvNm());

      setDisposition(downloadFile.getOrigNm()+'.'+downloadFile.getFileExtn(), request, response);
      in = new BufferedInputStream(new FileInputStream(file));
      out = new BufferedOutputStream(response.getOutputStream());
      FileCopyUtils.copy(in, out);
      out.flush();
      if(out!=null) out.close();
      if(in!=null )in.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  
  @PostMapping("/deleteVulnerable")
  @ResponseBody
  public void deleteVulnerable(@RequestBody Vulnerable vulnerable) {
	  fipTargetService.deleteVulnerable(vulnerable);
  }
//외사취약지 끝 
  
  
 
  
  
  

}
