package com.style24.core.biz.thirdparty;

import java.io.StringReader;
import java.net.URI;

import javax.annotation.PostConstruct;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.style24.persistence.domain.DataGoKr;

import lombok.extern.slf4j.Slf4j;

/**
 * 공공데이터포털을 이용한 통신판매사업자정보 조회
 * 
 * @author gagamel
 * @since 2020. 11. 9
 */
@Component
@Slf4j
public class DataGoKrApi {

	// 공공데이터포털 URL
	private String apiUrl = "http://apis.data.go.kr/1130000/openapi/service/MllInfoService";

	// 서비스키
	private String serviceKey = "";

	@Autowired
	private RestTemplate restTemplate;

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

	/**
	 * 사업자등록번호로 통신판매사업자 정보 조회
	 * @param bizNo - 사업자등록번호
	 * @return 통신판매사업자 정보
	 * @throws Exception
	 * @author gagamel
	 * @since 2020. 11. 18
	 */
	public DataGoKr getMllBizRNoInfo(String bizNo) throws Exception {
		DataGoKr dataGoKr = new DataGoKr();

		// Parameter
		MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
		params.add("ServiceKey", serviceKey);
		params.add("wrkrNo", bizNo);
		log.info("params: {}", params);

		// Header
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

		HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(params, headers);
		URI url = URI.create(apiUrl + "/" + "getMllBizRNoInfo");

		// POST방식으로 호출
		ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);
		log.info("responseEntity.getStatusCode(): {} ", responseEntity.getStatusCode());

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

//		<response>
//			<header>
//				<resultCode>00</resultCode>
//				<resultMsg>NORMAL SERVICE.</resultMsg>
//			</header>
//			<body>
//				<items>
//					<item>
//						<bupNm>(유)아이에스피</bupNm>
//						<dmnNm>www.cjlion.kr</dmnNm>
//						<mngStateCode>01</mngStateCode>
//						<permYmd>20111228</permYmd>
//						<repsntNm>김은령</repsntNm>
//						<seq>26</seq>
//					</item>
//				</items>
//				<numOfRows>10</numOfRows>
//				<pageNo>1</pageNo>
//				<totalCount>1</totalCount>
//			</body>
//		</response>

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse(new InputSource(new StringReader(responseXml)));
		NodeList nodeList = document.getElementsByTagName("items");

		if (nodeList.getLength() > 0) {
			NamedNodeMap nodeMap = nodeList.item(0).getAttributes();

			dataGoKr.setSeq(nodeMap.getNamedItem("seq").getTextContent());
			dataGoKr.setBupNm(nodeMap.getNamedItem("bupNm").getTextContent());
			dataGoKr.setRepsntNm(nodeMap.getNamedItem("repsntNm").getTextContent());
			dataGoKr.setSidoNm(nodeMap.getNamedItem("sidoNm").getTextContent());
			dataGoKr.setDmnNm(nodeMap.getNamedItem("dmnNm").getTextContent());
			dataGoKr.setMngStateCode(nodeMap.getNamedItem("mngStateCode").getTextContent());
			dataGoKr.setPermYmd(nodeMap.getNamedItem("permYmd").getTextContent());

			this.getMllInfoDetail(dataGoKr);
		}

		return dataGoKr;
	}

	/**
	 * 통신판매사업자 상세 정보 조회
	 * @param dataGoKr - 통신판매사업자 정보
	 * @return 통신판매사업자 상세 정보
	 * @throws Exception
	 * @author gagamel
	 * @since 2020. 11. 18
	 */
	private void getMllInfoDetail(DataGoKr dataGoKr) throws Exception {
		// Parameter
		MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
		params.add("ServiceKey", serviceKey);
		params.add("seq", dataGoKr.getSeq());
		log.info("params: {}", params);

		// Header
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

		HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(params, headers);
		URI url = URI.create(apiUrl + "/" + "getMllInfoDetail");

		// POST방식으로 호출
		ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);
		log.info("responseEntity.getStatusCode(): {} ", responseEntity.getStatusCode());

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

//		<response>
//			<header>
//				<resultCode>00</resultCode>
//				<resultMsg>NORMAL SERVICE.</resultMsg>
//			</header>
//			<body>
//				<items>
//					<item>
//						<addr>광주광역시 서구 동천동 235번지 **********</addr>
//						<apvPermMgtNo>2011-광주서구-00485</apvPermMgtNo>
//						<bupNm>(유)아이에스피</bupNm>
//						<bupYn>0</bupYn>
//						<dmnNm>www.cjlion.kr</dmnNm>
//						<mngStateCode>01</mngStateCode>
//						<permYmd>20111228</permYmd>
//						<repsntNm>김은령</repsntNm>
//						<seq>26</seq>
//						<silMet>02</silMet>
//						<treArtcl>0608</treArtcl>
//						<wrkrNo>4108654518</wrkrNo>
//					</item>
//				</items>
//				<numOfRows>10</numOfRows>
//				<pageNo>1</pageNo>
//				<totalCount>1</totalCount>
//			</body>
//		</response>

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse(new InputSource(new StringReader(responseXml)));
		NodeList nodeList = document.getElementsByTagName("items");

		if (nodeList.getLength() > 0) {
			NamedNodeMap nodeMap = nodeList.item(0).getAttributes();
			log.info("{}", nodeMap);

			dataGoKr.setNewaddr(nodeMap.getNamedItem("newaddr").getTextContent());
			dataGoKr.setBupRegNo(nodeMap.getNamedItem("bup_reg_no").getTextContent());
			dataGoKr.setWrkrNo(nodeMap.getNamedItem("wrkr_no").getTextContent());
			dataGoKr.setOrgAndTeamNm(nodeMap.getNamedItem("org_and_team_nm").getTextContent());
			dataGoKr.setRepTelno(nodeMap.getNamedItem("rep_telno").getTextContent());
			dataGoKr.setTreArtcl(nodeMap.getNamedItem("tre_artcl").getTextContent());
			dataGoKr.setSilMet(nodeMap.getNamedItem("sil_met").getTextContent());
			dataGoKr.setBupYn(nodeMap.getNamedItem("bup_yn").getTextContent());
			dataGoKr.setApvPermMgtNo(nodeMap.getNamedItem("apv_perm_mgt_no").getTextContent());
			dataGoKr.setHostSrvAddr(nodeMap.getNamedItem("host_srv_addr").getTextContent());
		}
	}

}
