package com.dbnt.faisp.main.faStatistics.internationalCrimeArrest;

import com.dbnt.faisp.main.authMgt.service.AuthMgtService;
import com.dbnt.faisp.main.codeMgt.model.CodeMgt;
import com.dbnt.faisp.main.codeMgt.service.CodeMgtService;
import com.dbnt.faisp.main.faStatistics.internationalCrimeArrest.model.InternationalCrimeArrest;
import com.dbnt.faisp.main.faStatistics.internationalCrimeArrest.repository.SuspectPersonInfoRepository;
import com.dbnt.faisp.main.faStatistics.internationalCrimeArrest.service.InternationalCrimeArrestService;
import com.dbnt.faisp.main.organMgt.model.OrganConfig;
import com.dbnt.faisp.main.organMgt.service.OrganConfigService;
import com.dbnt.faisp.main.userInfo.model.UserInfo;
import com.dbnt.faisp.util.Excel;
import com.dbnt.faisp.util.ParamMap;
import com.dbnt.faisp.util.Utils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/faStatistics")
public class InternationalCrimeArrestController {

    private final AuthMgtService authMgtService;
    private final InternationalCrimeArrestService internationalCrimeArrestService;
    private final CodeMgtService codeMgtService;
    private final OrganConfigService organConfigService;
    private final SuspectPersonInfoRepository suspectPersonInfoRepository;

    @GetMapping("/internationalCrimeArrest")
    public ModelAndView internationalCrimeArrest(@AuthenticationPrincipal UserInfo loginUser,InternationalCrimeArrest internationalCrimeArrest) {
        ModelAndView mav = new ModelAndView("faStatistics/internationalCrimeArrest/internationalCrimeArrest");

        //메뉴권한 확인
        String accessAuth = authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/faStatistics/internationalCrimeArrest").get(0).getAccessAuth();

        mav.addObject("accessAuth", accessAuth);
        mav.addObject("mgtOrganList", loginUser.getDownOrganCdList());

        internationalCrimeArrest.setQueryInfo();
        List<InternationalCrimeArrest> internationalCrimeArrestList = internationalCrimeArrestService.selectInternationalCrimeArrestList(internationalCrimeArrest);

        for (InternationalCrimeArrest ica:internationalCrimeArrestList) {
            ica.setSuspectPersonInfoList(suspectPersonInfoRepository.findByIcaKey(ica.getIcaKey()));
        }

        mav.addObject("internationalCrimeArrestList", internationalCrimeArrestList);
        internationalCrimeArrest.setContentCnt(internationalCrimeArrestService.selectInternationalCrimeArrestListCnt(internationalCrimeArrest));
        internationalCrimeArrest.setPaginationInfo();
        mav.addObject("organConfigList", selectOrganList());
        mav.addObject("searchParams", internationalCrimeArrest);
        return mav;
    }

    @GetMapping("/internationalCrimeArrest/internationalCrimeArrestEditModal")
    public ModelAndView internationalCrimeArrestEditModal(@AuthenticationPrincipal UserInfo loginUser, InternationalCrimeArrest internationalCrimeArrest){
        ModelAndView mav = new ModelAndView("faStatistics/internationalCrimeArrest/internationalCrimeArrestEditModal");
        if(internationalCrimeArrest.getIcaKey()!=null){
            internationalCrimeArrest = internationalCrimeArrestService.selectInternationalCrimeArrest(internationalCrimeArrest.getIcaKey());
        }else{
            internationalCrimeArrest.setWrtOrgan(loginUser.getOgCd());
            internationalCrimeArrest.setWrtNm(loginUser.getUserNm());
            internationalCrimeArrest.setWrtDt(LocalDateTime.now());
            internationalCrimeArrest.setSuspectPersonInfoList(suspectPersonInfoRepository.findByIcaKey(internationalCrimeArrest.getIcaKey()));
        }
        mav.addObject("organConfigList", selectOrganList());
        mav.addObject("internationalCrimeArrest", internationalCrimeArrest);
        return mav;
    }

    @GetMapping("/internationalCrimeArrest/internationalCrimeArrestViewModal")
    public ModelAndView internationalCrimeArrestViewModal(@AuthenticationPrincipal UserInfo loginUser, InternationalCrimeArrest internationalCrimeArrest){
        ModelAndView mav = new ModelAndView("faStatistics/internationalCrimeArrest/internationalCrimeArrestViewModal");
        internationalCrimeArrest = internationalCrimeArrestService.selectInternationalCrimeArrest(internationalCrimeArrest.getIcaKey());
        mav.addObject("internationalCrimeArrest", internationalCrimeArrest);
        mav.addObject("userSeq",loginUser.getUserSeq());
        mav.addObject("organConfigList", selectOrganList());
        //메뉴권한 확인
        mav.addObject("accessAuth", authMgtService.selectAccessConfigList(loginUser.getUserSeq(), "/faStatistics/internationalCrimeArrest").get(0).getAccessAuth());
        return mav;
    }

    @PostMapping("/internationalCrimeArrest/saveInternationalCrimeArrest")
    public Integer saveInternationalCrimeArrest(@AuthenticationPrincipal UserInfo loginUser,
                                                InternationalCrimeArrest internationalCrimeArrest){
        internationalCrimeArrest.setWrtUserSeq(loginUser.getUserSeq());
        return internationalCrimeArrestService.savedInternationalCrimeArrest(internationalCrimeArrest);
    }

    @GetMapping("/internationalCrimeArrest/ExcelDown")
    public void icaExcelDown(HttpServletResponse response, InternationalCrimeArrest internationalCrimeArrest) {
        int duplicateCount = internationalCrimeArrestService.icaDuplicateCount(internationalCrimeArrest);
        int rowCnt = internationalCrimeArrest.getRowCnt() + duplicateCount;
        internationalCrimeArrest.setRowCnt(rowCnt);
        internationalCrimeArrest.setQueryInfo();
        internationalCrimeArrest.setContentCnt(internationalCrimeArrestService.selectInternationalCrimeArrestListCnt(internationalCrimeArrest));
        internationalCrimeArrest.setPaginationInfo();

        Excel excel = new Excel();
        String[] headers = {"ica_key", "case_num", "organ", "department", "crime_type", "violation_type", "crime_name", "occur_table", "arrest_table", "suspect_table", "sex", "age", "country", "crime_awareness_dt", "case_sent_dt", "process_result"};
        String[] headerNames = { "", "", "", "", "", "", "", "", "", "", "피의자 인적사항", "", "", "", "", ""};
        String[] headerNames2 = { "", "사건번호", "지방청", "경찰서", "범죄테마", "위반유형", "죄명", "발생원표", "검거원표", "피의자원표","성별","나이","국적","범죄인지","사건송치","신병처리"};
        String[] columnType = { "int", "String", "String", "String", "String", "String", "String", "String", "String", "String","String","String","String","String","String","String"};
        excel.setHeaders(headers);
        excel.setHeaderNames(headerNames);
        excel.setHeaderNames2(headerNames2);
        excel.setColumnType(columnType);
        excel.setSheetName("국제범죄검거현황");
        excel.setExcelFileName("국제범죄검거현황");
        List<ParamMap> icaList =  internationalCrimeArrestService.selectInternationalCrimeArrestParamList(internationalCrimeArrest);
        excel.setList(icaList);

        try {
            Utils.icaDownExcel(response, excel);
        } catch (IOException e) {

        }
    }

    public List<OrganConfig> selectOrganList(){
        List<CodeMgt> organCdList = codeMgtService.selectCodeMgtList("OG", "");
        List<OrganConfig> organConfigList = organConfigService.selectSavedOrganList();
        for(CodeMgt organCode: organCdList){
            if(!organCode.getItemCd().equals("OG001")){
                boolean usedFlag = false;
                for(OrganConfig organConfig: organConfigList){
                    if(organCode.getItemCd().equals(organConfig.getOrganCd())){
                        usedFlag = true;
                        organConfig.setOrganNm(organCode.getItemValue());
                        organConfig.setUseState("T");
                        break;
                    }
                }
                if(!usedFlag){
                    OrganConfig organConfig = new OrganConfig();
                    organConfig.setOrganCd(organCode.getItemCd());
                    organConfig.setOrganNm(organCode.getItemValue());
                    organConfig.setUseState("F");
                    organConfigList.add(organConfig);
                }
            }
        }
        return organConfigList;
    }
}
