package com.madeu.crm.settings.medicalcategory.ctrl;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.madeu.constants.Constants;
import com.madeu.crm.settings.medicalcategory.dto.MedicalCategoryDTO;
import com.madeu.crm.settings.medicalcategory.service.MedicalCategoryService;
import com.madeu.crm.settings.medicalcategory.service.MedicalDiviProductService;
import com.madeu.init.ManagerDraftAction;
import com.madeu.util.HttpUtil;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/settings/medicalCategory")
public class MedicalCategoryController extends ManagerDraftAction {

    @Autowired
    private MedicalCategoryService medicalCategoryService;

    @Autowired
    private MedicalDiviProductService diviProductService;

    // ==================== 뷰 반환 메서드 ====================

    /**
     * 통합 진료유형 관리 메인 화면 이동
     */
    @RequestMapping("/list.do")
    public ModelAndView selectList(HttpServletRequest request, HttpServletResponse response) {
        log.debug("MedicalCategoryController selectList START");
        log.debug("MedicalCategoryController selectList END");

        // 프론트 설계 4번 항목 경로
        return new ModelAndView("/web/settings/medicalcategory/medicalCategoryList");
    }

    /**
     * 카테고리 1뎁스 팝업 화면 이동 (진료과목)
     */
    @RequestMapping("/infoPopDept1.do")
    public ModelAndView infoPopDept1(HttpServletRequest request, HttpServletResponse response) {
        log.debug("MedicalCategoryController infoPopDept1 START");
        log.debug("MedicalCategoryController infoPopDept1 END");
        return new ModelAndView("/web/settings/medicalcategory/popup/medicalCategoryInfoPopDept1");
    }

    /**
     * 카테고리 2뎁스 팝업 화면 이동 (진료유형)
     */
    @RequestMapping("/infoPopDept2.do")
    public ModelAndView infoPopDept2(HttpServletRequest request, HttpServletResponse response) {
        log.debug("MedicalCategoryController infoPopDept2 START");
        log.debug("MedicalCategoryController infoPopDept2 END");
        return new ModelAndView("/web/settings/medicalcategory/popup/medicalCategoryInfoPopDept2");
    }

    /**
     * 카테고리 3뎁스 팝업 화면 이동 (제품/시술)
     */
    @RequestMapping("/infoPopDept3.do")
    public ModelAndView infoPopDept3(HttpServletRequest request, HttpServletResponse response) {
        log.debug("MedicalCategoryController infoPopDept3 START");
        log.debug("MedicalCategoryController infoPopDept3 END");
        return new ModelAndView("/web/settings/medicalcategory/popup/medicalCategoryInfoPopDept3");
    }

    /**
     * 카테고리 4뎁스 팝업 화면 이동 (용량/출력)
     */
    @RequestMapping("/infoPopDept4.do")
    public ModelAndView infoPopDept4(HttpServletRequest request, HttpServletResponse response) {
        log.debug("MedicalCategoryController infoPopDept4 START");
        log.debug("MedicalCategoryController infoPopDept4 END");
        return new ModelAndView("/web/settings/medicalcategory/popup/medicalCategoryInfoPopDept4");
    }

    /**
     * 카테고리 5뎁스 팝업 화면 이동 (부위)
     */
    @RequestMapping("/infoPopDept5.do")
    public ModelAndView infoPopDept5(HttpServletRequest request, HttpServletResponse response) {
        log.debug("MedicalCategoryController infoPopDept5 START");
        log.debug("MedicalCategoryController infoPopDept5 END");
        return new ModelAndView("/web/settings/medicalcategory/popup/medicalCategoryInfoPopDept5");
    }

    // ==================== API 메서드 (JSON 반환) ====================

    /**
     * 진료유형 트리 리스트 조회
     */
    @PostMapping("/getMedicalCategoryTreeList.do")
    public HashMap<String, Object> getMedicalCategoryTreeList(HttpServletRequest request,
            HttpServletResponse response) {
        log.debug("MedicalCategoryController getMedicalCategoryTreeList START");

        HashMap<String, Object> paramMap = HttpUtil.getParameterMap(request);
        HashMap<String, Object> map = new HashMap<>();

        try {
            map = medicalCategoryService.getMedicalCategoryTreeList(paramMap);
        } catch (Exception e) {
            log.error("getMedicalCategoryTreeList : ", e);
            map.put("msgCode", Constants.FAIL);
            map.put("msgDesc", "서버 오류가 발생했습니다.");
        } finally {
            if (Constants.OK != map.get("msgCode")) {
                map.put("msgCode", Constants.FAIL);
                map.put("success", false);
                if (map.get("msgDesc") == null || "".equals(map.get("msgDesc"))) {
                    map.put("msgDesc", "정보를 불러오는데 실패했습니다. 관리자에게 문의하세요.");
                }
            }
        }
        log.debug("MedicalCategoryController getMedicalCategoryTreeList END");
        return map;
    }

    /**
     * 카테고리 단건 상세 정보 가져오기
     */
    @PostMapping("/getMedicalCategory.do")
    public HashMap<String, Object> getMedicalCategory(HttpServletRequest request, HttpServletResponse response) {
        log.debug("MedicalCategoryController getMedicalCategory START");
        HashMap<String, Object> paramMap = HttpUtil.getParameterMap(request);
        HashMap<String, Object> map = new HashMap<>();

        try {
            map = medicalCategoryService.getMedicalCategory(paramMap);
        } catch (Exception e) {
            log.error("getMedicalCategory : ", e);
            map.put("msgCode", Constants.FAIL);
            map.put("msgDesc", "서버 오류가 발생했습니다.");
        }
        log.debug("MedicalCategoryController getMedicalCategory END");
        return map;
    }

    /**
     * 거래처 목록 조회
     */
    @PostMapping("/getCustList.do")
    public HashMap<String, Object> getCustList(HttpServletRequest request, HttpServletResponse response) {
        log.debug("MedicalCategoryController getCustList START");
        HashMap<String, Object> paramMap = HttpUtil.getParameterMap(request);
        HashMap<String, Object> map = new HashMap<>();

        try {
            map = medicalCategoryService.getCustList(paramMap);
        } catch (Exception e) {
            log.error("getCustList : ", e);
            map.put("msgCode", Constants.FAIL);
            map.put("msgDesc", "서버 오류가 발생했습니다.");
        }
        log.debug("MedicalCategoryController getCustList END");
        return map;
    }

    /**
     * 진료유형 등록
     */
    @PostMapping("/putMedicalCategory.do")
    public HashMap<String, Object> putMedicalCategory(@RequestBody MedicalCategoryDTO dto, HttpServletRequest request) {
        log.debug("MedicalCategoryController putMedicalCategory START");
        HashMap<String, Object> map = new HashMap<>();

        try {
            map = medicalCategoryService.insertMedicalCategory(dto);
        } catch (Exception e) {
            log.error("putMedicalCategory : ", e);
            map.put("msgCode", Constants.FAIL);
            map.put("msgDesc", "서버 오류가 발생했습니다.");
        }
        log.debug("MedicalCategoryController putMedicalCategory END");
        return map;
    }

    /**
     * 진료유형 수정
     */
    @PostMapping("/modMedicalCategory.do")
    public HashMap<String, Object> modMedicalCategory(@RequestBody MedicalCategoryDTO dto, HttpServletRequest request) {
        log.debug("MedicalCategoryController modMedicalCategory START");
        HashMap<String, Object> map = new HashMap<>();

        try {
            map = medicalCategoryService.updateMedicalCategory(dto);
        } catch (Exception e) {
            log.error("modMedicalCategory : ", e);
            map.put("msgCode", Constants.FAIL);
            map.put("msgDesc", "서버 오류가 발생했습니다.");
        }
        log.debug("MedicalCategoryController modMedicalCategory END");
        return map;
    }

    /**
     * 진료유형 삭제
     */
    @PostMapping("/delMedicalCategory.do")
    public HashMap<String, Object> delMedicalCategory(HttpServletRequest request, HttpServletResponse response) {
        log.debug("MedicalCategoryController delMedicalCategory START");
        HashMap<String, Object> paramMap = HttpUtil.getParameterMap(request);
        HashMap<String, Object> map = new HashMap<>();

        try {
            map = medicalCategoryService.deleteMedicalCategory(paramMap);
        } catch (Exception e) {
            log.error("delMedicalCategory : ", e);
            map.put("msgCode", Constants.FAIL);
            map.put("msgDesc", "서버 오류가 발생했습니다.");
        }
        log.debug("MedicalCategoryController delMedicalCategory END");
        return map;
    }

    /**
     * 진료유형 다건 삭제
     */
    @PostMapping("/delMultiMedicalCategory.do")
    public HashMap<String, Object> delMultiMedicalCategory(@RequestBody Map<String, List<String>> body) {
        log.debug("MedicalCategoryController delMultiMedicalCategory START");
        HashMap<String, Object> map = new HashMap<>();

        try {
            List<String> pidList = body.get("pidList");
            if (pidList == null || pidList.isEmpty()) {
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc", "삭제할 항목이 선택되지 않았습니다.");
                return map;
            }
            map = medicalCategoryService.deleteMultiMedicalCategory(pidList);
        } catch (Exception e) {
            log.error("delMultiMedicalCategory : ", e);
            map.put("msgCode", Constants.FAIL);
            map.put("msgDesc", "서버 오류가 발생했습니다.");
        }
        log.debug("MedicalCategoryController delMultiMedicalCategory END");
        return map;
    }

    /**
     * 진료유형 인라인(부분) 수정
     */
    @PostMapping("/updatePartialMedicalCategory.do")
    public HashMap<String, Object> updatePartialMedicalCategory(@RequestBody HashMap<String, Object> paramMap,
            HttpServletRequest request) {
        log.debug("MedicalCategoryController updatePartialMedicalCategory START");
        HashMap<String, Object> map = new HashMap<>();

        try {
            map = medicalCategoryService.updatePartialMedicalCategory(paramMap);
        } catch (Exception e) {
            log.error("updatePartialMedicalCategory : ", e);
            map.put("msgCode", Constants.FAIL);
            map.put("msgDesc", "서버 오류가 발생했습니다.");
        }
        log.debug("MedicalCategoryController updatePartialMedicalCategory END");
        return map;
    }

    /**
     * 진료유형 인라인(부분) 여러건 일괄 수정 (전체보기 저장)
     */
    @PostMapping("/updateBatchMedicalCategory.do")
    public HashMap<String, Object> updateBatchMedicalCategory(@RequestBody List<MedicalCategoryDTO> list,
            HttpServletRequest request) {
        log.debug("MedicalCategoryController updateBatchMedicalCategory START");
        HashMap<String, Object> map = new HashMap<>();

        try {
            map = medicalCategoryService.updateBatchMedicalCategory(list);
        } catch (Exception e) {
            log.error("updateBatchMedicalCategory : ", e);
            map.put("msgCode", Constants.FAIL);
            map.put("msgDesc", "서버 오류가 발생했습니다.");
        }
        log.debug("MedicalCategoryController updateBatchMedicalCategory END");
        return map;
    }

    // ==================== 약품 관련 API ====================

    /**
     * 약품 리스트 조회
     */
    @PostMapping("/getDiviProductList.do")
    public HashMap<String, Object> getDiviProductList(HttpServletRequest request, HttpServletResponse response) {
        log.debug("MedicalCategoryController getDiviProductList START");
        HashMap<String, Object> paramMap = HttpUtil.getParameterMap(request);
        HashMap<String, Object> map = new HashMap<>();

        try {
            map = diviProductService.getDiviProductList(paramMap);
        } catch (Exception e) {
            log.error("getDiviProductList : ", e);
            map.put("msgCode", Constants.FAIL);
            map.put("msgDesc", "서버 오류가 발생했습니다.");
        }
        log.debug("MedicalCategoryController getDiviProductList END");
        return map;
    }

    /**
     * 약품 등록
     */
    @PostMapping("/putDiviProduct.do")
    public HashMap<String, Object> putDiviProduct(@RequestBody HashMap<String, Object> paramMap,
            HttpServletRequest request) {
        log.debug("MedicalCategoryController putDiviProduct START");
        HashMap<String, Object> map = new HashMap<>();

        try {
            map = diviProductService.insertDiviProduct(paramMap);
        } catch (Exception e) {
            log.error("putDiviProduct : ", e);
            map.put("msgCode", Constants.FAIL);
            map.put("msgDesc", "서버 오류가 발생했습니다.");
        }
        log.debug("MedicalCategoryController putDiviProduct END");
        return map;
    }

    /**
     * 약품 삭제
     */
    @PostMapping("/delDiviProduct.do")
    public HashMap<String, Object> delDiviProduct(HttpServletRequest request, HttpServletResponse response) {
        log.debug("MedicalCategoryController delDiviProduct START");
        HashMap<String, Object> paramMap = HttpUtil.getParameterMap(request);
        HashMap<String, Object> map = new HashMap<>();

        try {
            map = diviProductService.deleteDiviProduct(paramMap);
        } catch (Exception e) {
            log.error("delDiviProduct : ", e);
            map.put("msgCode", Constants.FAIL);
            map.put("msgDesc", "서버 오류가 발생했습니다.");
        }
        log.debug("MedicalCategoryController delDiviProduct END");
        return map;
    }

    /**
     * 약품 수정
     */
    @PostMapping("/modDiviProduct.do")
    public HashMap<String, Object> modDiviProduct(@RequestBody HashMap<String, Object> paramMap,
            HttpServletRequest request) {
        log.debug("MedicalCategoryController modDiviProduct START");
        HashMap<String, Object> map = new HashMap<>();

        try {
            map = diviProductService.updateDiviProduct(paramMap);
        } catch (Exception e) {
            log.error("modDiviProduct : ", e);
            map.put("msgCode", Constants.FAIL);
            map.put("msgDesc", "서버 오류가 발생했습니다.");
        }
        log.debug("MedicalCategoryController modDiviProduct END");
        return map;
    }

    /**
     * 약품 일괄 저장 (등록/수정/삭제)
     */

    @PostMapping("/saveDiviProductBatch.do")
    public HashMap<String, Object> saveDiviProductBatch(@RequestBody List<HashMap<String, Object>> list,
            HttpServletRequest request) {
        log.debug("MedicalCategoryController saveDiviProductBatch START");
        HashMap<String, Object> map = new HashMap<>();

        try {
            map = diviProductService.saveDiviProductBatch(list);
        } catch (Exception e) {
            log.error("saveDiviProductBatch : ", e);
            map.put("msgCode", Constants.FAIL);
            map.put("msgDesc", "서버 오류가 발생했습니다.");
        }
        log.debug("MedicalCategoryController saveDiviProductBatch END");
        return map;
    }

    /**
     * 제품(약품) 검색 (MU_PRODUCT 기반)
     */
    @PostMapping("/searchProductList.do")
    public HashMap<String, Object> searchProductList(HttpServletRequest request, HttpServletResponse response) {
        log.debug("MedicalCategoryController searchProductList START");
        HashMap<String, Object> paramMap = HttpUtil.getParameterMap(request);
        HashMap<String, Object> map = new HashMap<>();

        try {
            map = diviProductService.searchProductList(paramMap);
        } catch (Exception e) {
            log.error("searchProductList : ", e);
            map.put("msgCode", Constants.FAIL);
            map.put("msgDesc", "서버 오류가 발생했습니다.");
        }
        log.debug("MedicalCategoryController searchProductList END");
        return map;
    }
}
