package incheon.ags.cms.history.web;


import com.fasterxml.jackson.databind.JsonNode;
import incheon.ags.cms.admin.vo.RouteVO;
import incheon.ags.cms.history.service.HistoryService;
import incheon.com.cmm.ComDefaultVO;
import incheon.com.cmm.api.DefaultApiResponse;
import lombok.RequiredArgsConstructor;
import org.egovframe.rte.psl.dataaccess.util.EgovMap;
import org.egovframe.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api/v1/cms/history")
@RequiredArgsConstructor
public class HistoryApiController {

    private final HistoryService historyService;

    private static final Logger LOGGER = LoggerFactory.getLogger(HistoryApiController.class);

    /**
     *
     * 청소차량 운행기록 통계 목록 조회
     *
     * @param vhrno
     * @param beginYmd
     * @param endYmd
     * @param tmzs
     * @return 차량 운행기록 통계 목록
     * @throws Exception
     */
    @GetMapping("/getVehiclesSummaryList")
    @ResponseBody
    public ResponseEntity<DefaultApiResponse<Map<String, Object>>> getVehiclesSummaryList(
            @RequestParam(required = false) String vhrno, @RequestParam(required = false) String clnTypeCd,
            @RequestParam(required = false) String ogdpSggCd, @RequestParam String beginYmd, @RequestParam String endYmd,
            @RequestParam(required = false) List<Integer> tmzs, @RequestParam(defaultValue = "1") int pageIndex) throws Exception {

        Map<String, Object> response = new HashMap<>();
        ComDefaultVO comVO = new ComDefaultVO();

        int recordCountPerPage = 5; // comVO.getRecordCountPerPage()

        PaginationInfo paginationInfo = new PaginationInfo();
        paginationInfo.setCurrentPageNo(pageIndex);
        paginationInfo.setRecordCountPerPage(recordCountPerPage);
        paginationInfo.setPageSize(comVO.getPageSize());

        Map<String, Object> params = new EgovMap();
        params.put("vhrno", vhrno);
        params.put("clnTypeCd", clnTypeCd);
        params.put("ogdpSggCd", ogdpSggCd);
        params.put("beginYmd", beginYmd);
        params.put("endYmd", endYmd);
        params.put("timezoneList", tmzs);
        params.put("recordCountPerPage", paginationInfo.getRecordCountPerPage());
        params.put("firstIndex", paginationInfo.getFirstRecordIndex());

        // 차량별 운행기록 통계 건수
        int totalCount = historyService.selectVehiclesSummaryTotalCount(params);
        paginationInfo.setTotalRecordCount(totalCount);

        // 차량별 운행기록 통계 목록
        List<EgovMap> summaryList = historyService.selectVehiclesSummaryList(params);

        response.put("success", true);
        response.put("message", "차량별 운행기록 통계 조회가 완료되었습니다.");
        response.put("totalCount", totalCount);
        response.put("paginationInfo", paginationInfo);
        response.put("results", summaryList);
        LOGGER.info(response.get("message").toString());
        return ResponseEntity.ok(DefaultApiResponse.success(response));
    }

    /**
     *
     * 청소차량 일일 운행기록 목록 조회
     *
     * @param vhclId
     * @param beginYmd
     * @param endYmd
     * @param tmzs
     * @return 차량 일일 운행기록 목록
     * @throws Exception
     */
    @GetMapping("/getVehicleDailyRecordList")
    @ResponseBody
    public ResponseEntity<DefaultApiResponse<Map<String, Object>>> getVehicleDailyRecordList (
            @RequestParam int vhclId, @RequestParam String beginYmd, @RequestParam String endYmd,
            @RequestParam(required = false) List<Integer> tmzs, @RequestParam(defaultValue = "1") int pageIndex) throws Exception {

        Map<String, Object> response = new HashMap<>();

        ComDefaultVO comVO = new ComDefaultVO();

        int recordCountPerPage = 5; // comVO.getRecordCountPerPage()

        PaginationInfo paginationInfo = new PaginationInfo();
        paginationInfo.setCurrentPageNo(pageIndex);
        paginationInfo.setRecordCountPerPage(recordCountPerPage);
        paginationInfo.setPageSize(comVO.getPageSize());

        Map<String, Object> params = new EgovMap();
        params.put("vhclId", vhclId);
        params.put("beginYmd", beginYmd);
        params.put("endYmd", endYmd);
        params.put("timezoneList", tmzs);
        params.put("recordCountPerPage", paginationInfo.getRecordCountPerPage());
        params.put("firstIndex", paginationInfo.getFirstRecordIndex());

        // 일일 운행기록 건수
        int totalCount = historyService.selectVehicleDailyRecordTotalCount(params);
        paginationInfo.setTotalRecordCount(totalCount);

        // 일일 운행기록 목록
        List<EgovMap> dailyRecordList = historyService.selectVehicleDailyRecordList(params);

        response.put("success", true);
        response.put("message", "일일 운행기록 목록 조회가 완료되었습니다.");
        response.put("totalCount", totalCount);
        response.put("paginationInfo", paginationInfo);
        response.put("results", dailyRecordList);
        LOGGER.info(response.get("message").toString());
        return ResponseEntity.ok(DefaultApiResponse.success(response));
    }

    /**
     *
     * 청소차량 일일 운행경로 조회
     *
     * @param vhclId
     * @param oprYmd
     * @param tmzs
     * @return 차량 운행경로 + 차량 노선 목록(해당일자)
     * @throws Exception
     */
    @GetMapping("/getVehicleDrivePathAndRoute")
    @ResponseBody
    public ResponseEntity<DefaultApiResponse<Map<String, Object>>> getVehicleDrivePathAndRoute (
            @RequestParam(required = false) int vhclId, @RequestParam String oprYmd, @RequestParam(required = false) List<Integer> tmzs) throws Exception {

        Map<String, Object> response = new HashMap<>();

        Map<String, Object> params = new EgovMap();
        params.put("vhclId", vhclId);
        params.put("oprYmd", oprYmd);
        params.put("timezoneList", tmzs);

        // 운행경로, 해당일자 노선 목록 조회
        JsonNode drivePath = historyService.selectVehicleDrivePath(params);
        List<RouteVO> routeList = historyService.selectMappingRouteList(params);

        Map<String, Object> results = new HashMap<>();
        results.put("drivePath", drivePath);
        results.put("routeList", routeList);

        response.put("success", true);
        response.put("message", "운행경로 및 해당일자 노선 목록 조회가 완료되었습니다.");
        response.put("results", results);
        LOGGER.info(response.get("message").toString());
        return ResponseEntity.ok(DefaultApiResponse.success(response));
    }

    /**
     *
     * 청소차량 운행기록 통계 엑셀 다운로드
     *
     * @param vhrno
     * @param beginYmd
     * @param endYmd
     * @param tmzs
     * @return 차량 운행기록 통계 엑셀 다운로드
     * @throws Exception
     */
    @GetMapping("/excelDownloadVehiclesSummaryList")
    @ResponseBody
    public ResponseEntity<Resource> excelDownloadVehiclesSummaryList(
            @RequestParam(required = false) String vhrno, @RequestParam(required = false) String clnTypeCd,
            @RequestParam(required = false) String ogdpSggCd, @RequestParam String beginYmd, @RequestParam String endYmd,
            @RequestParam(required = false) List<Integer> tmzs) throws Exception {

        Map<String, Object> params = new EgovMap();
        params.put("vhrno", vhrno);
        params.put("clnTypeCd", clnTypeCd);
        params.put("ogdpSggCd", ogdpSggCd);
        params.put("beginYmd", beginYmd);
        params.put("endYmd", endYmd);
        params.put("timezoneList", tmzs);

        return historyService.excelDownloadVehiclesSummaryList(params);
    }

    /**
     *
     * 청소차량 일일 운행기록 엑셀 다운로드
     *
     * @param vhclId
     * @param beginYmd
     * @param endYmd
     * @param tmzs
     * @return 차량 일일 운행기록 엑셀 다운로드
     * @throws Exception
     */
    @GetMapping("/excelDownloadVehicleDailyRecordList")
    @ResponseBody
    public ResponseEntity<Resource> excelDownloadVehicleDailyRecordList(
            @RequestParam int vhclId, @RequestParam String vhrno, @RequestParam String beginYmd,
            @RequestParam String endYmd, @RequestParam(required = false) List<Integer> tmzs) throws Exception {

        Map<String, Object> params = new EgovMap();
        params.put("vhclId", vhclId);
        params.put("vhrno", vhrno);
        params.put("beginYmd", beginYmd);
        params.put("endYmd", endYmd);
        params.put("timezoneList", tmzs);

        return historyService.excelDownloadVehicleDailyRecordList(params);
    }

    /**
     *
     * 청소차량 통계지도용 증분 데이터 조회
     *
     * @param oprYmd
     * @return 통계지도용 증분 데이터 목록
     * @throws Exception
     */
    @GetMapping("/getCleaningIncrsData")
    @ResponseBody
    public ResponseEntity<DefaultApiResponse<Map<String, Object>>> getCleaningIncrsData(
            @RequestParam String oprYmd, @RequestParam(required = false) String beginTimezone,
            @RequestParam(required = false) String endTimezone, @RequestParam(required = false) String clnTypeCd) throws Exception {

        Map<String, Object> response = new HashMap<>();

        Map<String, Object> params = new EgovMap();
        params.put("oprYmd", oprYmd);
        params.put("beginTimezone", beginTimezone);
        params.put("endTimezone", endTimezone);
        params.put("clnTypeCd", clnTypeCd);

        // 통계지도용 증분 데이터 목록
        List<EgovMap> cleaningIncrsData = historyService.selectCleaningIncrsData(params);

        response.put("success", true);
        response.put("message", "통계지도용 증분 데이터 조회가 완료되었습니다.");
        response.put("results", cleaningIncrsData);
        LOGGER.info(response.get("message").toString());
        return ResponseEntity.ok(DefaultApiResponse.success(response));
    }

}
