package com.style24.core.biz.service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gagaframework.shoplinker.GagaShoplinkertUtil;
import com.gagaframework.shoplinker.domain.orderlist.Order;
import com.gagaframework.shoplinker.env.GagaShoplinkerConstants;
import com.gagaframework.web.parameter.GagaMap;
import com.gagaframework.web.util.GagaDateUtil;
import com.gagaframework.web.util.GagaFileUtil;
import com.style24.core.biz.dao.TscOrderOcmDao;
import com.style24.core.biz.dao.TscShoplinkerDao;
import com.style24.core.support.env.TscConstants;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.domain.ExtmallOrder;
import com.style24.persistence.domain.ShoplinkerGoods;
import com.style24.persistence.domain.ShoplinkerInvoice;
import com.style24.persistence.domain.ShoplinkerOrder;
import com.style24.persistence.domain.ShoplinkerSearch;

import lombok.extern.slf4j.Slf4j;

/**
 * 영업망관리 샵링커 Service
 *
 * @author gagamel
 * @since 2020. 11. 4
 */
@Service
@Slf4j
@SuppressWarnings("deprecation")
public class TscShoplinkerService {

	@Autowired
	private Environment env;

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private TscShoplinkerDao shoplinkerDao;

	@Autowired
	private TscCommonService commonService;

	@Autowired
	private TscOrderOcmDao orderOcmDao;

	@Autowired
	private ObjectMapper mapper;

	private String fileAddNm; // 유저번호_년월일시분초
	private String chkPermission = "";	// 임시 권한체크용


	/**
	 * 샵링커 api 호출 가능여부
	 *
	 * @param shoplinkerSearch
	 * @return
	 * @author jmh
	 * @since 2020. 5. 28
	 */
	public ShoplinkerSearch getCallRunableInfo(ShoplinkerSearch slkSearch) {
		ShoplinkerSearch result = shoplinkerDao.getCallRunableInfo(slkSearch);
		if( null == result ) {
			result = new ShoplinkerSearch();
			result.setRunCnt(0);
		}
		return result;
	}

	/**
	 * 샵링커 api 호출 가능여부-상품전송용
	 *
	 * @param shoplinkerSearch
	 * @return
	 * @author jmh
	 * @since 2020. 5. 28
	 */
	public ShoplinkerSearch getCallRunableInfoGoods(ShoplinkerSearch slkSearch) {
		ShoplinkerSearch result = shoplinkerDao.getCallRunableInfoGoods(slkSearch);
		if( null == result ) {
			result = new ShoplinkerSearch();
			result.setRunCnt(0);
		}
		return result;
	}

	/**
	 * 샵링커 api 호출 가능여부 상태 저장
	 *
	 * @param shoplinkerSearch
	 * @return
	 * @author jmh
	 * @since 2020. 5. 28
	 */
	public void saveCallApiRunable(ShoplinkerSearch slkSearch) {
		shoplinkerDao.saveCallApiRunable(slkSearch);
	}

	/**
	 * 샵링커 api 호출 가능여부 상태 수정
	 *
	 * @param shoplinkerSearch
	 * @return
	 * @author jmh
	 * @since 2020. 5. 28
	 */
	public void updateCallApiRunable(ShoplinkerSearch slkSearch) {
		shoplinkerDao.updateCallApiRunable(slkSearch);
	}

	/**
	 * 샵링커주문수집-주문수집등록 페이지별 호출
	 *
	 * @param shoplinkerOrder
	 * @return
	 * @author jmh
	 * @since 2021. 5. 20
	 */
	public GagaMap insertShoplinkerOrderStep1(ShoplinkerOrder shoplinkerOrder) {
		ShoplinkerSearch slkSearch = new ShoplinkerSearch();
		slkSearch.setSid(shoplinkerOrder.getSid());
		slkSearch.setRunStat(TscConstants.ShoplinkerApiStat.RUN.value());

		// 파일명 뒤에 붙일 시간
		fileAddNm = GagaDateUtil.getTodayDateTime();
		chkPermission = "";

		int totalPage = 0;
		int totalCount = 0;
		int currentlyPage = 1;
		int currListCount = 0;

		// 1. 첫번째 호출
		shoplinkerOrder.setOrderPageNo(currentlyPage);
		GagaMap map = this.insertShoplinkerOrderStep1Xml(shoplinkerOrder);

		if(TscConstants.ShoplinkerApiStat.TRUE.value().equals(map.getString("RESULT_TYPE"))) {

			totalPage = map.getInt("totalPage");
			totalCount = map.getInt("totalCount");
			currentlyPage = map.getInt("currentlyPage");
			currListCount = map.getInt("currListCount");

			DecimalFormat formatter = new DecimalFormat("###,###");
			slkSearch.setTxt(chkPermission+" ["+shoplinkerOrder.getInfoStr()+"]"+ " 총페이지: "+totalPage+ "("+formatter.format(totalCount)+"건) || "+currentlyPage);
			updateCallApiRunable(slkSearch);

			if( currentlyPage < 1 ) currentlyPage = 1;
			currentlyPage ++;	// 두번째 호출 페이지 수

			// 2. 페이지번호가 존재할 경우, n번째까지 호출(주문수집) // 1페이지당 500개 (주문이 500개 이상 시 페이지로 호출하란 가이드)
			for( int i=currentlyPage; i<= totalPage; i++) {

				slkSearch.setTxt("=>"+i);
				updateCallApiRunable(slkSearch);

				shoplinkerOrder.setOrderPageNo(i);
				map = this.insertShoplinkerOrderStep1Xml(shoplinkerOrder);
				currListCount += map.getInt("currListCount");
			}

			map.setInt("currListCount", currListCount);

		}else {
			// 수집건없음, 수집실패, 오류
			String txt = chkPermission+" ["+shoplinkerOrder.getInfoStr()+"] "+ map.getString("RESULT_MSG");
			slkSearch.setTxt(StringUtils.abbreviate(txt, 0 , 200));
			updateCallApiRunable(slkSearch);
		}

		return map;
	}

	/**
	 * 샵링커주문수집-주문수집등록
	 *
	 * @param shoplinkerOrder
	 * @return
	 * @author jmh
	 * @since 2021. 5. 20
	 */
	public GagaMap insertShoplinkerOrderStep1Xml(ShoplinkerOrder shoplinkerOrder) {

		GagaMap returnMap = new GagaMap();
		ShoplinkerGoods regMap = new ShoplinkerGoods();
		regMap.setApiSubUrl(env.getProperty("shoplinker.url.order"));
		regMap.setDomainUrl(shoplinkerOrder.getDomainUrl());

		int totalPage = 0;
		int currentlyPage = 0;	// 샵링커 header 현재 호출된 페이지번호
		int totalCount = 0;		// 샵링커 header 총 주문건수
		int currListCount = 0;  // for문안 목록 건수 건건이
		try {

			// xml 데이터 세팅
			String responseXmlData;
			com.gagaframework.shoplinker.domain.orderlist.Shoplinker shoplinkerResult;

			List<Order> rOrdList;
			com.gagaframework.shoplinker.domain.orderlist.Header rHeader;
			StringBuilder sbRequest;

			sbRequest = new StringBuilder();
			sbRequest.append("<?xml version=\"1.0\" encoding=\"euc-kr\"?>\n");
			sbRequest.append("<Shoplinker>\n");
			sbRequest.append("	<OrderInfo>\n");
			sbRequest.append("		<Order>\n");
			
			sbRequest.append("			<customer_id>").append(shoplinkerOrder.getCustomerId()).append("</customer_id>\n");
			sbRequest.append("			<shoplinker_id><![CDATA[").append(shoplinkerOrder.getShoplinkerId()).append("]]></shoplinker_id>\n");
			sbRequest.append("			<st_date>").append(shoplinkerOrder.getStDate().replace("-", "")).append("</st_date>\n");
			sbRequest.append("			<ed_date>").append(shoplinkerOrder.getEdDate().replace("-", "")).append("</ed_date>\n");
			if( "BATCH".equals(shoplinkerOrder.getAcType())){
				sbRequest.append("			<sdt_time>").append(shoplinkerOrder.getStTime()).append("</sdt_time>\n");
				sbRequest.append("			<edt_time>").append(shoplinkerOrder.getEdTime()).append("</edt_time>\n");
			}

			sbRequest.append("			<page_no>").append(shoplinkerOrder.getOrderPageNo()).append("</page_no>\n");

			sbRequest.append("		</Order>\n");
			sbRequest.append("	</OrderInfo>\n");
			sbRequest.append("</Shoplinker>\n");
			log.info("\n\n###################"+ sbRequest.toString());


			GagaShoplinkertUtil shoplinkerUtil = new GagaShoplinkertUtil("MS949");
			String responseXmlPath = "";
			
			// XML 파일 생성
			StringBuilder xmlFileName = new StringBuilder();
			xmlFileName.append("order"+"_"+fileAddNm).append(".xml");
			String xmlPath = GagaFileUtil.getConcatenationPath(shoplinkerOrder.getXmlPath(), xmlFileName.toString());
			log.info("\n################### SHOPLINKER_CHECK 0-1 : "+shoplinkerOrder.getProfiles()+" | "+ xmlPath);
			log.info("\n################### SHOPLINKER_CHECK 0-2 : "+shoplinkerOrder.getXmlPath());
			// 파일 권한확인 --------------------------------------------------
		    File dir = new File(shoplinkerOrder.getXmlPath());
		    if( null != dir) {
		    	log.info("\n################### SHOPLINKER_CHECK 0-3  "+dir);
		    	log.info("\n################### SHOPLINKER_CHECK 0-4  "+dir.canRead()+" / "+dir.canWrite());
		    	if( !dir.canRead()) {
		    		dir.setReadable(true);
		    		chkPermission = "P";
				}
				if( !dir.canWrite()) {
					dir.setWritable(true);
					chkPermission = "P";
				}
				log.info("\n################### SHOPLINKER_CHECK 0-5  "+dir.canRead()+" / "+dir.canWrite());
		    }
		    // 파일 권한확인 끝 ------------------------------------------------
		    log.info("\n################### SHOPLINKER_CHECK 1 ");
		    
		    shoplinkerUtil.makeRequestXmlFile(sbRequest.toString(), xmlPath);
		    
			log.info("\n################### SHOPLINKER_CHECK 2-1 : ");
			String xmlUrl = GagaFileUtil.getConcatenationPath(shoplinkerOrder.getDomainUrl(), xmlFileName.toString());
			
			if (!"locd".equals(shoplinkerOrder.getProfiles())) { // 로컬이 아닐때
				try {
					// API 호출
					responseXmlData = shoplinkerUtil.callShoplinkerApiByGet(GagaShoplinkerConstants.API_DOMAIN+regMap.getApiSubUrl()+URLEncoder.encode(xmlUrl), "");
					
					// 받은 내용 쌓음.(누락 데이터 확인용) 
					try {
						responseXmlPath = GagaFileUtil.getConcatenationPath(shoplinkerOrder.getXmlPath(), "rp_"+fileAddNm+"_"+shoplinkerOrder.getOrderPageNo()+".xml");
						shoplinkerUtil.makeRequestXmlFile(responseXmlData, responseXmlPath);
					}catch(Exception e) {
						log.error("insertShoplinkerOrderStep1Xml > responseXmlData error "+e);
					}
										
					// response 결과
					shoplinkerResult = (com.gagaframework.shoplinker.domain.orderlist.Shoplinker)shoplinkerUtil.unmarshal(com.gagaframework.shoplinker.domain.orderlist.Shoplinker.class, responseXmlData);
					rHeader = shoplinkerResult.getHeader();
					rOrdList = shoplinkerResult.getOrder();

					// 수집정보 존재
					if( null != rHeader ) {
						totalCount = rHeader.getTotalCount();
						totalPage = rHeader.getTotalPage();
						currentlyPage = rHeader.getCurrentlyPage();
						ShoplinkerOrder slOrder;

						int index = 0;
						GagaMap paramMap = new GagaMap();
						GagaMap slOrderMap = new GagaMap();
						List<GagaMap> insertOrderList = new ArrayList<GagaMap>();

						for(Order ord : rOrdList) {
							slOrder = mapper.convertValue(ord, ShoplinkerOrder.class);
							
							slOrder.setOrderIfIdx(commonService.getNextSequence("SEQ_SHHOPLINKER_ORD"));
							currListCount ++;

							//1. 샵링커 주문등록
							try {
								slOrderMap = mapper.convertValue(slOrder, GagaMap.class);
								insertOrderList.add(slOrderMap);
								index ++;

								// 5개씩 (5개씩 보내는게 가장 빠름)
								if (index % 5 == 0 || rOrdList.size() == index) {
									paramMap = new GagaMap();
									paramMap.put("insertOrderList", insertOrderList);

									shoplinkerDao.insertShoplinkerOrderList(paramMap);
									insertOrderList.clear();
								}
								
								// 한개씩 작업 시
								// shoplinkerDao.insertShoplinkerOrder(slOrder);
							}catch(Exception e) {
								ShoplinkerGoods map = new ShoplinkerGoods();
								String chkParams = "";
								chkParams += "SHOPLINKER_ORDER_ID="+ord.getShoplinkerOrderId() +",MALL_ORDER_ID="+ord.getMallOrderId()
										  + ",ORDER_NAME="+ord.getOrderName() + ",ORDER_TEL="+ord.getOrderTel() + ",ORDER_CEL="+ord.getOrderCel()
										  + ",RECEIVE="+ord.getReceive() + ",RECEIVE_TEL="+ord.getReceiveTel() + ",RECEIVE_CEL="+ord.getReceiveCel()
										  + ",RECEIVE_ADDR="+ord.getReceiveAddr() + ",DELIVERY_MSG="+ord.getDeliveryMsg() + ",PRODUCT_NAME="+ord.getProductName()
										  + ",SKU="+ord.getSku() + ",SUPPLY_ID="+ord.getSupplyId() + ",DELIVERY="+ord.getDelivery() + ",ORDER_USER_ID="+ord.getOrderUserId()
										  + ",SCRSPIK_USE="+ord.getCrspikUse() + ",DEAL_NO="+ord.getDealNo() + ",ORDER_MAIN_KEY="+ord.getOrderMainKey()
										  + ",PAN_TYPE="+ord.getPanType() + ",SCHANNEL_TYPE="+ord.getChannelType() + ",SHIP_NO="+ord.getShipNo();
								map.setApiType("ORDER");
								map.setXmlTxt(chkParams);
								map.setApiResult(TscConstants.ShoplinkerApiStat.S_ERROR.value());
								map.setApiMessage("샵링커 주문생성 오류");

								// 오류이력 저장
								shoplinkerDao.insertShoplinerApiHst(map);
							}
						}

						returnMap.setString("RESULT_TYPE", TscConstants.ShoplinkerApiStat.TRUE.value());

						log.debug("Shoplinker API Call: success");
						log.debug("responseXmlData {}", responseXmlData);
					}else {
						// 수집정보 존재안함.
						com.gagaframework.shoplinker.domain.goods.result.Shoplinker orderFailResult;
						com.gagaframework.shoplinker.domain.goods.result.ResultMessage orderFailResultMsg;
						orderFailResult =  (com.gagaframework.shoplinker.domain.goods.result.Shoplinker)shoplinkerUtil.unmarshal(com.gagaframework.shoplinker.domain.goods.result.Shoplinker.class, responseXmlData);
						orderFailResultMsg = orderFailResult.getResultMessage();

						returnMap.setString("RESULT_TYPE", orderFailResultMsg.getResult());
						returnMap.setString("RESULT_MSG", orderFailResultMsg.getMessage());
					}

				} catch (Exception e) {
					log.error("insertShoplinkerOrderStep1Xml error", e);
					returnMap.setString("RESULT_TYPE", TscConstants.ShoplinkerApiStat.ERROR.value());
					returnMap.setString("RESULT_MSG", StringUtils.abbreviate(e.getMessage(), 0 , 120));

					// 상세오류내역
					ShoplinkerGoods map = new ShoplinkerGoods();
					map.setApiType("ORDER");
					map.setXmlTxt(sbRequest.toString());
					map.setApiResult(TscConstants.ShoplinkerApiStat.S_ERROR.value());
					map.setApiMessage("API 오류: "+StringUtils.abbreviate(e.getMessage(), 0 , 120));
					shoplinkerDao.insertShoplinerApiHst(map);
				}
			}

			// 생성 파일삭제
			// GagaFileUtil.deleteFile(GagaFileUtil.getConcatenationPath(shoplinkerOrder.getXmlPath(), xmlFileName.toString()));

		}catch(Exception e) {
			log.error("xml 생성오류 ", e);
			returnMap.setString("RESULT_TYPE", TscConstants.ShoplinkerApiStat.ERROR.value());
			returnMap.setString("RESULT_MSG", "xml 생성오류");
		}

		returnMap.setInt("currListCount", currListCount);
		returnMap.setInt("totalCount", totalCount);	// 총 주문건수
		returnMap.setInt("totalPage", totalPage);
		returnMap.setInt("currentlyPage", currentlyPage);

		return returnMap;
	}

	/**
	 * 샵링커주문수집-제휴몰 주문등록
	 *
	 * @param shoplinkerOrder
	 * @return
	 * @author jmh
	 * @since 2021. 5. 20
	 */
	public void insertShoplinkerOrderStep2(ShoplinkerOrder shoplinkerOrder) {

		// 1. 외부몰 미등록 목록 가져옴
		Collection<ShoplinkerOrder> slkOrdList = shoplinkerDao.getShoplinkerRegExtmallList();

		ExtmallOrder extmallOrder;
		GagaMap addrMap; 	//주소 분리
		GagaMap checkMap;
		for(ShoplinkerOrder slOrder : slkOrdList) {

			extmallOrder = new ExtmallOrder();
			extmallOrder.setVendorId(TscConstants.VendorId.SHOPLINKER.value());			// 샵링커
			extmallOrder.setUploadStat(TscConstants.ExtmallUploadStat.WAIT.value()); 	// 대기
			extmallOrder.setUploadGb("S");												// 업로드구분(샵링커:S, 엑셀:E)
			extmallOrder.setRegNo(shoplinkerOrder.getRegNo());
			extmallOrder.setBasicParams(slOrder);										// 기본세팅파람

			try {

				extmallOrder.setDetailParams(slOrder);									// 상세파람

				if( null != slOrder.getDisPriceCoupon() && !slOrder.getDisPriceCoupon().isEmpty()) {
					extmallOrder.setCpnDcAmt(Integer.parseInt(slOrder.getDisPriceCoupon()));
				}else {
					extmallOrder.setCpnDcAmt(0);
				}

				if( null != slOrder.getDisPricePoint() && !slOrder.getDisPricePoint().isEmpty()) {
					extmallOrder.setPntDcAmt(Integer.parseInt(slOrder.getDisPricePoint()));
				}else {
					extmallOrder.setPntDcAmt(0);
				}

				// validation 체크
				checkMap = getRegOrderValidation(slOrder);
				if( "FAIL".equals(checkMap.getString("RESULT_MSG"))) {
					extmallOrder.setUploadStat(checkMap.getString("UploadStat"));	//실패
					extmallOrder.setUploadFailCd(checkMap.getString("UploadFailCd"));
					extmallOrder.setUploadFailReason(checkMap.getString("UploadFailReason")); // 실패사유

				}else {
					// 주소분리
					addrMap = this.returnChangeAddr(slOrder.getReceiveAddr());
					extmallOrder.setRecipBaseAddr(addrMap.getString("addrBase"));
					extmallOrder.setRecipDtlAddr(addrMap.getString("addrDtl"));
				}

				orderOcmDao.insertExtmallOrder(extmallOrder);

			}catch(Exception e) {
				log.error("TsaShoplinkerService.insertShoplinkerOrderStep2 Error : "+e);
				extmallOrder.setUploadStat(TscConstants.ExtmallUploadStat.FAIL.value());	//실패
				extmallOrder.setUploadFailCd(TscConstants.ExtmallUploadFailStat.ETC.value());
				extmallOrder.setUploadFailReason("제휴몰 등록오류 :: "+StringUtils.abbreviate(e.getMessage(), 0 , 120)); // 실패사유
				orderOcmDao.insertExtmallOrder(extmallOrder);
			}

			// 제휴몰등록여부 업데이트
			shoplinkerDao.updateShoplinkerOrder(slOrder);
		}
	}

	/**
	 * 샵링커주문수집-validation 체크
	 *
	 * @param shoplinkerOrder
	 * @return
	 * @author jmh
	 * @since 2021. 5. 20
	 */
	public GagaMap getRegOrderValidation(ShoplinkerOrder slOrder) {

		GagaMap rMap = new GagaMap();
		rMap.setString("RESULT_MSG", "FAIL");
		rMap.setString("UploadStat", TscConstants.ExtmallUploadStat.FAIL.value());

		//주문구분: 일반주문[신규 OR 발주] , 발주확인 주문 건만
		//플래그값 없이 전송시 일반주문만 내려주므로 아래 체크 할 필요는 없음
		/*if( "002".equals(slOrder.getOrderFlag()) || "003".equals(slOrder.getOrderFlag()) || "004".equals(slOrder.getOrderFlag()) ) {
		    rMap.setString("UploadFailCd", TscConstants.ExtmallUploadFailStat.ETC.value());
			rMap.setString("UploadFailReason", "주문타입 실패. 주문타입:"+slOrder.getOrderFlag()+"(정산확정:002/송장등록:003/송장전송완료:004)");
			return rMap;
		}*/

		if( null == slOrder.getReceiveAddr() || slOrder.getReceiveAddr().isEmpty()) {
			rMap.setString("UploadFailCd", TscConstants.ExtmallUploadFailStat.ETC.value());
			rMap.setString("UploadFailReason", "주소정보 없음.");
			return rMap;
		}

		rMap.setString("RESULT_MSG", "SUCCESS");

		return rMap;
	}
	
	/**
	 * 샵링커주문수집-가용재고로 인한 실패 건, 실패사유플래그 변경(엑셀에서 재주문 가능하도록)
	 * 
	 * @param ShoplinkerOrder
	 * @author jmh
	 * @throws Exception
	 * @since 2021. 7. 28
	 */
	@Transactional("shopTxnManager")
	public void updateOrderFailFlag(Collection<ShoplinkerOrder> orderList) {
		for( ShoplinkerOrder ord : orderList ) {
			shoplinkerDao.updateOrderFailFlag(ord);
		}
	}

	/**
	 * 송장전송-전송예정목록
	 *
	 * @param
	 * @return
	 * @author jmh
	 * @since 2021. 5. 20
	 */
	public Collection<ShoplinkerInvoice> getShoplinkerInvoiceOrdDtlSendList() {
		return shoplinkerDao.getShoplinkerInvoiceOrdDtlSendList();
	}

	/**
	 * 송장전송-전송
	 *
	 * @param sendList
	 * @return
	 * @author jmh
	 * @since 2021. 5. 20
	 */
	public void createShoplinkerInvoiceXml(ShoplinkerInvoice shoplinkerInvoice, Collection<ShoplinkerInvoice> sendList) throws IOException {
		// 파일명 뒤에 붙일 시간
		fileAddNm = GagaDateUtil.getTodayDateTime();

		ShoplinkerGoods apiHstMap = new ShoplinkerGoods();

		ShoplinkerGoods regMap = new ShoplinkerGoods();
		regMap.setApiType("INVOICE");
		regMap.setApiSubUrl(env.getProperty("shoplinker.url.invoice"));
		regMap.setRegNo(0);
		regMap.setXmlPath(shoplinkerInvoice.getXmlPath());
		regMap.setDomainUrl(shoplinkerInvoice.getDomainUrl());

		StringBuilder sbRequest;
		com.gagaframework.shoplinker.domain.invoice.ResultMessage resultMsg;

		if( null != sendList && !sendList.isEmpty()) {
			for(ShoplinkerInvoice info : sendList) {
				apiHstMap = new ShoplinkerGoods();

				// xml 데이터 세팅
				sbRequest = new StringBuilder();
				sbRequest.append("<?xml version=\"1.0\" encoding=\"euc-kr\"?>\n");
				sbRequest.append("<Shoplinker>\n");
				sbRequest.append("	<Delivery>\n");

				sbRequest.append("		<customer_id>").append(shoplinkerInvoice.getCustomerId()).append("</customer_id>\n");
				sbRequest.append("		<order_id>").append(info.getAgentOrderId()).append("</order_id>\n");
				sbRequest.append("		<delivery_name><![CDATA[").append(info.getDeliveryName()).append("]]></delivery_name>\n");
				sbRequest.append("		<delivery_invoice><![CDATA[").append(info.getDeliveryInvoice()).append("]]></delivery_invoice>\n");

				sbRequest.append("	</Delivery>\n");
				sbRequest.append("</Shoplinker>\n");

				StringBuilder xmlFileName = new StringBuilder();
				String xmlPath = "";
				String xmlUrl = "";

				// api 호출 및 결과 history 저장
				try {

					GagaShoplinkertUtil shoplinkerUtil = new GagaShoplinkertUtil("MS949");

					// XML 파일 생성
					xmlFileName = new StringBuilder();
					xmlFileName.append("invoice_"+info.getOrdDtlNo()).append(".xml");
					xmlPath = GagaFileUtil.getConcatenationPath(shoplinkerInvoice.getXmlPath(), xmlFileName.toString());
					shoplinkerUtil.makeRequestXmlFile(sbRequest.toString(), xmlPath);
					xmlUrl = GagaFileUtil.getConcatenationPath(shoplinkerInvoice.getDomainUrl(), xmlFileName.toString());

					// API 호출
					String apiUrl = GagaShoplinkerConstants.API_DOMAIN + regMap.getApiSubUrl() + URLEncoder.encode(xmlUrl);
					String responseXmlData = shoplinkerUtil.callShoplinkerApiByGet(apiUrl, "");

					// response 결과
					resultMsg = (com.gagaframework.shoplinker.domain.invoice.ResultMessage)shoplinkerUtil.unmarshal(com.gagaframework.shoplinker.domain.invoice.ResultMessage.class, responseXmlData);
					apiHstMap.setApiType("INVOICE");
					apiHstMap.setXmlTxt(sbRequest.toString());
					apiHstMap.setOrdDtlNo(info.getOrdDtlNo());
					apiHstMap.setApiResult(resultMsg.getResult());
					apiHstMap.setApiMessage(resultMsg.getMessage());
					
					if(-1 < resultMsg.getMessage().indexOf("could not open XML") ) {
						apiHstMap.setApiResult("error");
					}
					
				} catch (Exception e) {
					log.error("createShoplinkerInvoiceXml error", e);
					apiHstMap.setApiType("INVOICE");
					apiHstMap.setXmlTxt(sbRequest.toString());
					apiHstMap.setOrdDtlNo(info.getOrdDtlNo());
					apiHstMap.setApiResult(TscConstants.ShoplinkerApiStat.S_ERROR.value());
					apiHstMap.setApiMessage("API 오류");
				}

				// 전송이력 저장
				shoplinkerDao.insertShoplinerApiHst(apiHstMap);

				// 생성 파일삭제
				// GagaFileUtil.deleteFile(GagaFileUtil.getConcatenationPath(shoplinkerInvoice.getXmlPath(), xmlFileName.toString()));
			}
		}
	}


	/**
	 * 제휴몰 주문등록 주소분리
	 *
	 * @param addrStr
	 * @return
	 * @author jmh
	 * @since 2020. 5. 21
	 */
	public GagaMap returnChangeAddr(String addrStr) {
		GagaMap rtnMap = new GagaMap();

		String tmpStr = "";
		String addrBase = "";
		String addrDtl = "";

		if( -1 < addrStr.indexOf(" ")) {
			// 공백  있음!
			String[] addr = addrStr.split(" ");
			if( addrStr.getBytes().length <= 100) {
				addrBase = addr[0];
				addrDtl = addrStr.replace(addr[0], "").trim();
			}else {

				for( int i=0; i< addr.length; i++) {
					tmpStr = addrBase + addr[i];
					if( 100 <  tmpStr.getBytes().length) {
						break;
					}else {
						addrBase += addr[i]+" ";
					}
				}

				addrBase = addrBase.trim();
				addrDtl = addrStr.replace(addrBase, "").trim();
			}

		}else {
			// 공백 없음! 무작위로 자르기!!
			if( addrStr.getBytes().length <= 100) {
				addrBase = addrStr;
				addrDtl = null;
			}else {

				tmpStr = addrStr.substring(0, addrStr.length()/2);
				if( 100 < tmpStr.getBytes().length ) {
					tmpStr = tmpStr.substring(0, tmpStr.length()/2);
				}
				// 숫자를 기준으로 자름
				for (char c : tmpStr.toCharArray()) {
					if (Character.isDigit(c)) {
			           break;
			        }else {
			        	addrBase += c;
			        }
			    }
				addrBase = addrBase.trim();
				addrDtl = addrStr.replace(addrBase, "").trim();
			}
		}

		rtnMap.put("addrBase", addrBase);
		rtnMap.put("addrDtl", addrDtl);

		return rtnMap;
	}
	
}
