package cokr.xit.ens.modules.common.ctgy.intgrnbill.nv.presentation;

import cokr.xit.ens.core.exception.EnsException;
import cokr.xit.ens.core.exception.code.EnsErrCd;
import cokr.xit.ens.modules.common.ctgy.intgrnbill.nv.service.NvPayProcessService;
import cokr.xit.ens.modules.common.ctgy.intgrnbill.support.code.PayUseSysResCd;
import cokr.xit.ens.modules.common.ctgy.intgrnbill.support.model.PayApiRespDTO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Tag(name = "NvPaymentPageController")
@Slf4j
@RequiredArgsConstructor
@Controller
public class NvPaymentPageController {
    private final NvPayProcessService nvPayProcessService;

    @GetMapping(value = "/bill/nv/ep/test/page")
    public String nvEpTestPage(ModelMap model) {

        return "modules/bill/nvEpTest";
    }

    @Parameter(name = "flag", example = "ok", in = ParameterIn.PATH)
    @Operation(summary = "네이버페이 납부(결제)결과 테스트페이지 출력")
    @GetMapping(value = "/bill/nv/ep/test/rslt/prnt/{flag}")
    public String nvEpTestRsltPrnt(@PathVariable String flag, ModelMap modelMap) throws JsonProcessingException {
        Gson gson = new Gson();

        if ("ok".equals(flag)) {
            Map<String, Object> param = gson.fromJson("{\"code\":\"Success\",\"message\":\"성공\",\"body\":{\"paymentId\":\"20230206NP1041083209\",\"detail\":{\"paymentId\":\"20230206NP1041083209\",\"payHistId\":\"20230206NP1041083231\",\"merchantName\":\"민자도로 관리지원센터_테스트\",\"merchantId\":\"np_mtbfw423545\",\"merchantPayKey\":\"gamengUserKey-00001\",\"merchantUserKey\":\"gamengUserKey-00001\",\"admissionTypeCode\":\"01\",\"admissionYmdt\":\"20230206142529\",\"tradeConfirmYmdt\":\"20230206142529\",\"admissionState\":\"SUCCESS\",\"totalPayAmount\":100,\"primaryPayAmount\":0,\"npointPayAmount\":100,\"giftCardAmount\":0,\"taxScopeAmount\":100,\"taxExScopeAmount\":0,\"environmentDepositAmount\":0,\"primaryPayMeans\":\"CARD\",\"cardCorpCode\":\"C3\",\"cardNo\":\"5570-****-****-****\",\"cardAuthNo\":\"\",\"cardInstCount\":3,\"usedCardPoint\":false,\"bankCorpCode\":\"020\",\"bankAccountNo\":\"1002-***-***-***\",\"productName\":\"테스트상품\",\"settleExpected\":false,\"settleExpectAmount\":0,\"payCommissionAmount\":0,\"merchantExtraParameter\":\"\",\"extraDeduction\":false,\"useCfmYmdt\":\"\"}},\"LPGEX\":\"TnYSG\"}", new TypeToken<Map<String, Object>>() {
            }.getType());
            modelMap.putAll(param);
        } else if ("fail".equals(flag)) {
            modelMap.put("code", PayUseSysResCd.NO_TARGET_PAYABLE.getCode());
            modelMap.put("message", PayUseSysResCd.NO_TARGET_PAYABLE.getCodeNm());
        } else {
            throw new EnsException(EnsErrCd.ERR405, "유효하지 않은 요청 입니다");
        }

        return "modules/bill/nvEpApply";
    }

    @Parameters({
            @Parameter(name = "billUid", example = "청구서UID", required = true, in = ParameterIn.QUERY),
            @Parameter(name = "paymentId", example = "결제번호", required = true, in = ParameterIn.QUERY),
            @Parameter(name = "resultCode", example = "Success", required = true, in = ParameterIn.QUERY),
            @Parameter(name = "resultMessage", example = "성공", required = false, in = ParameterIn.QUERY),
            @Parameter(name = "reserveId", example = "결제 예약ID", required = false, in = ParameterIn.QUERY)
    })
    @Operation(summary = "네이버페이 간편결제 승인")
    @GetMapping(value = "/bill/nv/ep/apply")
    public String nvEpApply(@RequestParam Map<String, Object> param, ModelMap modelMap) {
        PayApiRespDTO payApiRespDTO = nvPayProcessService.payAble(param);

        StringBuffer message = new StringBuffer();
        if (PayUseSysResCd.OK.getCode().equals(payApiRespDTO.getResCode())) {
            if (payApiRespDTO.getData() != null)
                modelMap.putAll((Map<? extends String, ?>) payApiRespDTO.getData());
        } else {
            modelMap.put("code", payApiRespDTO.getResCode());
            modelMap.put("message", payApiRespDTO.getMessage());
        }

        return "modules/bill/nvEpApply";
    }


}
