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

import cokr.xit.ens.core.utils.CmmnUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
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.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
//@Profile({"!local-test"})
public class BillNvEasyPayApi implements BillNvEasyPayApiSpec {

    @Value("${contract.naver.pay.easy.host}")
    private String HOST;
    @Value("${contract.naver.pay.easy.api.pay-apply}")
    private String API_PAY_APPLY;
    @Value("${contract.naver.pay.easy.api.pay-cancel}")
    private String API_PAY_CANCEL;
    @Value("${contract.naver.pay.easy.api.pay-hist}")
    private String API_PAY_HIST;
    @Value("${contract.naver.pay.easy.api.purchase-confirm}")
    private String API_PURCHASE_CONFIRM;
    @Value("${contract.naver.pay.easy.api.point-save}")
    private String API_POINT_SAVE;
    @Value("${contract.naver.pay.easy.api.cash-amount}")
    private String API_CASH_AMOUNT;


    /**
     * <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, Object 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(60000);
            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("네이버페이 간편결제 API\n[ REQUEST ]-----------------------------------------------------------------------\n{}\n[ RESPONSE ]-----------------------------------------------------------------------\n{}", sb.toString(), responseEntity.getBody());
        }

        
        return responseEntity;
    }


    @Override
    public ResponseEntity<String> payApply(String partnerId, String clientId, String clientSecret, LinkedMultiValueMap param) {
       
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(new MediaType(MediaType.APPLICATION_FORM_URLENCODED, Charset.forName("utf-8")));
        headers.set("X-Naver-Client-Id", clientId);
        headers.set("X-Naver-Client-Secret", clientSecret);
        headers.set("X-Xit-PartnerId", partnerId);

       
        StringBuilder url = new StringBuilder()
                .append(this.HOST)
                .append(this.API_PAY_APPLY.replace("{partnerId}", partnerId == null ? "" : partnerId));

       
        MultiValueMap<String, String> body = param;

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

    @Override
    public ResponseEntity<String> payCancel(String partnerId, String clientId, String clientSecret, LinkedMultiValueMap param) {
       
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(new MediaType(MediaType.APPLICATION_FORM_URLENCODED, Charset.forName("utf-8")));
        headers.set("X-Naver-Client-Id", clientId);
        headers.set("X-Naver-Client-Secret", clientSecret);
        headers.set("X-Xit-PartnerId", partnerId);

       
        StringBuilder url = new StringBuilder()
                .append(this.HOST)
                .append(this.API_PAY_CANCEL.replace("{partnerId}", partnerId == null ? "" : partnerId));

       
        MultiValueMap<String, String> body = param;

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

    @Override
    public ResponseEntity<String> payHist(String partnerId, String clientId, String clientSecret, Map<String, Object> param) {
       
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(new MediaType(MediaType.APPLICATION_JSON, Charset.forName("utf-8")));
        headers.set("X-Naver-Client-Id", clientId);
        headers.set("X-Naver-Client-Secret", clientSecret);
        headers.set("X-Xit-PartnerId", partnerId);

       
        StringBuilder url = new StringBuilder()
                .append(this.HOST)
                .append(this.API_PAY_HIST.replace("{partnerId}", partnerId == null ? "" : partnerId));

       
        String jsonStr = CmmnUtil.toJsonString(param);

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

    @Override
    public ResponseEntity<String> purchaseConfirm(String partnerId, String clientId, String clientSecret, String paymentId, String requester) {
       
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(new MediaType(MediaType.APPLICATION_FORM_URLENCODED, Charset.forName("utf-8")));
        headers.set("X-Naver-Client-Id", clientId);
        headers.set("X-Naver-Client-Secret", clientSecret);
        headers.set("X-Xit-PartnerId", partnerId);

       
        StringBuilder url = new StringBuilder()
                .append(this.HOST)
                .append(this.API_PURCHASE_CONFIRM.replace("{partnerId}", partnerId == null ? "" : partnerId));

       
        MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
        param.add("paymentId", paymentId);
        param.add("requester", requester);
        MultiValueMap<String, String> body = param;

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

    @Override
    public ResponseEntity<String> pointSave(String partnerId, String clientId, String clientSecret, String paymentId) {
       
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(new MediaType(MediaType.APPLICATION_FORM_URLENCODED, Charset.forName("utf-8")));
        headers.set("X-Naver-Client-Id", clientId);
        headers.set("X-Naver-Client-Secret", clientSecret);
        headers.set("X-Xit-PartnerId", partnerId);

       
        StringBuilder url = new StringBuilder()
                .append(this.HOST)
                .append(this.API_POINT_SAVE.replace("{partnerId}", partnerId == null ? "" : partnerId));

       
        MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
        param.add("paymentId", paymentId);
        MultiValueMap<String, String> body = param;

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

    @Override
    public ResponseEntity<String> cashAmount(String partnerId, String clientId, String clientSecret, ArrayList<String> paymentIds) {
       
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(new MediaType(MediaType.APPLICATION_JSON, Charset.forName("utf-8")));
        headers.set("X-Naver-Client-Id", clientId);
        headers.set("X-Naver-Client-Secret", clientSecret);
        headers.set("X-Xit-PartnerId", partnerId);

       
        StringBuilder url = new StringBuilder()
                .append(this.HOST)
                .append(this.API_POINT_SAVE.replace("{partnerId}", partnerId == null ? "" : partnerId));

       
        Map<String, List<String>> param = new HashMap<>();
        param.put("paymentIds", paymentIds);
        String jsonStr = CmmnUtil.toJsonString(param);

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