package incheon.ags.ias.rst.volu.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 org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import incheon.ags.ias.rst.volu.service.AgsRstVoluService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName : AgsRstVoluController.java
 * @Description : 부동산통계 전월세 거래량 관리 컨트롤러
 *
 * @author : 이주훈
 * @since : 2025. 10. 30
 * @version : 1.0
 *
 */
@Slf4j
@Controller
@RequestMapping("/ags/ias/rst")
@RequiredArgsConstructor
public class AgsRstVoluController {
	
	private final AgsRstVoluService agsRstvoluService;
	
	/**
	 * 전월세 거래량 목록 화면
	 */
	@GetMapping("/voluList.do")
	public String voluList(
	    @RequestParam(defaultValue = "1") int page,
	    @RequestParam(required = false) String year,
	    @RequestParam(required = false) String month,
	    ModelMap model
	) throws Exception {

	    model.addAttribute("headerTitle", "전월세 거래량 관리");

	    // 기준연월 범위 세팅
	    List<Map<String, Object>> crtrYmRange = agsRstvoluService.getCrtrYmRange();
	    if (!crtrYmRange.isEmpty()) {
	        model.addAttribute("crtrYmRange", crtrYmRange);
	        Map<String, Object> last = crtrYmRange.get(0);
	        model.addAttribute("maxYear", last.get("year"));
	        model.addAttribute("maxMonth", last.get("maxmonth"));
	    }

	    // 기본값 처리
	    if (year == null || year.isEmpty()) year = "0000";
	    if (month == null || month.isEmpty()) month = "00";

	    // 검색 기준연월 처리
	    String searchCrtrYm = "";
	    if (!"0000".equals(year)) {
	        if (!"00".equals(month)) {
	            searchCrtrYm = year + month;
	        } else {
	            searchCrtrYm = year;
	        }
	    }

	    // 전체 조회(연도=0000, 월=00)일 경우 조건 제거
	    if ("0000".equals(year) && "00".equals(month)) {
	        searchCrtrYm = "";
	    }

	    // 페이징 설정
	    PaginationInfo paginationInfo = new PaginationInfo();
	    paginationInfo.setCurrentPageNo(page);
	    paginationInfo.setRecordCountPerPage(10);
	    paginationInfo.setPageSize(10);

	    Map<String, Object> param = new HashMap<>();
	    param.put("searchCrtrYm", searchCrtrYm);
	    param.put("firstIndex", paginationInfo.getFirstRecordIndex());
	    param.put("recordCountPerPage", paginationInfo.getRecordCountPerPage());

	    // 기준연월별 조회
	    List<Map<String, Object>> ymList = agsRstvoluService.selectCrtrYmSummary(param);
	    ymList.forEach(m -> System.out.println(m.get("crtrYm")));
	    int totalCount = agsRstvoluService.selectCrtrYmSummaryCnt(param);

	    paginationInfo.setTotalRecordCount(totalCount);

	    model.addAttribute("paginationInfo", paginationInfo);
	    model.addAttribute("voluList", ymList);
	    model.addAttribute("totalCount", totalCount);
	    model.addAttribute("year", year);
	    model.addAttribute("month", month);

	    return "ags/ias/rst/volu/voluList";
	}

	@GetMapping("/getMonthsByYear.do")
	@ResponseBody
	public List<String> getMonthsByYear(String year) {
		return agsRstvoluService.getMonthsByYear(year);
	}
	
	/**
	 * 전월세 거래량 등록 화면
	 */
	@GetMapping("/voluRegist.do")
	public String voluRegist(ModelMap model) {
	    model.addAttribute("headerTitle", "전월세 거래량 등록");

	    List<Map<String, Object>> crtrYmRange = agsRstvoluService.getCrtrYmRange();
	    if (!crtrYmRange.isEmpty()) {
	        model.addAttribute("crtrYmRange", crtrYmRange);
	        Map<String, Object> last = crtrYmRange.get(0);
	        model.addAttribute("maxYear", last.get("year"));
	        model.addAttribute("maxMonth", last.get("maxmonth"));
	    }

	    return "ags/ias/rst/volu/voluRegist";
	}
	
    /**
     * 전월세 거래량 등록 처리
     */
	@PostMapping("/insertVolu.do")
	@ResponseBody
	public Map<String, Object> insertVoluBulk(HttpServletRequest request) {
	    Map<String, Object> result = new HashMap<>();
	    try {
	    	String crtrYm = request.getParameter("crtrYm");
	        String[] sggs = request.getParameterValues("sttySggCdList");
	        String[] hsTypes = request.getParameterValues("hsTypeSeCdList");
	        String[] nocs = request.getParameterValues("dlngNocsList");

	        result = agsRstvoluService.processVoluBulk("insert", crtrYm, sggs, hsTypes, nocs);
	    } catch (DataAccessException e) {
	        log.error("전월세 거래량 등록 중 DB 오류 발생");
	        result.put("success", false);
	        result.put("msg", "데이터베이스 저장 중 오류가 발생했습니다.");
	    } catch (NullPointerException e) {
	        log.error("전월세 거래량 등록 중 필수 데이터 누락 발생");
	        result.put("success", false);
	        result.put("msg", "입력 데이터가 올바르지 않습니다.");
	    } 
	    
	    return result;
	}

	/**
	 * 전월세 거래량 수정 화면
	 */
	@GetMapping("/voluModify.do")
	public String voluModify(@RequestParam String crtrYm, ModelMap model) {

	    model.addAttribute("headerTitle", "전월세 거래량 수정");

	    List<Map<String, Object>> crtrYmRange = agsRstvoluService.getCrtrYmRange();
	    model.addAttribute("crtrYmRange", crtrYmRange);

	    // 기준연도, 월 분리
	    String year = crtrYm.substring(0, 4);
	    String month = crtrYm.length() >= 6 ? crtrYm.substring(4, 6) : "00";
	    model.addAttribute("crtrYear", year);
	    model.addAttribute("crtrMonth", month);

	    // 수정용 매트릭스 데이터 조회
	    List<Map<String, Object>> voluMatrix = agsRstvoluService.selectVoluMatrix(crtrYm);
	    model.addAttribute("voluMatrix", voluMatrix);

	    return "ags/ias/rst/volu/voluModify";
	}
    
	/**
	 * 전월세 거래량 일괄 수정 처리
	 */
	@PostMapping("/updateVolu.do")
	@ResponseBody
	public Map<String, Object> updateVoluBulk(HttpServletRequest request) {
		Map<String, Object> result = new HashMap<>();
	    try {
	    	String crtrYm = request.getParameter("crtrYm");
	        String[] sggs = request.getParameterValues("sttySggCdList");
	        String[] hsTypes = request.getParameterValues("hsTypeSeCdList");
	        String[] nocs = request.getParameterValues("dlngNocsList");
	        
	        return agsRstvoluService.processVoluBulk("update", crtrYm, sggs, hsTypes, nocs);
	    } catch (DataAccessException e) {
	        log.error("전월세 거래량 수정 중 DB 오류 발생");
	        result.put("success", false);
	        result.put("msg", "데이터베이스 수정 중 오류가 발생했습니다.");
	    } 
	    
	    return result;
	}
    
    /**
     * 전월세 거래량 상세 화면
     */
    @GetMapping("/voluDetail.do")
    public String voluDetail(@RequestParam(required = false) String crtrYm, ModelMap model) {

        model.addAttribute("headerTitle", "전월세 거래량 상세정보");

        if (crtrYm == null || crtrYm.trim().isEmpty()) {
            model.addAttribute("msg", "기준연월이 전달되지 않았습니다.");
            return "redirect:/ags/ias/rst/voluList.do";
        }

        String year = "";
        String month = "";
        if (crtrYm.length() >= 4) {
            year = crtrYm.substring(0, 4);
            if (crtrYm.length() >= 6) month = crtrYm.substring(4, 6);
        }

        model.addAttribute("crtrYear", year);
        model.addAttribute("crtrMonth", month);

        // 기준연월 범위
        List<Map<String, Object>> crtrYmRange = agsRstvoluService.getCrtrYmRange();
        model.addAttribute("crtrYmRange", crtrYmRange);

        // 군·구 주택유형 매트릭스
        List<Map<String, Object>> voluMatrix = agsRstvoluService.selectVoluMatrix(crtrYm);
        model.addAttribute("voluMatrix", voluMatrix);

        return "ags/ias/rst/volu/voluDetail";
    }
    
    /**
     * 삭제 
     */
    @DeleteMapping("/deleteVolu.do/{crtrYm}")
    @ResponseBody
    public Map<String, Object> deleteVolu(@PathVariable("crtrYm") String crtrYm) {
        Map<String, Object> result = new HashMap<>();
        try {
            agsRstvoluService.deleteVolu(crtrYm);
            result.put("success", true);
            result.put("message", "[" + crtrYm + "] 전체 데이터가 삭제되었습니다.");
        } catch (DataAccessException e) {
            log.error("전월세 거래량 삭제 중 DB 오류 발생 (crtrYm={})", crtrYm);
            result.put("success", false);
            result.put("message", "데이터베이스 삭제 처리 중 오류가 발생했습니다.");
        }
        
        return result;
    }
    
}
    
