package incheon.ags.dss.report.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.egovframe.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
import incheon.com.cmm.api.DefaultApiResponse;
// import incheon.com.cmm.util.RequestContext;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import incheon.ags.dss.report.service.SimRptpService;
import incheon.ags.dss.report.vo.SimRptpMstVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 보고서(SimRptp) 기능의 JSON 데이터를 반환하는 API 컨트롤러 (CRD)
 */
@RestController 
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/api/v1/dss/sim/rptp")
public class SimRptpApiController {

    private final SimRptpService simRptpService;

    //TODO 프론트 무한 스크롤
    /**
     * 보고서 이력 목록(Mst) 데이터 조회 (JSON)
     */
    @GetMapping("/list.do")
    public ResponseEntity<DefaultApiResponse> getSimRptpList(
            @ModelAttribute SimRptpMstVO searchVO) throws Exception {
        
        PaginationInfo paginationInfo = new PaginationInfo();
        paginationInfo.setCurrentPageNo(searchVO.getPageIndex());
        paginationInfo.setRecordCountPerPage(searchVO.getRecordCountPerPage());//5
        paginationInfo.setPageSize(searchVO.getPageSize());//10

        searchVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
        // searchVO.setLOGIN_USER_ID(RequestContext.getCurrentUserId());

        List<SimRptpMstVO> list = simRptpService.selectSimRptpList(searchVO);
        int totalCount = simRptpService.selectSimRptpListCnt(searchVO);
        paginationInfo.setTotalRecordCount(totalCount);
        
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("paging", paginationInfo);
        
        return ResponseEntity.ok(DefaultApiResponse.success(result, "조회되었습니다."));
    }
    
    /** * 생성 팝업용 후보군 조회 (페이징 적용) 
     * - 각 탭별(통계, 진단 등) 데이터와 총 건수를 반환
     */
    @GetMapping("/candidates.do")
    public ResponseEntity<DefaultApiResponse> getCandidates(@ModelAttribute SimRptpMstVO searchVO) throws Exception {
        
        // 1. 페이징 정보 설정 (기본값 처리)
        PaginationInfo paginationInfo = new PaginationInfo();
        paginationInfo.setCurrentPageNo(searchVO.getPageIndex());
        paginationInfo.setRecordCountPerPage(searchVO.getRecordCountPerPage() > 0 ? searchVO.getRecordCountPerPage() : 5); // 팝업이므로 5건씩
        paginationInfo.setPageSize(searchVO.getPageSize());

        searchVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
        searchVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());

        // 2. 서비스 호출 (VO 전달)
        Map<String, Object> result = simRptpService.selectReportCandidates(searchVO);
        
        // 페이징 정보도 함께 내려줄 수 있음 (필요 시)
        // result.put("paginationInfo", paginationInfo);

        return ResponseEntity.ok(DefaultApiResponse.success(result, "조회되었습니다."));
    }
    
    //TODO: 보고서 형식으로 jsp호출 -> pdf 다운로드 지원식으로
    /**
     * 보고서 상세(Mst + Dtl) 데이터 조회 (JSON)
     */
    @GetMapping("/view.do")
    public ResponseEntity<DefaultApiResponse> getSimRptpDetail(@RequestParam("rptpNo") String rptpNo) throws Exception {
        SimRptpMstVO resultSet = simRptpService.selectSimRptpDetail(SimRptpMstVO.builder().rptpNo(rptpNo).build());
        
        return ResponseEntity.ok(DefaultApiResponse.success(resultSet, "조회되었습니다."));
    }

    //TODO: 보고서 형식 표시 가능하게 저장
    /**
     * 신규 보고서 생성 (JSON)
     */
    @PostMapping("/save.do") // (CRD 기능이므로 'Create'만 담당)
    public ResponseEntity<DefaultApiResponse> saveSimRptp(
            @RequestBody SimRptpMstVO vo,
            HttpServletRequest request) throws Exception {
        
        // ServiceImpl에서 Mst 등록 -> Dtl 등록 (트랜잭션)
        String rptpNo = simRptpService.insertSimRptp(vo);
        
        Map<String, Object> result = new HashMap<>();
        result.put("rptpNo", rptpNo);
        
        return ResponseEntity.ok(DefaultApiResponse.success(result, "생성되었습니다."));
    }

    /**
     * 보고서 삭제 (JSON)
     */
    @PostMapping("/delete.do")
    public ResponseEntity<DefaultApiResponse> deleteSimRptp(
    		@RequestBody SimRptpMstVO vo,
            HttpServletRequest request) throws Exception {
        simRptpService.deleteSimRptp(vo);
        
        return ResponseEntity.ok(DefaultApiResponse.success(null, "삭제되었습니다."));
    }
}