package com.dbnt.faisp.main.userInfo;


import com.dbnt.faisp.kwms.service.KwmsService;
import com.dbnt.faisp.main.authMgt.service.AuthMgtService;
import com.dbnt.faisp.main.codeMgt.service.CodeMgtService;
import com.dbnt.faisp.main.userInfo.model.*;
import com.dbnt.faisp.main.userInfo.model.PersonnelStatus;
import com.dbnt.faisp.main.userInfo.model.UserCareer;
import com.dbnt.faisp.main.userInfo.model.UserEdu;
import com.dbnt.faisp.main.userInfo.service.PoliceService;
import com.dbnt.faisp.main.userInfo.service.UserInfoService;
import com.dbnt.faisp.util.Utils;

import lombok.RequiredArgsConstructor;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequiredArgsConstructor
@RequestMapping("/police")
public class PoliceController {

  private final AuthMgtService authMgtService;
  private final CodeMgtService codeMgtService;
  private final UserInfoService userInfoService;
  private final PoliceService policeService;
  private final KwmsService kwmsService;


  @GetMapping("/policeList")
  public ModelAndView policeList(@AuthenticationPrincipal UserInfo loginUser, UserInfo userInfo, HttpServletResponse response) {
    ModelAndView mav = new ModelAndView("police/police/policeList");
    userInfo.setDownOrganCdList(loginUser.getDownOrganCdList());
    if(userInfo.getUserStatus() == null) {
      userInfo.setUserStatus("USC003");
    }
    //엑셀다운
    if(userInfo.getExcel() != null && userInfo.getExcel().equals("Y")){
      String[] headers = { "rownum", "title_cd", "user_nm", "organ_nm", "ofc_cd", "birth_date", "sex", "police_in_date", "title_in_date", "ofc_in_date", "outturn_cd","", "job_in_cd", "wrt_dt"};
      String[] headerNames = { "순번", "계급","성명", "청", "현부서"+System.lineSeparator()+"과", "생년월일","성별", "최초"+System.lineSeparator()+"임용", "현 계급"+System.lineSeparator()+"임용", "현 부서"+System.lineSeparator()+"임용", "수사경과"+System.lineSeparator()+"보유여부", "외사경력", "입직"+System.lineSeparator()+"경로","최종"+System.lineSeparator()+"수정일"};
      String[] columnType = {"String", "String", "String","String", "String", "String", "String", "String", "String", "String", "String", "String","String", "String"};
      String sheetName ="";
      String excelFileName="";
      if(userInfo.getUserStatus().equals("USC003")) {
        sheetName = "現 외사경찰 현황";
        excelFileName = "現 외사경찰 현황";
      }
      if(userInfo.getUserStatus().equals("USC006")) {
        sheetName = "前 외사경찰 현황";
        excelFileName = "前 외사경찰 현황";
      }
      if(userInfo.getUserStatus().equals("USC007")) {
        sheetName = "非 외사경찰 현황";
        excelFileName = "非 외사경찰 현황";
      }
      List<UserInfo> policeList= userInfoService.selectPoliceList(userInfo);

      try {
        Utils.policelistToExcel(policeList, response, headers, headerNames, columnType, sheetName, excelFileName);
      } catch (IOException e) {

      }
      return null;
    }

    //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/police/policeList").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);
    userInfo.setQueryInfo();
    mav.addObject("policeList", userInfoService.selectPoliceList(userInfo));
    userInfo.setContentCnt(userInfoService.selectPoliceListCnt(userInfo));
    userInfo.setPaginationInfo();
    mav.addObject("mgtOrganList", loginUser.getDownOrganCdList());
    mav.addObject("userStatus", userInfo.getUserStatus());
    mav.addObject("searchParams", userInfo);
    return mav;
  }

  @GetMapping("/policeEditModal")
  public ModelAndView policeEditModal(@AuthenticationPrincipal UserInfo loginUser,UserInfo userInfo){
    ModelAndView mav = new ModelAndView("police/police/policeEditModal");
    mav.addObject("ogList", codeMgtService.selectCodeMgtList("OG", ""));
    mav.addObject("ofcList", codeMgtService.selectCodeMgtList("OFC", ""));
    mav.addObject("titleList", codeMgtService.selectCodeMgtList("JT", ""));
    mav.addObject("outturnList", codeMgtService.selectCodeMgtList("OTC", ""));
    mav.addObject("seriesList", codeMgtService.selectCodeMgtList("SRC", ""));
    mav.addObject("languageList", codeMgtService.selectCodeMgtList("LNG", ""));
    mav.addObject("statusList", codeMgtService.selectCodeMgtList("USC", ""));

    //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/police/policeList").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);
    mav.addObject("userInfo", userInfoService.selectUserInfo(userInfo.getUserSeq()));
    return mav;
  }

  @PostMapping("/updateUserInfo")
  public int updateUserInfo(@AuthenticationPrincipal UserInfo loginUser,UserInfo userInfo) {
    userInfoService.updateUserInfo(loginUser,userInfo);
    return userInfo.getUserSeq();
  }

  @GetMapping("/policeHistory")
  public ModelAndView policeHistory(@AuthenticationPrincipal UserInfo loginUser,UserInfoHistory userInfoHistory){
    ModelAndView mav = new ModelAndView("police/police/policeHistory");
    mav.addObject("userStatus", userInfoService.selectUserStatus(userInfoHistory));
    mav.addObject("policeList", userInfoService.selectPoliceHisList(userInfoHistory));

    return mav;
  }

  @GetMapping("/policeHistoryView")
  @ResponseBody
  public UserInfoHistory policeHistoryView(UserInfoHistory userInfoHistory){
    return userInfoService.selectPoliceHistoryView(userInfoHistory);
  }

  @PostMapping("/policeStatusUpdate")
  @ResponseBody
  public int userCompanion(@RequestBody List<UserInfo> userInfo){
    return userInfoService.updateUserCompanion(userInfo);
  }

  @PostMapping("/syncUserInfoToKwms")
  @ResponseBody
  public String syncUserInfoToKwms(@AuthenticationPrincipal UserInfo loginUser,@RequestBody List<UserInfo> infoList){
    for(UserInfo info: infoList){
      UserInfo kwmsInfo = kwmsService.selectEmpInfo(info.getDicCode());
      if(kwmsInfo!=null){
        kwmsInfo.setUserSeq(info.getUserSeq());
        userInfoService.updateUserInfo(loginUser,kwmsInfo);
      }
    }
    if(infoList.size()==1){
      return infoList.get(0).getUserSeq().toString();
    }else{
      return "";
    }
  }

  @GetMapping("/personnelStatus")
  public ModelAndView personnelStatus(@AuthenticationPrincipal UserInfo loginUser, PersonnelStatus personnelStatus){
    ModelAndView mav = new ModelAndView("police/personnelStatus/personnelStatus");
    //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/police/personnelStatus").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);

    if(personnelStatus.getYear()==null){
      personnelStatus.setYear(Integer.toString(LocalDateTime.now().getYear()));
    }
    personnelStatus.setDownOrganCdList(loginUser.getDownOrganCdList());
    mav.addObject("searchParams", personnelStatus);
    mav.addObject("jtList", codeMgtService.selectCodeMgtList("JT", "reverse"));
    List<PersonnelStatus> statusList = policeService.selectPersonnelStatusList(personnelStatus);
    statusList = calcStatusList(statusList);
    mav.addObject("statusSummary", makeStatusSummary(statusList));
    mav.addObject("statusList", statusList);
    return mav;
  }

  @GetMapping("/personnelStatusRow")
  public ModelAndView personnelStatusRow(@AuthenticationPrincipal UserInfo loginUser){
    ModelAndView mav = new ModelAndView("police/personnelStatus/personnelStatusRow");
    mav.addObject("mgtOrganList", loginUser.getDownOrganCdList());
    return mav;
  }
  @GetMapping("/selectPersonnelStatus")
  public PersonnelStatus selectPersonnelStatus(PersonnelStatus personnelStatus){
    return policeService.selectPersonnelStatusLastVersion(personnelStatus);
  }
  @GetMapping("/nowPersonnelStatus")
  public PersonnelStatus nowPersonnelStatus(String ogCd){
    return policeService.nowPersonnelStatus(ogCd);
  }
  @PostMapping("/savePersonnelStatus")
  @ResponseBody
  public void savePersonnelStatus(@AuthenticationPrincipal UserInfo loginUser, @RequestBody List<PersonnelStatus> personnelStatusList){
    policeService.savePersonnelStatus(loginUser, personnelStatusList);
  }
  @GetMapping("/personnelStatusHistory")
  public ModelAndView personnelStatusHistory(PersonnelStatus status){
    ModelAndView mav = new ModelAndView("police/personnelStatus/personnelStatusHistory");
    mav.addObject("jtList", codeMgtService.selectCodeMgtList("JT", "reverse"));
    List<PersonnelStatus> statusList = policeService.selectPersonnelStatusHistoryList(status);
    mav.addObject("statusList", calcStatusList(statusList));
    return mav;
  }

  @GetMapping("/careerMgt")
  public ModelAndView careerMgt(@AuthenticationPrincipal UserInfo loginUser, UserInfo userInfo){
    ModelAndView mav = new ModelAndView("police/career/careerMgt");
    userInfo.setDownOrganCdList(loginUser.getDownOrganCdList());
    if(userInfo.getUserStatus() == null) {
      userInfo.setUserStatus("USC003");
    }

    //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/police/careerMgt").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);
    userInfo.setQueryInfo();
    mav.addObject("policeList", userInfoService.selectPoliceList(userInfo));
    userInfo.setContentCnt(userInfoService.selectPoliceListCnt(userInfo));
    userInfo.setPaginationInfo();
    mav.addObject("mgtOrganList", loginUser.getDownOrganCdList());
    mav.addObject("userStatus", userInfo.getUserStatus());
    mav.addObject("searchParams", userInfo);
    return mav;
  }
  @GetMapping("/careerModal")
  public ModelAndView careerModal(@AuthenticationPrincipal UserInfo loginUser, UserCareer career){
    ModelAndView mav = new ModelAndView("police/career/careerModal");

    //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/police/careerMgt").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);
    mav.addObject("selectedTab", career.getCareerCd());
    mav.addObject("crcList", codeMgtService.selectCodeMgtList("CRC", ""));
    mav.addObject("userInfo", policeService.selectPoliceInfo(career.getUserSeq()));
    mav.addObject("careerList", policeService.selectCareerList(career.getUserSeq()));
    mav.addObject("userSeq", loginUser.getUserSeq());
    return mav;
  }
  @GetMapping("/careerFormModal")
  public ModelAndView careerFormModal(@AuthenticationPrincipal UserInfo loginUser, UserCareer career){
    ModelAndView mav = new ModelAndView("police/career/careerFormModal");
    mav.addObject("crcList", codeMgtService.selectCodeMgtList("CRC", ""));
    mav.addObject("dsnList", codeMgtService.selectCodeMgtList("DSN", ""));
    mav.addObject("ogList", codeMgtService.selectCodeMgtList("OG", ""));
    mav.addObject("ofcList", codeMgtService.selectCodeMgtList("OFC", ""));
    mav.addObject("jtList", codeMgtService.selectCodeMgtList("JT", ""));
    mav.addObject("career", career);
    return mav;
  }
  @PostMapping("/saveCareer")
  public void saveCareer(@AuthenticationPrincipal UserInfo loginUser, UserCareer career){
    career.setWrtOrgan(loginUser.getOgCd());
    career.setWrtPart(loginUser.getOfcCd());
    career.setWrtUserSeq(loginUser.getUserSeq());
    career.setWrtUserGrd(loginUser.getTitleCd());
    career.setWrtUserNm(loginUser.getUserNm());
    career.setWrtDt(LocalDateTime.now());
    policeService.saveCareer(career);
  }
  @PostMapping("/saveCareerList")
  public void saveCareerList(@AuthenticationPrincipal UserInfo loginUser, UserCareer info){
    for(UserCareer career: info.getCareerList()){
      career.setWrtOrgan(loginUser.getOgCd());
      career.setWrtPart(loginUser.getOfcCd());
      career.setWrtUserSeq(loginUser.getUserSeq());
      career.setWrtUserGrd(loginUser.getTitleCd());
      career.setWrtUserNm(loginUser.getUserNm());
      career.setWrtDt(LocalDateTime.now());
    }
    policeService.saveCareerList(info.getCareerList());
  }
  @PostMapping("/deleteCareer")
  public void deleteCareer(UserCareer career){
    policeService.deleteCareer(career);
  }
  
  @GetMapping("/educationMgt")
  public ModelAndView educationMgt(@AuthenticationPrincipal UserInfo loginUser, UserInfo userInfo, HttpServletResponse response){
    ModelAndView mav = new ModelAndView("police/education/educationMgt");
    userInfo.setDownOrganCdList(loginUser.getDownOrganCdList());
    if(userInfo.getUserStatus() == null) {
      userInfo.setUserStatus("USC003");
    }

    //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/police/educationMgt").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);
    userInfo.setQueryInfo();
    mav.addObject("policeList", userInfoService.selectPoliceList(userInfo));
    userInfo.setContentCnt(userInfoService.selectPoliceListCnt(userInfo));
    userInfo.setPaginationInfo();
    mav.addObject("mgtOrganList", loginUser.getDownOrganCdList());
    mav.addObject("userStatus", userInfo.getUserStatus());
    mav.addObject("searchParams", userInfo);
    return mav;
  }
  
  @GetMapping("/eduEditModal")
  public ModelAndView eduEditModal(@AuthenticationPrincipal UserInfo loginUser, UserEdu userEdu){
    ModelAndView mav = new ModelAndView("police/education/eduEditModal");

    //메뉴권한 확인
    String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/police/educationMgt").get(0).getAccessAuth();
    mav.addObject("accessAuth", accessAuth);
    mav.addObject("userInfo", policeService.selectPoliceInfo(userEdu.getUserSeq()));
    mav.addObject("eduList", policeService.selectEduList(userEdu));
    mav.addObject("userSeq", loginUser.getUserSeq());
    return mav;
  }
  
  @PostMapping("/saveEdu")
  @ResponseBody
  public int saveEdu(@AuthenticationPrincipal UserInfo loginUser,@RequestBody List<UserEdu> userEdu){
	  return policeService.saveEdu(loginUser,userEdu);
  }
  
  @PostMapping("/deleteEdu")
  @ResponseBody
  public int deleteEdu(@RequestBody UserEdu userEdu) {
    return policeService.deleteEdu(userEdu);
  }

  private List<PersonnelStatus> calcStatusList(List<PersonnelStatus> statusList) {
    for (PersonnelStatus status : statusList) {
      status.setSumMax(status.getJt001Max() + status.getJt002Max() + status.getJt003Max() + status.getJt004Max() + status.getJt005Max() + status.getJt006Max() + status.getJt007Max());
      status.setSumNow(status.getJt001Now() + status.getJt002Now() + status.getJt003Now() + status.getJt004Now() + status.getJt005Now() + status.getJt006Now() + status.getJt007Now());
    }
    return statusList;
  }

  private PersonnelStatus makeStatusSummary(List<PersonnelStatus> statusList) {
    PersonnelStatus statusSummary = new PersonnelStatus();
    for(PersonnelStatus status: statusList){
      statusSummary.setSumMax(statusSummary.getSumMax()+status.getSumMax());
      statusSummary.setSumNow(statusSummary.getSumNow()+status.getSumNow());
      statusSummary.setJt007Max(statusSummary.getJt007Max()+ status.getJt007Max());
      statusSummary.setJt007Now(statusSummary.getJt007Now()+ status.getJt007Now());
      statusSummary.setJt006Max(statusSummary.getJt006Max()+ status.getJt006Max());
      statusSummary.setJt006Now(statusSummary.getJt006Now()+ status.getJt006Now());
      statusSummary.setJt005Max(statusSummary.getJt005Max()+ status.getJt005Max());
      statusSummary.setJt005Now(statusSummary.getJt005Now()+ status.getJt005Now());
      statusSummary.setJt004Max(statusSummary.getJt004Max()+ status.getJt004Max());
      statusSummary.setJt004Now(statusSummary.getJt004Now()+ status.getJt004Now());
      statusSummary.setJt003Max(statusSummary.getJt003Max()+ status.getJt003Max());
      statusSummary.setJt003Now(statusSummary.getJt003Now()+ status.getJt003Now());
      statusSummary.setJt002Max(statusSummary.getJt002Max()+ status.getJt002Max());
      statusSummary.setJt002Now(statusSummary.getJt002Now()+ status.getJt002Now());
      statusSummary.setJt001Max(statusSummary.getJt001Max()+ status.getJt001Max());
      statusSummary.setJt001Now(statusSummary.getJt001Now()+ status.getJt001Now());
    }
    return statusSummary;
  }
}
