package com.style24.core.biz.thirdparty;

import java.net.URI;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.google.gson.Gson;
import com.style24.persistence.domain.KCertifyNo;
import com.style24.persistence.domain.KCertifyNoOnly;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.web.parameter.GagaMap;

/**
 * KC인증번호 조회 (www.safetykorea.kr open API)
 *
 * @author gagamel
 * @since 2020. 12. 1
 */
@Component
@Slf4j
public class SafetyKoreaApi {

	// URL
	private String apiUrl = "http://www.safetykorea.kr/openapi/api/cert/certificationList.json";

	private String apiDetailUrl = "http://www.safetykorea.kr/openapi/api/cert/certificationDetail.json";

	// 인증키
	private String authKey = "34fa9888-a2fb-4c02-adf4-18f018bb936d";

	@Autowired
	private RestTemplate restTemplate;

	@PostConstruct
	public void init() {
		log.debug("\n\n---- SafetyKoreaApi initialization started ----");
		log.debug("apiUrl: [{}]", apiUrl);
		log.debug("apiDetailUrl: [{}]", apiDetailUrl);
		log.debug("authKey: [{}]", authKey);
		log.debug("\n--- SafetyKoreaApi initialization completed ----\n");
	}

	/**
	 * KC인증번호 정보 조회
	 * @param goodsCd - 상품코드
	 * @return 인증번호
	 * @throws Exception
	 * @author gagamel
	 * @since 2020. 12. 1
	 */
	public GagaMap getKoreaCertifyNo(String goodsCd) throws Exception {

		GagaMap result = new GagaMap();

		String requestUrl = apiUrl + "?conditionKey=all&conditionValue=" + goodsCd;
		log.info("requestUrl: {}", requestUrl);
		URI url = URI.create(requestUrl);

		String responseJson = getExtracted( url);

		Gson gson = new Gson();
		KCertifyNo kcNo = gson.fromJson(responseJson, KCertifyNo.class);

		if (kcNo.getResultCode() != null && "2000".equals(kcNo.getResultCode())) { // 성공
			result.set("certNum", kcNo.getResultData().iterator().next().getCertNum());
			result.set("certDiv", kcNo.getResultData().iterator().next().getCertDiv());
			result.set("certState", kcNo.getResultData().iterator().next().getCertState());
			result.set("certDt", kcNo.getResultData().iterator().next().getCertDate());
			return result;
		}

		return result;
	}


	/**
	 * KC인증번호로 조회
	 * @param certNum - 인증번호
	 * @return
	 * @throws Exception
	 * @author eskim
	 * @since 2020. 12. 07
	 */
	public GagaMap getKoreaCertifyDetail(String certNum) throws Exception {

		GagaMap result = new GagaMap();

		String requestUrl = apiDetailUrl + "?certNum=" + certNum;
		URI url = URI.create(requestUrl);

		String responseJson = getExtracted( url);

		Gson gson = new Gson();
		KCertifyNoOnly kcNo = gson.fromJson(responseJson, KCertifyNoOnly.class);

		if (kcNo.getResultCode() != null && "2000".equals(kcNo.getResultCode())) { // 성공
			result.set("certNum", kcNo.getResultData().getCertNum());
			result.set("certDiv", kcNo.getResultData().getCertDiv());
			result.set("certState", kcNo.getResultData().getCertState());
			result.set("certDt", kcNo.getResultData().getCertDate());
			return result;
		}

		return result;

	}

	/**
	 * KC인증정보 조회
	 * @param url - KC인증 URL
	 * @return
	 * @throws Exception
	 * @author eskim
	 * @since 2020. 12. 07
	 */
	private String getExtracted( URI url) {

		String responseJson = "";
		// Header
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		headers.add("AuthKey", authKey);

		// GET방식으로 호출
		HttpEntity<String> request = new HttpEntity<String>(headers);
		ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
		log.info("responseEntity.getStatusCode(): {} ", responseEntity.getStatusCode());

		responseJson = responseEntity.getBody();
		log.info("responseEntity.getBody(): {}", responseJson);

//		{
//		    "resultCode": "2000",
//		    "resultMsg": "Success",
//		    "resultData": [
//		        {
//		            "certUid": 4675807,
//		            "certOrganName": "FITI시험연구원(FITI)",
//		            "certNum": "CB015R0919-8001",
//		            "certState": "적합",
//		            "certDiv": "어린이제품 특별법 대상>안전확인 대상",
//		            "certDate": "20180703",
//		            "certChgDate": null,
//		            "certChgReason": "",
//		            "firstCertNum": null,
//		            "productName": "유아용 섬유제품",
//		            "brandName": "",
//		            "modelName": "MNW1BQKP20",
//		            "categoryName": "어린이>유아용 섬유제품",
//		            "importDiv": "수입",
//		            "makerName": "INWOO",
//		            "makerCntryName": "인도네시아",
//		            "importerName": "(주)아은",
//		            "remark": "",
//		            "signDate": "20200629",
//		            "derivationModels": null,
//		            "certificationImageUrls": null,
//		            "factories": null,
//		            "similarCertifications": null
//		        }
//		    ]
//		}

		return responseJson;
	}

}
