package cokr.xit.ens.biz.iup.billpay.presentation;

import cokr.xit.ens.biz.iup.billpay.service.IupBillKkoPayUseSysService;
import cokr.xit.ens.biz.iup.domain.TbInputDataXit;
import cokr.xit.ens.biz.iup.domain.repository.TbInputDataXitRepository;
import cokr.xit.ens.core.utils.CmmnUtil;
import cokr.xit.ens.modules.common.ctgy.intgrnbill.kko.model.BillKkoApiRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Tag(name = "IupBillKkoPayUseSysController")
@Slf4j
@RequiredArgsConstructor
@RestController
public class IupBillKkoPayUseSysController {

    private final TbInputDataXitRepository tbInputDataXitRepository;

    private final Map<String, IupBillKkoPayUseSysService> iupBillKkoPayUseSysServiceMap;


    @io.swagger.v3.oas.annotations.parameters.RequestBody(required = true, content = {
            @Content(mediaType = "application/json", examples = {
                    @ExampleObject(name = "Sample Example..."
                            , summary = "sample"
                            , value = "{\n" +
                            "\"data\": {\n" +
                            "\"biller_user_key\": \"0000000001\",\n" +
                            "\"user_birth\":\"19900301\",\n" +
                            "\"parameters\": {\n" +
                            "\"some_param\": \"KT00000001\"\n" +
                            "}\n" +
                            "}\n" +
                            "}"
                    )
            })
    })
    @ApiResponses({
            @ApiResponse(responseCode = "200", content = {
                    @Content(mediaType = "application/json", examples = {
                            @ExampleObject(name = "Success Example..."
                                    , summary = "Success"
                                    , value = "{\n" +
                                    "    \"res_code\": \"OK\",\n" +
                                    "    \"message\": \"성공\",\n" +
                                    "    \"data\": {\n" +
                                    "        \"result\": {\n" +
                                    "            \"biller_user_key\": \"0000000001\",\n" +
                                    "            \"title\": \"통신요금\",\n" +
                                    "            \"amount\": 29000,\n" +
                                    "            \"tax_free_amount\": 0,\n" +
                                    "            \"vat_amount\": 0,\n" +
                                    "            \"pay_expire_date\": \"20190801\",\n" +
                                    "            \"details\": [\n" +
                                    "                {\n" +
                                    "                    \"title\": \"고객정보\",\n" +
                                    "                    \"itemType\": \"KEY_VALUE\",\n" +
                                    "                    \"elements\": [\n" +
                                    "                        {\n" +
                                    "                            \"key\": \"이름\",\n" +
                                    "                            \"value\": \"홍길동\",\n" +
                                    "                            \"level\": \"1\"\n" +
                                    "                        },\n" +
                                    "                        {\n" +
                                    "                            \"key\": \"고객번호\",\n" +
                                    "                            \"value\": \"945034260\",\n" +
                                    "                            \"level\": \"1\"\n" +
                                    "                        }\n" +
                                    "                    ]\n" +
                                    "                },\n" +
                                    "                {\n" +
                                    "                    \"title\": \"상세내용\",\n" +
                                    "                    \"itemType\": \"KEY_VALUE\",\n" +
                                    "                    \"elements\": [\n" +
                                    "                        {\n" +
                                    "                            \"key\": \"상품명(서비스번호)\",\n" +
                                    "                            \"value\": \"모바일(010-61**-*234)\",\n" +
                                    "                            \"level\": \"1\"\n" +
                                    "                        },\n" +
                                    "                        {\n" +
                                    "                            \"key\": \"당월요금계\",\n" +
                                    "                            \"value\": \"42,610원\",\n" +
                                    "                            \"level\": \"1\"\n" +
                                    "                        }\n" +
                                    "                    ]\n" +
                                    "                }\n" +
                                    "            ]\n" +
                                    "        }\n" +
                                    "    }\n" +
                                    "}"
                            ),
                            @ExampleObject(name = "Fail Example..."
                                    , summary = "Fail"
                                    , value = "{\n" +
                                    "\"res_code\": \"E402\",\n" +
                                    "\"message\": \"청구서 조회 결과가 없습니다.\",\n" +
                                    "\"data\": null\n" +
                                    "}"
                            )
                    })
            })
    })
    @Operation(summary = "청구서 조회")
    @PostMapping(value = "/iup/kakao/notice", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<BillKkoApiRespDTO> kakaoNotice(@RequestBody Map<String, Object> mParam) {
        try {
            Map<String, Object> data = (Map<String, Object>) mParam.get("data");
            String billerUserKey = (String) data.get("biller_user_key");
            TbInputDataXit tbInputDataXit = tbInputDataXitRepository.findById(billerUserKey).orElseThrow(() -> new RuntimeException("biller_user_key와 일치하는 데이터를 찾을 수 없습니다."));
            IupBillKkoPayUseSysService iupPayProcessService = iupBillKkoPayUseSysServiceMap.get("iupBillKkoPayUseSysService_" + tbInputDataXit.getTbInputXit().getSendType());

            return new ResponseEntity<BillKkoApiRespDTO>(iupPayProcessService.findNoticeInfo(mParam), HttpStatus.OK);

        } finally {

            StringBuffer sb = new StringBuffer();
            sb.append("\n==============================================================================")
                    .append("\n[ kakao 청구서 - 청구서조회  ]")
                    .append("\n### Request Info...")
                    .append("\n" + CmmnUtil.toJsonString(mParam))
//            .append("\n### Response Info...")
//            .append("\n" + resp.getBody())
                    .append("\n==============================================================================");
            log.info(sb.toString());
        }


    }


    @io.swagger.v3.oas.annotations.parameters.RequestBody(required = true, content = {
            @Content(mediaType = "application/json", examples = {
                    @ExampleObject(name = "Sample Example..."
                            , summary = "sample"
                            , value = "{\n" +
                            "\"data\": {\n" +
                            "\"biller_user_key\": \"0000000001\",\n" +
                            "\"amount\": 29000,\n" +
                            "\"parameters\": {\n" +
                            "\"pay_rqt_seq\": \"KT00000001\"\n" +
                            "}\n" +
                            "}\n" +
                            "}")
            })
    })
    @ApiResponses({
            @ApiResponse(responseCode = "200", content = {
                    @Content(mediaType = "application/json", examples = {
                            @ExampleObject(name = "Success Example..."
                                    , summary = "Success"
                                    , value = "{\n" +
                                    "\"res_code\": \"OK\",\n" +
                                    "\"message\": \"성공\",\n" +
                                    "\"data\": null\n" +
                                    "}"
                            ),
                            @ExampleObject(name = "Fail Example..."
                                    , summary = "Fail"
                                    , value = "{\n" +
                                    "\"res_code\": \"E502\",\n" +
                                    "\"message\": \"납부불가 - 납부 대상 없음\",\n" +
                                    "\"data\": null\n" +
                                    "}"
                            )
                    })
            })
    })
    @Operation(summary = "납부 가능 조회")
    @PostMapping(value = "/iup/kakao/prepay", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<BillKkoApiRespDTO> kakaoPrepay(@RequestBody Map<String, Object> mParam) {
        try {
            Map<String, Object> data = (Map<String, Object>) mParam.get("data");
            String billerUserKey = (String) data.get("biller_user_key");
            TbInputDataXit tbInputDataXit = tbInputDataXitRepository.findById(billerUserKey).orElseThrow(() -> new RuntimeException("biller_user_key와 일치하는 데이터를 찾을 수 없습니다."));
            IupBillKkoPayUseSysService iupBillPayService = iupBillKkoPayUseSysServiceMap.get("iupBillKkoPayUseSysService_" + tbInputDataXit.getTbInputXit().getSendType());

            return new ResponseEntity<BillKkoApiRespDTO>(iupBillPayService.findPrepayInfo(mParam), HttpStatus.OK);

        } finally {

            StringBuffer sb = new StringBuffer();
            sb.append("\n==============================================================================")
                    .append("\n[ kakao 청구서 - 납부가능조회 ]")
                    .append("\n### Request Info...")
                    .append("\n" + CmmnUtil.toJsonString(mParam))
//                    .append("\n### Response Info...")
//                    .append("\n" + resp.getBody())
                    .append("\n==============================================================================");
            log.info(sb.toString());
        }


    }


    @io.swagger.v3.oas.annotations.parameters.RequestBody(required = true, content = {
            @Content(mediaType = "application/json", examples = {
                    @ExampleObject(name = "Sample Example..."
                            , summary = "sample"
                            , value = "{\n" +
                            "\"data\": {\n" +
                            "\"biller_user_key\": \"0000000001\",\n" +
                            "\"parameters\": {\n" +
                            "\"pay_rqt_seq\": \"KT00000001\"\n" +
                            "},\n" +
                            "\"pay_by\": \"MONEY\",\n" +
                            "\"pay_type\": \"P\",\n" +
                            "\"pay_detail1\": \"\",\n" +
                            "\"pay_detail2\": \"\",\n" +
                            "\"amount\": 20000,\n" +
                            "\"pay_amount\": 20000,\n" +
                            "\"pay_fee_type\": \"BEFORE\",\n" +
                            "\"pay_fee\": 150,\n" +
                            "\"pay_fee_tax\": 15,\n" +
                            "\"paid_at\": \"20190220161656\",\n" +
                            "\"pay_id\": 2748877\n" +
                            "}\n" +
                            "}")
            })
    })
    @ApiResponses({
            @ApiResponse(responseCode = "200", content = {
                    @Content(mediaType = "application/json", examples = {
                            @ExampleObject(name = "Success Example..."
                                    , summary = "Success"
                                    , value = "{\n" +
                                    "\"res_code\": \"OK\",\n" +
                                    "\"message\": \"성공\",\n" +
                                    "\"data\": null\n" +
                                    "}"
                            )
                    })
            })
    })
    @Operation(summary = "납부 결과 전달")
    @PostMapping(value = "/iup/kakao/pay-result", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<BillKkoApiRespDTO> kakaoPayResult(@RequestBody Map<String, Object> mParam) {
        try {
            Map<String, Object> data = (Map<String, Object>) mParam.get("data");
            String billerUserKey = (String) data.get("biller_user_key");
            TbInputDataXit tbInputDataXit = tbInputDataXitRepository.findById(billerUserKey).orElseThrow(() -> new RuntimeException("biller_user_key와 일치하는 데이터를 찾을 수 없습니다."));
            IupBillKkoPayUseSysService iupBillPayService = iupBillKkoPayUseSysServiceMap.get("iupBillKkoPayUseSysService_" + tbInputDataXit.getTbInputXit().getSendType());

            return new ResponseEntity<BillKkoApiRespDTO>(iupBillPayService.addPayReultIfno(mParam), HttpStatus.OK);

        } finally {

            StringBuffer sb = new StringBuffer();
            sb.append("\n==============================================================================")
                    .append("\n[ kakao 청구서 - 납부결과전달 ]")
                    .append("\n### Request Info...")
                    .append("\n" + CmmnUtil.toJsonString(mParam))
//                    .append("\n### Response Info...")
//                    .append("\n" + resp.getBody())
                    .append("\n==============================================================================");
            log.info(sb.toString());
        }

    }


}
