package cokr.xit.ens.modules.nvsigntalk.presentation;

import cokr.xit.ens.core.aop.EnsResponseVO;
import cokr.xit.ens.core.exception.EnsException;
import cokr.xit.ens.core.exception.code.EnsErrCd;
import cokr.xit.ens.core.utils.CmmnUtil;
import cokr.xit.ens.modules.common.ctgy.mblpage.domain.SendDetailMblPage;
import cokr.xit.ens.modules.common.ctgy.mblpage.domain.ids.SendDetailMblPageIds;
import cokr.xit.ens.modules.common.ctgy.mblpage.domain.repository.SendDetailMblPageRepository;
import cokr.xit.ens.modules.common.ctgy.mblpage.presentation.MblPageControllerSupport;
import cokr.xit.ens.modules.nvsigntalk.domain.SendDetailNvSigntalk;
import cokr.xit.ens.modules.nvsigntalk.domain.repository.SendDetailNvSigntalkRepository;
import cokr.xit.ens.modules.nvsigntalk.service.NvSigntalkService;
import com.google.gson.Gson;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

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

@Tag(name = "NvSigntalkMblPageController")
@Slf4j
@RequiredArgsConstructor
@Controller
public class NvSigntalkMblPageController extends MblPageControllerSupport {

    private final NvSigntalkService nvSigntalkService;
    private final SendDetailNvSigntalkRepository sendDetailNvSigntalkRepository;
    private final SendDetailMblPageRepository sendDetailMblPageRepository;



//    @Parameters({
//            @Parameter(in = ParameterIn.QUERY, name = "nonce"),
//            @Parameter(in = ParameterIn.QUERY, name = "docId"),
//            @Parameter(in = ParameterIn.QUERY, name = "clientDocId"),
//    })
    @GetMapping(value = "/nv/signtalk/page/prnt")
    public String mblPagePrnt(@RequestParam Map<String, String> mParam, ModelMap model) {
        final String nonce = mParam.get("nonce");
        final String docId = mParam.get("docId");
        final String clientDocId = mParam.get("clientDocId");


        try {
            if (CmmnUtil.isEmpty(nonce) && CmmnUtil.isEmpty(docId) && CmmnUtil.isEmpty(clientDocId))
                throw new EnsException(EnsErrCd.ERR410, "정상적인 요청이 아닙니다. 재인증 후 시도하시기 바랍니다.");
            SendDetailNvSigntalk sendDetail = sendDetailNvSigntalkRepository.findFetchByClientDocIdAndDocId(clientDocId, docId)
                    .orElseThrow(() -> new EnsException(EnsErrCd.ERR404, "문서를 찾을 수 없습니다."));


            EnsResponseVO responseVO = nvSigntalkService.tokenVerify(sendDetail.getSendMast().getOrgCd(), docId, nonce, clientDocId);
            if (!EnsErrCd.OK.equals(responseVO.getErrCode()))
                throw new EnsException(responseVO.getErrCode(), responseVO.getErrMsg());


            SendDetailNvSigntalk sendDetailNvSigntalk = sendDetailNvSigntalkRepository.findByClientDocIdAndDocId(clientDocId, docId)
                    .orElseThrow(() -> new EnsException(EnsErrCd.ERR404, String.format("일치하는 자료가 없습니다. [ docId %s clientDocId %s ]", docId, clientDocId)));

            SendDetailMblPage sendDetailMblPage = sendDetailMblPageRepository.findById(SendDetailMblPageIds.builder()
                            .postSe(sendDetailNvSigntalk.getSendMast().getPostSe().getCode())
                            .sendDetailId(sendDetailNvSigntalk.getSendDetailId())
                            .build())
                    .orElseThrow(() -> new EnsException(EnsErrCd.ERR404, String.format("일치하는 페이지데이터가 없습니다. [ docId %s clientDocId %s ]", docId, clientDocId)));

            if (CmmnUtil.isEmpty(sendDetailMblPage.getDetails()))
                throw new EnsException(EnsErrCd.ERR401, String.format("details 필드 값이 비어있습니다. [ docId %s clientDocId %s ]", docId, clientDocId));

            model.put("details", sendDetailMblPage.getDetails());
            
            if ("Y".equals(sendDetailNvSigntalk.getMkBillUseYn())) {
                model.put("payBtnInf", getJsonPayBtnInf(sendDetailNvSigntalk.getBill(), sendDetailNvSigntalk.getSendMast()));
            }


        } catch (EnsException e) {
            model.put("errCode", e.getErrCd());
            model.put("errMsg", e.getMessage());
            model.put("details", "{}");
        }

        return "modules/mblpage/notiprnt";
    }


//    @GetMapping(value = "/nv/signtalk/page/prnt/test/{sendDetailId}")
//    public String mblPagePrnt(@PathVariable Long sendDetailId, ModelMap model) {
//
////		Optional<SendDetailNvSigntalkMblPage> SendDetailNvSigntalkMblPage = sendDetailMblPageRepository.findById(sendDetailId);
//        Optional<SendDetailMblPage> sendDetailMblPage = sendDetailMblPageRepository.findById(SendDetailMblPageIds.builder()
//                .postSe(PostSeCd.nvSigntalk.getCode())
//                .sendDetailId(sendDetailId)
//                .build());
//
//        model.put("details", sendDetailMblPage.isPresent() ? sendDetailMblPage.get().getDetails() : "{}");
//        model.put("errCode", EnsErrCd.OK);
//        model.put("errMsg", EnsErrCd.OK.getCodeNm());
//
//
//        return "modules/mblpage/notiprnt";
//    }
}
