package com.madeu.crm.callLog.ctrl;

import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.madeu.constants.Constants;
import com.madeu.crm.callLog.dto.CallLogSearchDTO;
import com.madeu.crm.callLog.dto.CallMemoDTO;
import com.madeu.crm.callLog.service.CallLogService;
import com.madeu.crm.callLog.service.GoodArsService;
import com.madeu.util.HttpUtil;

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

@Slf4j
@Controller
@RequestMapping("/callLog")
public class CallLogController {

    @Autowired
    private CallLogService callLogService;

    @Autowired
    private GoodArsService goodArsService;

    /**
     * 통화 로그 관리 화면으로 이동
     */
    @RequestMapping("/moveCallLogList.do")
    public String moveCallLogList(HttpSession session, HttpServletRequest request, HttpServletResponse response,
            Model model) {
        log.debug("CallLogController moveCallLogList START");

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

        try {
            paramMap.put("loginMemberId", String.valueOf(session.getAttribute("loginMemberId")));
            map = callLogService.moveCallLogList(paramMap);
            model.addAttribute("selectUseYn", map.get("selectUseYn"));
            model.addAttribute("insertUseYn", map.get("insertUseYn"));
            model.addAttribute("updateUseYn", map.get("updateUseYn"));
            model.addAttribute("deleteUseYn", map.get("deleteUseYn"));
            model.addAttribute("downloadUseYn", map.get("downloadUseYn"));
        } catch (Exception e) {
            e.printStackTrace();
            return "/web/login/logout";
        }
        log.debug("CallLogController moveCallLogList END");

        return "/web/callLog/callLogSelectList";
    }

    /**
     * 통화 로그 목록 조회 (통계 포함)
     */
    @PostMapping("/getCallLogList.do")
    public ModelAndView getCallLogList(HttpSession session, HttpServletRequest request,
            HttpServletResponse response, CallLogSearchDTO searchDTO) {
        log.debug("CallLogController getCallLogList START");

        HashMap<String, Object> map = new HashMap<>();

        try {
            searchDTO.setLoginMemberId(String.valueOf(session.getAttribute("loginMemberId")));
            map = callLogService.getCallLogList(searchDTO);
        } catch (Exception e) {
            e.printStackTrace();
            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 (null == map.get("msgDesc") || ("").equals(map.get("msgDesc"))) {
                    map.put("msgDesc", "정상적으로 수행되지 않았습니다. 관리자에게 문의하시기 바랍니다.");
                }
            }
        }
        log.debug("CallLogController getCallLogList END");
        return HttpUtil.makeHashToJsonModelAndView(map);
    }

    /**
     * 통화 메모 저장
     */
    @PostMapping("/saveCallMemo.do")
    public ModelAndView saveCallMemo(HttpSession session, HttpServletRequest request,
            HttpServletResponse response, CallMemoDTO memoDTO) {
        log.debug("CallLogController saveCallMemo START");

        HashMap<String, Object> map = new HashMap<>();

        try {
            memoDTO.setLoginMemberId(String.valueOf(session.getAttribute("loginMemberId")));
            map = callLogService.saveCallMemo(memoDTO);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msgCode", Constants.FAIL);
            map.put("msgDesc", "메모 저장 중 오류가 발생하였습니다.");
        }
        log.debug("CallLogController saveCallMemo END");
        return HttpUtil.makeHashToJsonModelAndView(map);
    }

    /**
     * 전화 걸기 (아웃바운드)
     */
    @PostMapping("/makeOutboundCall.do")
    public ModelAndView makeOutboundCall(HttpSession session, HttpServletRequest request,
            HttpServletResponse response) {
        log.debug("CallLogController makeOutboundCall START");

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

        try {
            String loginCid = String.valueOf(paramMap.get("loginCid"));
            String sendCid = String.valueOf(paramMap.get("sendCid"));
            String userCid = String.valueOf(paramMap.get("userCid"));

            map = goodArsService.makeOutboundCall(loginCid, sendCid, userCid);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("msgDesc", "전화 발신 중 오류가 발생하였습니다.");
        }
        log.debug("CallLogController makeOutboundCall END");
        return HttpUtil.makeHashToJsonModelAndView(map);
    }

    /**
     * 전화 돌려주기 (Push)
     */
    @PostMapping("/pushCall.do")
    public ModelAndView pushCall(HttpSession session, HttpServletRequest request,
            HttpServletResponse response) {
        log.debug("CallLogController pushCall START");

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

        try {
            String loginCid = String.valueOf(paramMap.get("loginCid"));
            String pushCid = String.valueOf(paramMap.get("pushCid"));

            map = goodArsService.pushCall(loginCid, pushCid);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("msgDesc", "전화 연결 중 오류가 발생하였습니다.");
        }
        log.debug("CallLogController pushCall END");
        return HttpUtil.makeHashToJsonModelAndView(map);
    }

    /**
     * 녹음 파일 URL 조회
     */
    @PostMapping("/getRecordFileUrl.do")
    public ModelAndView getRecordFileUrl(HttpSession session, HttpServletRequest request,
            HttpServletResponse response) {
        log.debug("CallLogController getRecordFileUrl START");

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

        try {
            String recordNo = String.valueOf(paramMap.get("recordNo"));
            String url = goodArsService.getRecordFileUrl(recordNo);
            map.put("success", true);
            map.put("recordUrl", url);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("msgDesc", "녹음 파일 조회 중 오류가 발생하였습니다.");
        }
        log.debug("CallLogController getRecordFileUrl END");
        return HttpUtil.makeHashToJsonModelAndView(map);
    }
}
