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

import cokr.xit.ens.core.utils.CmmnUtil;
import cokr.xit.ens.modules.common.ctgy.intgrnbill.kko.code.BillKkoErrCd;
import cokr.xit.ens.modules.common.ctgy.intgrnbill.kko.model.BillKkoApiRespDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Profile;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
@Component
@Profile({"!local-test"})
public class IupKkoPayUseSysApi implements IupKkoPayUseSysApiSpec {

    /**
     * 고객사별 납부가능조회 API 호출
     *
     * @param uri
     * @param mParam
     * @return
     */
    @Override
    public BillKkoApiRespDTO callApiByOrg(String uri, Map<String, Object> mParam) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(new MediaType(MediaType.APPLICATION_JSON, Charset.forName("utf-8")));


        StringBuilder url = new StringBuilder();
        url.append(uri);

        String jsonStr = CmmnUtil.toJsonString(mParam);


        ResponseEntity<String> resp = this.callApi(HttpMethod.POST, url.toString(), jsonStr, headers);

        return setResponse(resp, url.toString());
    }


    /**
     * API 호출 응답정보를 IupBillPayRespVO 로 반환
     *
     * @param resp
     * @return
     */
    private BillKkoApiRespDTO setResponse(ResponseEntity<String> resp, String url) {
        if (log.isDebugEnabled()) {
            StringBuffer sb = new StringBuffer();
            sb.append("\n================================================")
                    .append("\nKkoBillClientApi.setResponse...")
                    .append("\n" + resp.getBody())
                    .append("\n================================================");
            log.debug(sb.toString());
        }
        BillKkoApiRespDTO respVO = null;
        try {
            if (HttpStatus.OK.equals(resp.getStatusCode())) {

                ObjectMapper mapper = new ObjectMapper();
                Map<String, Object> mResp = mapper.readValue(resp.getBody(), Map.class);
                if ("OK".equals(mResp.get("res_code")) || "성공".equals(mResp.get("res_code")))
                    respVO = BillKkoApiRespDTO.okBuilder()
                            .data(null)
                            .build();
                else
                    respVO = BillKkoApiRespDTO.errBuilder()
                            .resCode(String.valueOf(mResp.get("res_code")))
                            .message(String.valueOf(mResp.get("message")))
                            .build();
            } else {
                respVO = BillKkoApiRespDTO.errBuilder()
                        .resCode(BillKkoErrCd.ERR601.getCode())
                        .message(String.format("기관과 통신 실패. [URL]:::%s. [ERROR]:::%s %s.", url, resp.getStatusCode().toString(), resp.getBody()))
                        .build();
            }
        } catch (IOException e) {
            respVO = BillKkoApiRespDTO.errBuilder()
                    .resCode(BillKkoErrCd.ERR505.getCode())
                    .message(e.getMessage())
                    .build();
        } catch (Exception e) {
            respVO = BillKkoApiRespDTO.errBuilder()
                    .resCode(BillKkoErrCd.ERR999.getCode())
                    .message(e.getMessage())
                    .build();
        }

        return respVO;

    }


    /**
     * <pre>메소드 설명: API 호출
     * </pre>
     *
     * @param method
     * @param url
     * @param body
     * @param headers
     * @return ResponseEntity 요청처리 후 응답객체
     * @author: 박민규
     * @date: 2021. 8. 4.
     * @apiNote: 사이트 참조 https://e2e2e2.tistory.com/15
     */
    private ResponseEntity<String> callApi(HttpMethod method, String url, String body, HttpHeaders headers) {

        StringBuffer sb = new StringBuffer();
        ResponseEntity<String> responseEntity = null;
        try {

            HttpEntity<?> entity = null;
            UriComponents uri = null;
            switch (method) {
                case GET:
                    entity = new HttpEntity<>(headers);
                    uri = UriComponentsBuilder
                            .fromHttpUrl(String.format("%s?%s", url, body == null ? "" : body))
//							.encode(StandardCharsets.UTF_8)	//"%"기호가 "%25"로 인코딩 발생하여 주석처리 함.
                            .build(false);
                    break;
                case POST:
                    entity = new HttpEntity<>(body, headers);
                    uri = UriComponentsBuilder
                            .fromHttpUrl(url)
                            .encode(StandardCharsets.UTF_8)
                            .build();
                    break;

                default:
                    break;
            }



            HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
            factory.setConnectTimeout(5000);
//            factory.setReadTimeout(3000);
//            factory.setReadTimeout(10000);
            factory.setReadTimeout(15000);
            RestTemplate restTemplate = new RestTemplate(factory);
            sb.append("\n  url => " + uri.toString())
                    .append("\n  method => " + method)
                    .append("\n  headers => " + entity.getHeaders().toString())
                    .append("\n  body => " + entity.getBody());
            responseEntity = restTemplate.exchange(URI.create(uri.toString()), method, entity, String.class);

            /*
             * HttpStatus 정보 확인 방법
             * 	-.코드: responseEntity.getStatusCodeValue()
             * 	-.메시지: responseEntity.getStatusCode()
             */

        } catch (HttpServerErrorException e) {
            responseEntity = new ResponseEntity<String>(e.getResponseBodyAsString(), e.getStatusCode());
            log.error("call API 서버오류\n[ url ]: {} \n[ param ]: {} \n[ error ]: {}", url, body, CmmnUtil.printStackTraceToString(e));
        } catch (HttpClientErrorException e) {
            responseEntity = new ResponseEntity<String>(e.getResponseBodyAsString(), e.getStatusCode());
            log.error("call API 클라이언트오류\n[ url ]: {} \n[ param ]: {} \n[ error ]: {}", url, body, CmmnUtil.printStackTraceToString(e));
        } catch (RestClientException e) {
            responseEntity = new ResponseEntity<String>(e.getMessage(), HttpStatus.REQUEST_TIMEOUT);
            log.error("RestAPI 호출 오류\n[ url ]: {} \n[ param ]: {} \n[ error ]: {}", url, body, CmmnUtil.printStackTraceToString(e));
        } catch (Exception e) {
            responseEntity = new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
            log.error("call API 기타오류\n[ url ]: {} \n[ param ]: {} \n[ error ]: {}", url, body, CmmnUtil.printStackTraceToString(e));
        } finally {
            log.info("카카오페이 청구서 Client API\n[ REQUEST ]-----------------------------------------------------------------------\n{}\n[ RESPONSE ]-----------------------------------------------------------------------\n{}", sb.toString(), responseEntity.getBody());
        }


        return responseEntity;
    }

}
