package itn.let.kakao.kakaoComm.kakaoApi;

import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.swing.ImageIcon;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import egovframework.rte.fdl.property.EgovPropertyService;
import itn.let.kakao.kakaoComm.KakaoButtonVO;
import itn.let.kakao.kakaoComm.KakaoCommentVO;
import itn.let.kakao.kakaoComm.KakaoItemVO;
import itn.let.kakao.kakaoComm.KakaoReturnVO;
import itn.let.kakao.kakaoComm.KakaoVO;
import itn.let.kakao.kakaoComm.kakaoApi.service.KakaoApiService;
import itn.let.utl.fcc.service.EgovStringUtil;

/**
* @FileName : KakaoApiTemplate.java
* @Project : mjon
* @Date : 2023. 1. 31.
* @작성자 :  WYH

* @프로그램 설명 :
*/
@Component
public class KakaoApiTemplate {

	
	/** 비즈 회원 아이디 */
	@Value("#{globalSettings['Globals.mjon.biz.url']}")
	private String mjonBizUrl;
	
	/** 비즈 회원 아이디 */
	@Value("#{globalSettings['Globals.mjon.biz.id']}")
	private String mjonBizId;
	
	/** 비즈 회원 API 키*/
	@Value("#{globalSettings['Globals.mjon.biz.kakao.apiKey']}")
	private String mjonBizKakaoApiKey;
	
	@Resource(name = "kakaoApiService")
	private KakaoApiService kakaoApiService;
	
    @Resource(name = "propertiesService")
    protected EgovPropertyService propertyService;
	
	/**
	* @Method Name : insertKakaoApiTemplate
	* @작성일 : 2023. 1. 4.
	* @작성자 :  WYH
	* @Method 설명 : 발신프로필 템플릿 등록
	*/
	@SuppressWarnings("unchecked")
	public KakaoReturnVO insertKakaoApiTemplate(KakaoVO kakaoVO) {
		KakaoReturnVO kakaoReturnVO = new KakaoReturnVO();
		try {
			
			String sendUrl = mjonBizUrl + "/v3/kakao/template/add";
			 
			JSONObject jsonObject = new JSONObject(); 
			//버튼 추가를 위한 배열 변수 선언
			JSONArray btnJsonArr = new JSONArray();
			JSONObject btnJsonObj = new JSONObject();
			
			jsonObject.put("bizId", mjonBizId);
			jsonObject.put("apiKey", mjonBizKakaoApiKey);
			jsonObject.put("senderKey", kakaoVO.getSenderKey());
			jsonObject.put("templateName", kakaoVO.getTemplateName());
			jsonObject.put("templateMessageType", kakaoVO.getTemplateMessageType());
			jsonObject.put("templateEmphasizeType", kakaoVO.getTemplateEmphasizeType());
			jsonObject.put("templateContent", kakaoVO.getTemplateContent());
			jsonObject.put("categoryCode", kakaoVO.getCategoryCode());
			
			if(kakaoVO.getTemplateMessageType().equals("EX")) {
				jsonObject.put("templateExtra", kakaoVO.getTemplateExtra() );
			}else if(kakaoVO.getTemplateMessageType().equals("AD")) {
				//jsonObject.put("templateAd", kakaoVO.getTamplateAd());

				//메세지 유형 채널추가형인 경우 채널추가 버튼 생성해주기
				btnJsonObj.put("name", "채널추가");
				btnJsonObj.put("linkType", "AC");
				btnJsonArr.add(btnJsonObj);
				
			}else if(kakaoVO.getTemplateMessageType().equals("MI")) {
				jsonObject.put("templateExtra", kakaoVO.getTemplateExtra() );
				//jsonObject.put("templateAd", kakaoVO.getTamplateAd());

				//메세지 유형 채널추가형인 경우 채널추가 버튼 생성해주기
				btnJsonObj.put("name", "채널추가");
				btnJsonObj.put("linkType", "AC");
				btnJsonArr.add(btnJsonObj);
				
			}
			
			if(kakaoVO.getTemplateEmphasizeType().equals("TEXT")){
				jsonObject.put("templateTitle", kakaoVO.getTemplateTitle());
				jsonObject.put("templateSubtitle", kakaoVO.getTemplateSubtitle());
			}else if(kakaoVO.getTemplateEmphasizeType().equals("IMAGE")){
				jsonObject.put("templateImageUrl", kakaoVO.getTemplateImageUrl());
				jsonObject.put("templateImageName", kakaoVO.getTemplateImageName());
			}else if(kakaoVO.getTemplateEmphasizeType().equals("ITEM_LIST")){
				
			}

			
			List<KakaoButtonVO> buttonVOList = new ArrayList<KakaoButtonVO>();
			
			buttonVOList = kakaoVO.getButtonVOList();
			
			for(KakaoButtonVO buttonInfo : buttonVOList) {
				
				JSONObject btnTmpObj = new JSONObject();
				
				String linkType = buttonInfo.getLinkType();
				String name = buttonInfo.getName();
				String linkAnd = "";
				String linkIos = "";
				String linkMo = "";
				String linkPc = "";
				
				if(linkType.equals("WL")) {
					
					linkMo = buttonInfo.getLinkMo();
					linkPc = buttonInfo.getLinkPc();
					
					btnTmpObj.put("linkMo", linkMo);
					btnTmpObj.put("linkPc", linkPc);
					
				}else if(linkType.equals("AL")) {
					
					linkAnd = buttonInfo.getLinkAnd();
					linkIos = buttonInfo.getLinkIos();
					btnTmpObj.put("linkAnd", linkAnd);
					btnTmpObj.put("linkIos", linkIos);
					
				}
				
				if(!linkType.equals("") && !name.equals("")) {
				
					btnTmpObj.put("name", name);
					btnTmpObj.put("linkType", linkType);
					btnJsonArr.add(btnTmpObj);
					
				}
				
				
			}
			
			for(int i=0; i<btnJsonArr.size(); i++) {
				
				JSONObject tmpInfo = new JSONObject(); 
				
				tmpInfo = (JSONObject) btnJsonArr.get(i);
				
			}
			
			//버튼 정보가 있으면 추가
			if(btnJsonArr.size() > 0) {
				jsonObject.put("buttons", btnJsonArr);
			}
			
			
			HttpClient httpClient = HttpClientBuilder.create().build(); 
			HttpPost httpPost = new HttpPost(sendUrl); 
			httpPost.setEntity(new StringEntity(jsonObject.toString(), "UTF-8")); 
			httpPost.addHeader("Content-type", "application/json"); 
			httpPost.addHeader("Accept", "application/json");
			
			HttpResponse response = httpClient.execute(httpPost);

			String result = "";
			String statusCode = Integer.toString(response.getStatusLine().getStatusCode());
			
			if(statusCode.equals("200")) {
				
				result = EntityUtils.toString(response.getEntity()); 
				
				result = new String(result.getBytes("iso-8859-1"));//한글 깨짐 현상이 있어서 변환 해줌.
				System.out.println(result);
				JSONParser parser = new JSONParser();
				Object obj = parser.parse(result);
				JSONObject object = (JSONObject) obj;
				
				String code = object.get("code").toString();
				String msg = object.get("message").toString();
				
				kakaoReturnVO.setBizReturnCode(code);
				kakaoReturnVO.setBizReturnMsg(msg);
				
			}else {
				kakaoReturnVO.setBizReturnMsg("400 : 명령을 실행 오류");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return kakaoReturnVO;
	}
	
	/**
	* @Method Name : updateKakaoApiTemplate
	* @작성일 : 2023. 2. 17.
	* @작성자 :  우영두
	* @Method 설명 : 발신프로필 템플릿 수정
	*/
	@SuppressWarnings("unchecked")
	public KakaoReturnVO updateKakaoApiTemplate(KakaoVO kakaoVO) {
		KakaoReturnVO kakaoReturnVO = new KakaoReturnVO();
		try {
			
			String sendUrl = mjonBizUrl + "/v3/kakao/template/update";
			 
			JSONObject jsonObject = new JSONObject(); 
			//버튼 추가를 위한 배열 변수 선언
			JSONArray btnJsonArr = new JSONArray();
			JSONObject btnJsonObj = new JSONObject();
			
			jsonObject.put("bizId", mjonBizId);
			jsonObject.put("apiKey", mjonBizKakaoApiKey);
			jsonObject.put("senderKey", kakaoVO.getSenderKey());
			jsonObject.put("templateCode", kakaoVO.getTemplateCode());
			jsonObject.put("newTemplateCode", kakaoVO.getNewTemplateCode());
			jsonObject.put("templateName", kakaoVO.getTemplateName());
			jsonObject.put("templateMessageType", kakaoVO.getTemplateMessageType());
			jsonObject.put("templateEmphasizeType", kakaoVO.getTemplateEmphasizeType());
			jsonObject.put("templateContent", kakaoVO.getTemplateContent());
			jsonObject.put("categoryCode", kakaoVO.getCategoryCode());
			
			if(kakaoVO.getTemplateMessageType().equals("EX")) {
				jsonObject.put("templateExtra", kakaoVO.getTemplateExtra() );
			}else if(kakaoVO.getTemplateMessageType().equals("AD")) {
				//jsonObject.put("templateAd", kakaoVO.getTamplateAd());

				//메세지 유형 채널추가형인 경우 채널추가 버튼 생성해주기
				btnJsonObj.put("name", "채널추가");
				btnJsonObj.put("linkType", "AC");
				btnJsonArr.add(btnJsonObj);
				
			}else if(kakaoVO.getTemplateMessageType().equals("MI")) {
				jsonObject.put("templateExtra", kakaoVO.getTemplateExtra() );
				//jsonObject.put("templateAd", kakaoVO.getTamplateAd());

				//메세지 유형 채널추가형인 경우 채널추가 버튼 생성해주기
				btnJsonObj.put("name", "채널추가");
				btnJsonObj.put("linkType", "AC");
				btnJsonArr.add(btnJsonObj);
				
			}
			
			if(kakaoVO.getTemplateEmphasizeType().equals("TEXT")){
				jsonObject.put("templateTitle", kakaoVO.getTemplateTitle());
				jsonObject.put("templateSubtitle", kakaoVO.getTemplateSubtitle());
			}else if(kakaoVO.getTemplateEmphasizeType().equals("IMAGE")){
				jsonObject.put("templateImageUrl", kakaoVO.getTemplateImageUrl());
				jsonObject.put("templateImageName", kakaoVO.getTemplateImageName());
			}else if(kakaoVO.getTemplateEmphasizeType().equals("ITEM_LIST")){
				
			}

			
			List<KakaoButtonVO> buttonVOList = new ArrayList<KakaoButtonVO>();
			
			buttonVOList = kakaoVO.getButtonVOList();
			
			for(KakaoButtonVO buttonInfo : buttonVOList) {
				
				JSONObject btnTmpObj = new JSONObject();
				
				String linkType = buttonInfo.getLinkType();
				String name = buttonInfo.getName();
				String linkAnd = "";
				String linkIos = "";
				String linkMo = "";
				String linkPc = "";
				
				if(linkType.equals("WL")) {
					
					linkMo = buttonInfo.getLinkMo();
					linkPc = buttonInfo.getLinkPc();
					
					btnTmpObj.put("linkMo", linkMo);
					btnTmpObj.put("linkPc", linkPc);
					
				}else if(linkType.equals("AL")) {
					
					linkAnd = buttonInfo.getLinkAnd();
					linkIos = buttonInfo.getLinkIos();
					btnTmpObj.put("linkAnd", linkAnd);
					btnTmpObj.put("linkIos", linkIos);
					
				}
				
				
				if(!linkType.equals("") && !name.equals("")) {
					
					btnTmpObj.put("name", name);
					btnTmpObj.put("linkType", linkType);
					btnJsonArr.add(btnTmpObj);
				
				}
				
			}
			
			for(int i=0; i<btnJsonArr.size(); i++) {
				
				JSONObject tmpInfo = new JSONObject(); 
				
				tmpInfo = (JSONObject) btnJsonArr.get(i);
				
			}
			
			//버튼 정보가 있으면 추가
			if(btnJsonArr.size() > 0) {
				jsonObject.put("buttons", btnJsonArr);
			}
			
			
			HttpClient httpClient = HttpClientBuilder.create().build(); 
			HttpPost httpPost = new HttpPost(sendUrl); 
			httpPost.setEntity(new StringEntity(jsonObject.toString(), "UTF-8")); 
			httpPost.addHeader("Content-type", "application/json"); 
			httpPost.addHeader("Accept", "application/json");
			
			HttpResponse response = httpClient.execute(httpPost);

			String result = "";
			String statusCode = Integer.toString(response.getStatusLine().getStatusCode());
			
			if(statusCode.equals("200")) {
				
				result = EntityUtils.toString(response.getEntity()); 
				
				result = new String(result.getBytes("iso-8859-1"));//한글 깨짐 현상이 있어서 변환 해줌.
				JSONParser parser = new JSONParser();
				Object obj = parser.parse(result);
				JSONObject object = (JSONObject) obj;
				
				String code = object.get("code").toString();
				String msg = object.get("message").toString();
				
				kakaoReturnVO.setBizReturnCode(code);
				kakaoReturnVO.setBizReturnMsg(msg);
				
			}else {
				kakaoReturnVO.setBizReturnMsg("400 : 명령을 실행 오류");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return kakaoReturnVO;
	}
	
	/**
	* @Method Name : selectKakaoApiTemplate
	* @작성일 : 2023. 1. 25.
	* @작성자 :  WYH
	* @Method 설명 : 발신프로필 템플릿 조회
	*/
	@SuppressWarnings("unchecked")
	public KakaoReturnVO selectKakaoApiTemplate(KakaoVO kakaoVO) {
		KakaoReturnVO kakaoReturnVO = new KakaoReturnVO();
		try {
			
			String sendUrl = mjonBizUrl + "/v3/kakao/template/list";
			 
			JSONObject jsonObject = new JSONObject(); 
			jsonObject.put("bizId", mjonBizId);
			jsonObject.put("apiKey", mjonBizKakaoApiKey);
			jsonObject.put("senderKey", kakaoVO.getSenderKey());
			jsonObject.put("categoryCode", kakaoVO.getCategoryCode());
			
			//템플릿 페이징 처리	
			if(!"".equals(kakaoVO.getCount())) { //페이지 별 템플릿 개수. 디폴트 30	
				jsonObject.put("count", kakaoVO.getCount());	
			}	
			if(!"".equals(kakaoVO.getPage())) { //요청 페이지. 디폴트 1	
				jsonObject.put("page", kakaoVO.getPage());	
			}			
			
			// 알림톡 화면 템플릿 조회(승인난 템플릿만 조회)
			if(kakaoVO.getPageType().equals("notityTalk")) {
//				jsonObject.put("templateStatus", "ACT");
			}else if(!kakaoVO.getTemplateStatus().equals("")) {//템플릿 조회시 상태값이 넘어오면 해당 데이터만 조회, 없으면 전체 조회
				jsonObject.put("templateStatus", kakaoVO.getTemplateStatus());
			}
			
			if(!kakaoVO.getKeyword().equals("")) {
				jsonObject.put("keyword", kakaoVO.getKeyword());
			}
			
			HttpClient httpClient = HttpClientBuilder.create().build(); 
			HttpPost httpPost = new HttpPost(sendUrl); 
			httpPost.setEntity(new StringEntity(jsonObject.toString(), "UTF-8")); 
			httpPost.addHeader("Content-type", "application/json"); 
			httpPost.addHeader("Accept", "application/json");
			
			HttpResponse response = httpClient.execute(httpPost);

			String result = "";
			String statusCode = Integer.toString(response.getStatusLine().getStatusCode());
			
			if(statusCode.equals("200")) {
				
				result = EntityUtils.toString(response.getEntity()); 
				result = new String(result.getBytes("iso-8859-1"));//한글 깨짐 현상이 있어서 변환 해줌.
				JSONParser parser = new JSONParser();
				Object obj = parser.parse(result);
				JSONObject object = (JSONObject) obj;
				
				String code = object.get("code").toString();
				String msg = object.get("message").toString();
				kakaoReturnVO.setBizReturnCode(code);
				kakaoReturnVO.setBizReturnMsg(msg);
				
				if(code.equals("200")) {//kakao api 결과가 성공 코드이면 리턴 데이터 파싱 시작
					
					kakaoReturnVO.setTotalCount(object.get("totalCount").toString());
					kakaoReturnVO.setTotalPage(object.get("totalPage").toString());
					kakaoReturnVO.setCurrentPage(object.get("currentPage").toString());
					
					JSONObject data = (JSONObject) object.get("data"); //String type으로 리턴 됨.
					
					JSONArray tempJSONList = (JSONArray) data.get("list");

					List<KakaoReturnVO> templatList = new ArrayList<KakaoReturnVO>() ;
					for(int i=0; i < tempJSONList.size(); i++) {
						JSONObject templateInfo = (JSONObject)tempJSONList.get(i);
						KakaoReturnVO templateInfoVO = new KakaoReturnVO();
						
						String senderKey = templateInfo.get("senderKey").toString();
						String senderKeyType = templateInfo.get("senderKeyType").toString();
						String templateCode = templateInfo.get("templateCode").toString();
						String templateName = templateInfo.get("templateName").toString();
						String categoryCode = templateInfo.get("categoryCode").toString();
						String createdAt = templateInfo.get("createdAt").toString();
						String modifiedAt = templateInfo.get("modifiedAt").toString();
						String serviceStatus = templateInfo.get("serviceStatus").toString();
						
						templateInfoVO.setSenderKey(senderKey);
						templateInfoVO.setSenderKeyType(senderKeyType);
						templateInfoVO.setTemplateCode(templateCode);
						templateInfoVO.setTemplateName(templateName);
						templateInfoVO.setCategoryCode(categoryCode);
						templateInfoVO.setCreatedAt(createdAt);
						templateInfoVO.setModifiedAt(modifiedAt);
						
						if(serviceStatus.equals("REG")) {
							templateInfoVO.setServiceStatus("등록");
						}else if(serviceStatus.equals("REQ")) {
							templateInfoVO.setServiceStatus("검수요청");
						}else if(serviceStatus.equals("REJ")) {
							templateInfoVO.setServiceStatus("반려");
						}else if(serviceStatus.equals("STP")) {
							templateInfoVO.setServiceStatus("차단");
						}else if(serviceStatus.equals("RDY")) {
							templateInfoVO.setServiceStatus("발송전");
						}else if(serviceStatus.equals("ACT")) {
							templateInfoVO.setServiceStatus("정상");
						}else if(serviceStatus.equals("DMT")) {
							templateInfoVO.setServiceStatus("휴면");
						}else if(serviceStatus.equals("BLK")) {
							templateInfoVO.setServiceStatus("차단");
						}
						
						templatList.add(templateInfoVO);
					}
					kakaoReturnVO.setTemplatList(templatList);
				}
				
			}else {
				kakaoReturnVO.setBizReturnMsg("400 : 명령을 실행 오류");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return kakaoReturnVO;
	}
	
	/**
	* @Method Name : requestKakaoApiTemplate
	* @작성일 : 2023. 1. 30.
	* @작성자 :  WYH
	* @Method 설명 : 템플릿 검수 요청
	*/
	public KakaoReturnVO requestKakaoApiTemplate(KakaoVO kakaoVO) {
		KakaoReturnVO kakaoReturnVO = new KakaoReturnVO();
		try {
			
			String sendUrl = mjonBizUrl + "/v3/kakao/template/request";
			 
			JSONObject jsonObject = new JSONObject(); 
			jsonObject.put("bizId", mjonBizId);
			jsonObject.put("apiKey", mjonBizKakaoApiKey);
			jsonObject.put("senderKey", kakaoVO.getSenderKey());
//			jsonObject.put("senderKeyType", kakaoVO.getSenderKeyType());
			jsonObject.put("templateCode", kakaoVO.getTemplateCode());
			
			HttpClient httpClient = HttpClientBuilder.create().build(); 
			HttpPost httpPost = new HttpPost(sendUrl); 
			httpPost.setEntity(new StringEntity(jsonObject.toString(), "UTF-8")); 
			httpPost.addHeader("Content-type", "application/json"); 
			httpPost.addHeader("Accept", "application/json");
			
			HttpResponse response = httpClient.execute(httpPost);

			String result = "";
			String statusCode = Integer.toString(response.getStatusLine().getStatusCode());
			
			if(statusCode.equals("200")) {
				
				result = EntityUtils.toString(response.getEntity()); 
				
				result = new String(result.getBytes("iso-8859-1"));//한글 깨짐 현상이 있어서 변환 해줌.
				JSONParser parser = new JSONParser();
				Object obj = parser.parse(result);
				JSONObject object = (JSONObject) obj;
				
				String code = object.get("code").toString();
				String msg = object.get("message").toString();
				
				kakaoReturnVO.setBizReturnCode(code);
				kakaoReturnVO.setBizReturnMsg(msg);
				
			}else {
				kakaoReturnVO.setBizReturnMsg("400 : 명령을 실행 오류");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return kakaoReturnVO;
	}
	
	/**
	* @Method Name : requestCancelKakaoApiTemplate
	* @작성일 : 2023. 3. 10.
	* @작성자 :  우영두
	* @Method 설명 : 템플릿 검수 요청 취소
	*/
	public KakaoReturnVO requestCancelKakaoApiTemplate(KakaoVO kakaoVO) {
		KakaoReturnVO kakaoReturnVO = new KakaoReturnVO();
		try {
			
			String sendUrl = mjonBizUrl + "/v3/kakao/template/cancel_request";
			 
			JSONObject jsonObject = new JSONObject(); 
			jsonObject.put("bizId", mjonBizId);
			jsonObject.put("apiKey", mjonBizKakaoApiKey);
			jsonObject.put("senderKey", kakaoVO.getSenderKey());
			jsonObject.put("templateCode", kakaoVO.getTemplateCode());
			
			HttpClient httpClient = HttpClientBuilder.create().build(); 
			HttpPost httpPost = new HttpPost(sendUrl); 
			httpPost.setEntity(new StringEntity(jsonObject.toString(), "UTF-8")); 
			httpPost.addHeader("Content-type", "application/json"); 
			httpPost.addHeader("Accept", "application/json");
			
			HttpResponse response = httpClient.execute(httpPost);

			String result = "";
			String statusCode = Integer.toString(response.getStatusLine().getStatusCode());
			
			if(statusCode.equals("200")) {
				
				result = EntityUtils.toString(response.getEntity()); 
				
				result = new String(result.getBytes("iso-8859-1"));//한글 깨짐 현상이 있어서 변환 해줌.
				JSONParser parser = new JSONParser();
				Object obj = parser.parse(result);
				JSONObject object = (JSONObject) obj;
				
				String code = object.get("code").toString();
				String msg = object.get("message").toString();
				
				kakaoReturnVO.setBizReturnCode(code);
				kakaoReturnVO.setBizReturnMsg(msg);
				
			}else {
				kakaoReturnVO.setBizReturnMsg("400 : 명령을 실행 오류");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return kakaoReturnVO;
	}
	
	
	/**
	* @Method Name : selectKakaoApiTemplateDetail
	* @작성일 : 2023. 1. 31.
	* @작성자 :  WYH
	* @Method 설명 : 템플릿 상세 정보
	*/
	public KakaoReturnVO selectKakaoApiTemplateDetail(KakaoVO kakaoVO) {
		KakaoReturnVO kakaoReturnVO = new KakaoReturnVO();
		try {
			
			String sendUrl = mjonBizUrl + "/v3/kakao/template/detail";
			 
			JSONObject jsonObject = new JSONObject(); 
			jsonObject.put("bizId", mjonBizId);
			jsonObject.put("apiKey", mjonBizKakaoApiKey);
			jsonObject.put("senderKey", kakaoVO.getSenderKey());
			jsonObject.put("templateCode", kakaoVO.getTemplateCode());
			
			HttpClient httpClient = HttpClientBuilder.create().build(); 
			HttpPost httpPost = new HttpPost(sendUrl); 
			httpPost.setEntity(new StringEntity(jsonObject.toString(), "UTF-8")); 
			httpPost.addHeader("Content-type", "application/json"); 
			httpPost.addHeader("Accept", "application/json");
			
			HttpResponse response = httpClient.execute(httpPost);

			String result = "";
			String statusCode = Integer.toString(response.getStatusLine().getStatusCode());
			
			if(statusCode.equals("200")) {
				
				result = EntityUtils.toString(response.getEntity()); 
				result = new String(result.getBytes("iso-8859-1"));//한글 깨짐 현상이 있어서 변환 해줌.
				JSONParser parser = new JSONParser();
				Object obj = parser.parse(result);
				JSONObject object = (JSONObject) obj;
				
				
				String code = object.get("code").toString();
				String msg = object.get("message").toString();
				
				kakaoReturnVO.setBizReturnCode(code);
				kakaoReturnVO.setBizReturnMsg(msg);
				
				if(code.equals("200")) {//kakao api 결과가 성공 코드이면 리턴 데이터 파싱 시작
					
					JSONObject templateInfo = (JSONObject) object.get("data");
					
					String templateCode = (templateInfo.get("templateCode") == null) ? null : templateInfo.get("templateCode").toString();
					kakaoReturnVO.setTemplateCode(templateCode);
					
					String templateName = (templateInfo.get("templateName") == null) ? null : templateInfo.get("templateName").toString();
					kakaoReturnVO.setTemplateName(templateName);
					
					String templateMessageType = (templateInfo.get("templateMessageType") == null) ? null : templateInfo.get("templateMessageType").toString();
					kakaoReturnVO.setTemplateMessageType(templateMessageType);
					
					String templateEmphasizeType = (templateInfo.get("templateEmphasizeType") == null) ? null : templateInfo.get("templateEmphasizeType").toString();
					kakaoReturnVO.setTemplateEmphasizeType(templateEmphasizeType);
					
					String templateContent = (templateInfo.get("templateContent") == null) ? null : templateInfo.get("templateContent").toString();
					kakaoReturnVO.setTemplateContent(templateContent);
					
					String templateExtra = (templateInfo.get("templateExtra") == null) ? null : templateInfo.get("templateExtra").toString();
					kakaoReturnVO.setTemplateExtra(templateExtra);
					
					String templateAd = (templateInfo.get("templateAd") == null) ? null : templateInfo.get("templateAd").toString();
					kakaoReturnVO.setTemplateAd(templateAd);
					
					String templateImageName = (templateInfo.get("templateImageName") == null) ? null : templateInfo.get("templateImageName").toString();
					kakaoReturnVO.setTemplateImageName(templateImageName);
					
					String templateImageUrl = (templateInfo.get("templateImageUrl") == null) ? null : templateInfo.get("templateImageUrl").toString();
					kakaoReturnVO.setTemplateImageUrl(templateImageUrl);
					
					String templateTitle = (templateInfo.get("templateTitle") == null) ? null : templateInfo.get("templateTitle").toString();
					kakaoReturnVO.setTemplateTitle(templateTitle);
					
					String templateSubtitle = (templateInfo.get("templateSubtitle") == null) ? null : templateInfo.get("templateSubtitle").toString();
					kakaoReturnVO.setTemplateSubtitle(templateSubtitle);
					
					String templateHeader = (templateInfo.get("templateHeader") == null) ? null : templateInfo.get("templateHeader").toString();
					kakaoReturnVO.setTemplateHeader(templateHeader);
					
					String categoryCode = (templateInfo.get("categoryCode") == null) ? null : templateInfo.get("categoryCode").toString();
					kakaoReturnVO.setCategoryCode(categoryCode);
					
					Boolean securityFlag = (Boolean) templateInfo.get("securityFlag");
					kakaoReturnVO.setSecurityFlag(securityFlag);
					
					String inspectionStatus = (templateInfo.get("inspectionStatus") == null) ? null : templateInfo.get("inspectionStatus").toString();
					kakaoReturnVO.setInspectionStatus(inspectionStatus);
					
					String createdAt = (templateInfo.get("createdAt") == null) ? null : templateInfo.get("createdAt").toString();
					kakaoReturnVO.setCreatedAt(createdAt);
					
					String modifiedAt = (templateInfo.get("modifiedAt") == null) ? null : templateInfo.get("modifiedAt").toString();
					kakaoReturnVO.setModifiedAt(modifiedAt);
					
					String status = (templateInfo.get("status") == null) ? null : templateInfo.get("status").toString();
					kakaoReturnVO.setStatus(status);
					
					boolean block = (boolean) templateInfo.get("block");
					kakaoReturnVO.setBlock(block);
					
					boolean dormant = (boolean) templateInfo.get("dormant");
					kakaoReturnVO.setDormant(dormant);
					
					// @@ 아이탬 하이라이트 및 아이탬 정보 파싱 관련 문의
					//아이템 하이라이트(강조형)
					if(templateInfo.get("templateItemHighlight") != null) {
						
						JSONObject templateItemHighlight = (JSONObject) templateInfo.get("templateItemHighlight");
						
						String higtLightTitle = (templateItemHighlight.get("title") == null) ? null : templateItemHighlight.get("title").toString();
						String higtLightDesc = (templateItemHighlight.get("description") == null) ? null : templateItemHighlight.get("description").toString();
						String higtLightImgUrl = (templateItemHighlight.get("imageUrl") == null) ? null : templateItemHighlight.get("imageUrl").toString();
						
						kakaoReturnVO.setTitle(higtLightTitle);
						kakaoReturnVO.setDescription(higtLightDesc);
						kakaoReturnVO.setImageUrl(higtLightImgUrl);
						
					}
					
					//템플릿 아이템 정보 처리 해주기
					if(templateInfo.get("templateItem") != null) {
						
						JSONObject templateItemInfo = (JSONObject) templateInfo.get("templateItem");
						
						if(templateItemInfo.get("list") != null) {//아이템 리스트의 정보가 있으면
							
							JSONArray itemList = (JSONArray) templateItemInfo.get("list");
							
							if(itemList.size() != 0) {
								List<KakaoItemVO> itemVOList = new ArrayList<KakaoItemVO>();
								for(int i=0; i < itemList.size(); i++) {
									JSONObject itemInfo = (JSONObject)itemList.get(i);
									KakaoItemVO itemVO = new KakaoItemVO();
									
									String title = (itemInfo.get("title") == null) ? null : itemInfo.get("title").toString();					//타이틀
									String description = (itemInfo.get("description") == null) ? null : itemInfo.get("description").toString();	//디스크립션
									
									itemVO.setTitle(title);
									itemVO.setDescription(description);
									
									itemVOList.add(itemVO);
									
								}
								
								if(itemVOList != null) {
									kakaoReturnVO.setItemList(itemVOList);	
								}
							}
							
						}
						
						
						
						if(templateItemInfo.get("summary") != null) {//아이템 요약정보 정보 처리해주기
							
							JSONObject templateItemSummary = (JSONObject) templateItemInfo.get("summary");
							
							String sumTitle = (templateItemSummary.get("title") == null) ? null : templateItemSummary.get("title").toString();
							String sumDescription = (templateItemSummary.get("description") == null) ? null : templateItemSummary.get("description").toString();
							
							kakaoReturnVO.setSumTitle(sumTitle);
							kakaoReturnVO.setSumDescription(sumDescription);
							
						}
						
						
						
					}
					
					
					//버튼 정보 처리 해주기
					if(templateInfo.get("buttons") != null) {
						
						JSONArray buttonList = (JSONArray) templateInfo.get("buttons");
						if(buttonList.size() != 0) {
							List<KakaoButtonVO> buttonVOList = new ArrayList<KakaoButtonVO>();
							for(int i=0; i < buttonList.size(); i++) {
								JSONObject buttonInfo = (JSONObject)buttonList.get(i);
								KakaoButtonVO buttonVO = new KakaoButtonVO();
								
								String name = (buttonInfo.get("name") == null) ? null : buttonInfo.get("name").toString();				//버튼명
								String linkType = (buttonInfo.get("linkType") == null) ? null : buttonInfo.get("linkType").toString();	//버튼 일크타입
								String linkAnd = (buttonInfo.get("linkAnd") == null) ? null : buttonInfo.get("linkAnd").toString();		//Android 앱 링크 주소
								String linkIos = (buttonInfo.get("linkIos") == null) ? null : buttonInfo.get("linkIos").toString();		//ios 앱 링크 주소
								String linkMo = (buttonInfo.get("linkMo") == null) ? null : buttonInfo.get("linkMo").toString();		//모바일 웹 링크 주소
								String linkPc = (buttonInfo.get("linkPc") == null) ? null : buttonInfo.get("linkPc").toString();		//PC 웹 링크 주소
								String pluginId = (buttonInfo.get("pluginId") == null) ? null : buttonInfo.get("pluginId").toString();	//플러그인 ID
								
								buttonVO.setName(name);
								buttonVO.setLinkType(linkType);
								buttonVO.setLinkAnd(linkAnd);
								buttonVO.setLinkIos(linkIos);
								buttonVO.setLinkMo(linkMo);
								buttonVO.setLinkPc(linkPc);
								buttonVO.setPluginId(pluginId);
								
								buttonVOList.add(buttonVO);
								
							}
							
							if(buttonVOList != null) {
								kakaoReturnVO.setButtonList(buttonVOList);	
							}
						}
					}
					
					//바로연결 정보 처리
					if(templateInfo.get("quickReplies") != null) {
						
						JSONArray quickReplyList = (JSONArray) templateInfo.get("quickReplies");
						if(quickReplyList.size() != 0) {
							List<KakaoButtonVO> quickReplyVOList = new ArrayList<KakaoButtonVO>();
							for(int i=0; i < quickReplyList.size(); i++) {
								JSONObject quickReplyInfo = (JSONObject)quickReplyList.get(i);
								KakaoButtonVO quickReplyVO = new KakaoButtonVO();
								
								String quickName = (quickReplyInfo.get("name") == null) ? null : quickReplyInfo.get("name").toString();			//버튼명
								String quickLinkType = (quickReplyInfo.get("linkType") == null) ? null : quickReplyInfo.get("linkType").toString();		//버튼 일크타입
								String quickLinkAnd = (quickReplyInfo.get("linkAnd") == null) ? null : quickReplyInfo.get("linkAnd").toString();		//Android 앱 링크 주소
								String quickLinkIos = (quickReplyInfo.get("linkIos") == null) ? null : quickReplyInfo.get("linkIos").toString();		//ios 앱 링크 주소
								String quickLinkMo = (quickReplyInfo.get("linkMo") == null) ? null : quickReplyInfo.get("linkMo").toString();		//모바일 웹 링크 주소
								String quickLinkPc = (quickReplyInfo.get("linkPc") == null) ? null : quickReplyInfo.get("linkPc").toString();		//PC 웹 링크 주소
								
								quickReplyVO.setName(quickName);
								quickReplyVO.setLinkType(quickLinkType);
								quickReplyVO.setLinkAnd(quickLinkAnd);
								quickReplyVO.setLinkIos(quickLinkIos);
								quickReplyVO.setLinkMo(quickLinkMo);
								quickReplyVO.setLinkPc(quickLinkPc);
								
								quickReplyVOList.add(quickReplyVO);
							}
							
							
							if(quickReplyVOList != null) {
								kakaoReturnVO.setQuickReplyList(quickReplyVOList);	
							}
						}
					}
					
					//댓글 목록 정보 
					if(templateInfo.get("comments") != null) {
						
						JSONArray commentList = (JSONArray) templateInfo.get("comments");
						if(commentList.size() != 0) {
							List<KakaoCommentVO> commentVOList = new ArrayList<KakaoCommentVO>();
							for(int i=0; i < commentList.size(); i++) {
								JSONObject commentInfo = (JSONObject)commentList.get(i);
								KakaoCommentVO kakaoCommentVO = new KakaoCommentVO();
								
								String content = (commentInfo.get("content") == null) ? null : commentInfo.get("content").toString();
								String commentInfoCreatedAt = (commentInfo.get("createdAt") == null) ? null : commentInfo.get("createdAt").toString();
								String commentInfoStatus = (commentInfo.get("status") == null) ? null : commentInfo.get("status").toString();
								String userName = (commentInfo.get("userName") == null) ? null : commentInfo.get("userName").toString();
								
								kakaoCommentVO.setContent(content);
								kakaoCommentVO.setCreatedAt(commentInfoCreatedAt);
								kakaoCommentVO.setStatus(commentInfoStatus);
								kakaoCommentVO.setUserName(userName);
								
								if(commentInfo.get("attachment") != null) {
									
									List<KakaoCommentVO> attachVOList = new ArrayList<KakaoCommentVO>();
									JSONArray attachList = (JSONArray) commentInfo.get("attachment");
									for(int j=0; j < attachList.size(); j++) {
										JSONObject attachmentInfo = (JSONObject)attachList.get(i);
										KakaoCommentVO attachVO = new KakaoCommentVO();
										
										String fileName = (attachmentInfo.get("originalFileName") == null) ? null : attachmentInfo.get("originalFileName").toString();
										String filePath = (attachmentInfo.get("filePath") == null) ? null : attachmentInfo.get("filePath").toString();
										
										attachVO.setOriginalFileName(fileName);
										attachVO.setFilePath(filePath);
										
										attachVOList.add(attachVO);
									}
									
									if(attachVOList != null) {
										
										kakaoCommentVO.setAttachFileList(attachVOList);
									}
								}
								commentVOList.add(kakaoCommentVO);
							}
							
							if(commentVOList != null) {
								kakaoReturnVO.setCommentList(commentVOList);
							}
						}
					}
				}
				
			}else {
				kakaoReturnVO.setBizReturnMsg("400 : 명령을 실행 오류");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return kakaoReturnVO;
	}
	
	
	/**
	* @Method Name : selectKakaoApiSimpleTemplateDetail
	* @작성일 : 2023. 2. 17.
	* @작성자 :  우영두
	* @Method 설명 : 템플릿 상세 정보(필수 항목만 결과를 Parsing 처리함)
	* , 템플릿 리스트의 내용 상세정보 표시를 위해 사용
	* , 기존 상세정보는 결과 처리에 시간이 많이 걸려서 별도로 만들었음
	*/
	@SuppressWarnings("unchecked")
	public KakaoReturnVO selectKakaoApiSimpleTemplateDetail(KakaoVO kakaoVO) {
		KakaoReturnVO kakaoReturnVO = new KakaoReturnVO();
		try {
			
			String sendUrl = mjonBizUrl + "/v3/kakao/template/detail";
			 
			JSONObject jsonObject = new JSONObject(); 
			jsonObject.put("bizId", mjonBizId);
			jsonObject.put("apiKey", mjonBizKakaoApiKey);
			jsonObject.put("senderKey", kakaoVO.getSenderKey());
			jsonObject.put("templateCode", kakaoVO.getTemplateCode());
			
			HttpClient httpClient = HttpClientBuilder.create().build(); 
			HttpPost httpPost = new HttpPost(sendUrl); 
			httpPost.setEntity(new StringEntity(jsonObject.toString(), "UTF-8")); 
			httpPost.addHeader("Content-type", "application/json"); 
			httpPost.addHeader("Accept", "application/json");
			
			HttpResponse response = httpClient.execute(httpPost);

			String result = "";
			String statusCode = Integer.toString(response.getStatusLine().getStatusCode());
			
			Date startDate = new Date();
			System.out.println(startDate);
			if(statusCode.equals("200")) {
				
				result = EntityUtils.toString(response.getEntity()); 
				result = new String(result.getBytes("iso-8859-1"));//한글 깨짐 현상이 있어서 변환 해줌.
				JSONParser parser = new JSONParser();
				Object obj = parser.parse(result);
				JSONObject object = (JSONObject) obj;
				
				
				String code = object.get("code").toString();
				String msg = object.get("message").toString();
				
				kakaoReturnVO.setBizReturnCode(code);
				kakaoReturnVO.setBizReturnMsg(msg);
				
				if(code.equals("200")) {//kakao api 결과가 성공 코드이면 리턴 데이터 파싱 시작
					
					JSONObject templateInfo = (JSONObject) object.get("data");
					
					String templateCode = (templateInfo.get("templateCode") == null) ? null : templateInfo.get("templateCode").toString();
					kakaoReturnVO.setTemplateCode(templateCode);
					
					String templateName = (templateInfo.get("templateName") == null) ? null : templateInfo.get("templateName").toString();
					kakaoReturnVO.setTemplateName(templateName);
					
					String templateMessageType = (templateInfo.get("templateMessageType") == null) ? null : templateInfo.get("templateMessageType").toString();
					kakaoReturnVO.setTemplateMessageType(templateMessageType);
					
					String templateEmphasizeType = (templateInfo.get("templateEmphasizeType") == null) ? null : templateInfo.get("templateEmphasizeType").toString();
					kakaoReturnVO.setTemplateEmphasizeType(templateEmphasizeType);
					
					String templateContent = (templateInfo.get("templateContent") == null) ? null : templateInfo.get("templateContent").toString();
					kakaoReturnVO.setTemplateContent(templateContent);
					
					String templateExtra = (templateInfo.get("templateExtra") == null) ? null : templateInfo.get("templateExtra").toString();
					kakaoReturnVO.setTemplateExtra(templateExtra);
					
					String templateAd = (templateInfo.get("templateAd") == null) ? null : templateInfo.get("templateAd").toString();
					kakaoReturnVO.setTemplateAd(templateAd);
					
					String templateImageName = (templateInfo.get("templateImageName") == null) ? null : templateInfo.get("templateImageName").toString();
					kakaoReturnVO.setTemplateImageName(templateImageName);
					
					String templateImageUrl = (templateInfo.get("templateImageUrl") == null) ? null : templateInfo.get("templateImageUrl").toString();
					kakaoReturnVO.setTemplateImageUrl(templateImageUrl);
					
					String templateTitle = (templateInfo.get("templateTitle") == null) ? null : templateInfo.get("templateTitle").toString();
					kakaoReturnVO.setTemplateTitle(templateTitle);
					
					String templateSubtitle = (templateInfo.get("templateSubtitle") == null) ? null : templateInfo.get("templateSubtitle").toString();
					kakaoReturnVO.setTemplateSubtitle(templateSubtitle);
					
					//String templateHeader = (templateInfo.get("templateHeader") == null) ? null : templateInfo.get("templateHeader").toString();
					//kakaoReturnVO.setTemplateHeader(templateHeader);
					
					String categoryCode = (templateInfo.get("categoryCode") == null) ? null : templateInfo.get("categoryCode").toString();
					kakaoReturnVO.setCategoryCode(categoryCode);
					
					//Boolean securityFlag = (Boolean) templateInfo.get("securityFlag");
					//kakaoReturnVO.setSecurityFlag(securityFlag);
					
					//템플릿 검수상태값
					String inspectionStatus = (templateInfo.get("inspectionStatus") == null) ? null : templateInfo.get("inspectionStatus").toString();
					kakaoReturnVO.setInspectionStatus(inspectionStatus);
					
					//템플릿 등록일자
					String createdAt = (templateInfo.get("createdAt") == null) ? null : templateInfo.get("createdAt").toString();
					kakaoReturnVO.setCreatedAt(createdAt);
					
					//템플릿 수정일자
					String modifiedAt = (templateInfo.get("modifiedAt") == null) ? null : templateInfo.get("modifiedAt").toString();
					kakaoReturnVO.setModifiedAt(modifiedAt);
					
					//템플릿 상태 - S: 중지, A: 정상, R: 대기(발송전)
					String status = (templateInfo.get("status") == null) ? null : templateInfo.get("status").toString();
					kakaoReturnVO.setStatus(status);
					
					//템플릿 차단 여부 (true:차단, false: 해제)
					boolean block = (boolean) templateInfo.get("block");
					kakaoReturnVO.setBlock(block);
					
					//템플릿 휴면 여부 (true:휴면, false: 해제)
					boolean dormant = (boolean) templateInfo.get("dormant");
					kakaoReturnVO.setDormant(dormant);
					
					// @@ 아이탬 하이라이트 및 아이탬 정보 파싱 관련 문의
					//아이템 하이라이트(강조형)
					/*if(templateInfo.get("templateItemHighlight") != null) {
						
						JSONObject templateItemHighlight = (JSONObject) templateInfo.get("templateItemHighlight");
						
						String higtLightTitle = (templateItemHighlight.get("title") == null) ? null : templateItemHighlight.get("title").toString();
						String higtLightDesc = (templateItemHighlight.get("description") == null) ? null : templateItemHighlight.get("description").toString();
						String higtLightImgUrl = (templateItemHighlight.get("imageUrl") == null) ? null : templateItemHighlight.get("imageUrl").toString();
						
						kakaoReturnVO.setTitle(higtLightTitle);
						kakaoReturnVO.setDescription(higtLightDesc);
						kakaoReturnVO.setImageUrl(higtLightImgUrl);
						
					}*/
					
					//템플릿 아이템 정보 처리 해주기
					/*if(templateInfo.get("templateItem") != null) {
						
						JSONObject templateItemInfo = (JSONObject) templateInfo.get("templateItem");
						
						if(templateItemInfo.get("list") != null) {//아이템 리스트의 정보가 있으면
							
							JSONArray itemList = (JSONArray) templateItemInfo.get("list");
							
							if(itemList.size() != 0) {
								List<KakaoItemVO> itemVOList = new ArrayList<KakaoItemVO>();
								for(int i=0; i < itemList.size(); i++) {
									JSONObject itemInfo = (JSONObject)itemList.get(i);
									KakaoItemVO itemVO = new KakaoItemVO();
									
									String title = (itemInfo.get("title") == null) ? null : itemInfo.get("title").toString();					//타이틀
									String description = (itemInfo.get("description") == null) ? null : itemInfo.get("description").toString();	//디스크립션
									
									itemVO.setTitle(title);
									itemVO.setDescription(description);
									
									itemVOList.add(itemVO);
									
								}
								
								if(itemVOList != null) {
									kakaoReturnVO.setItemList(itemVOList);	
								}
							}
							
						}
						
						
						if(templateItemInfo.get("summary") != null) {//아이템 요약정보 정보 처리해주기
							
							JSONObject templateItemSummary = (JSONObject) templateItemInfo.get("summary");
							
							String sumTitle = (templateItemSummary.get("title") == null) ? null : templateItemSummary.get("title").toString();
							String sumDescription = (templateItemSummary.get("description") == null) ? null : templateItemSummary.get("description").toString();
							
							kakaoReturnVO.setSumTitle(sumTitle);
							kakaoReturnVO.setSumDescription(sumDescription);
							
						}
						
					}*/
					
					
					//버튼 정보 처리 해주기
					if(templateInfo.get("buttons") != null) {
						
						JSONArray buttonList = (JSONArray) templateInfo.get("buttons");
						if(buttonList.size() != 0) {
							List<KakaoButtonVO> buttonVOList = new ArrayList<KakaoButtonVO>();
							for(int i=0; i < buttonList.size(); i++) {
								JSONObject buttonInfo = (JSONObject)buttonList.get(i);
								KakaoButtonVO buttonVO = new KakaoButtonVO();
								
								String name = (buttonInfo.get("name") == null) ? null : buttonInfo.get("name").toString();				//버튼명
								String linkType = (buttonInfo.get("linkType") == null) ? null : buttonInfo.get("linkType").toString();	//버튼 일크타입
								String linkAnd = (buttonInfo.get("linkAnd") == null) ? null : buttonInfo.get("linkAnd").toString();		//Android 앱 링크 주소
								String linkIos = (buttonInfo.get("linkIos") == null) ? null : buttonInfo.get("linkIos").toString();		//ios 앱 링크 주소
								String linkMo = (buttonInfo.get("linkMo") == null) ? null : buttonInfo.get("linkMo").toString();		//모바일 웹 링크 주소
								String linkPc = (buttonInfo.get("linkPc") == null) ? null : buttonInfo.get("linkPc").toString();		//PC 웹 링크 주소
								String pluginId = (buttonInfo.get("pluginId") == null) ? null : buttonInfo.get("pluginId").toString();	//플러그인 ID
								
								buttonVO.setName(name);
								buttonVO.setLinkType(linkType);
								buttonVO.setLinkAnd(linkAnd);
								buttonVO.setLinkIos(linkIos);
								buttonVO.setLinkMo(linkMo);
								buttonVO.setLinkPc(linkPc);
								buttonVO.setPluginId(pluginId);
								
								buttonVOList.add(buttonVO);
								
							}
							
							if(buttonVOList != null) {
								kakaoReturnVO.setButtonList(buttonVOList);	
							}
						}
					}
					
					//바로연결 정보 처리
					/*if(templateInfo.get("quickReplies") != null) {
						
						JSONArray quickReplyList = (JSONArray) templateInfo.get("quickReplies");
						if(quickReplyList.size() != 0) {
							List<KakaoButtonVO> quickReplyVOList = new ArrayList<KakaoButtonVO>();
							for(int i=0; i < quickReplyList.size(); i++) {
								JSONObject quickReplyInfo = (JSONObject)quickReplyList.get(i);
								KakaoButtonVO quickReplyVO = new KakaoButtonVO();
								
								String quickName = (quickReplyInfo.get("name") == null) ? null : quickReplyInfo.get("name").toString();			//버튼명
								String quickLinkType = (quickReplyInfo.get("linkType") == null) ? null : quickReplyInfo.get("linkType").toString();		//버튼 일크타입
								String quickLinkAnd = (quickReplyInfo.get("linkAnd") == null) ? null : quickReplyInfo.get("linkAnd").toString();		//Android 앱 링크 주소
								String quickLinkIos = (quickReplyInfo.get("linkIos") == null) ? null : quickReplyInfo.get("linkIos").toString();		//ios 앱 링크 주소
								String quickLinkMo = (quickReplyInfo.get("linkMo") == null) ? null : quickReplyInfo.get("linkMo").toString();		//모바일 웹 링크 주소
								String quickLinkPc = (quickReplyInfo.get("linkPc") == null) ? null : quickReplyInfo.get("linkPc").toString();		//PC 웹 링크 주소
								
								quickReplyVO.setName(quickName);
								quickReplyVO.setLinkType(quickLinkType);
								quickReplyVO.setLinkAnd(quickLinkAnd);
								quickReplyVO.setLinkIos(quickLinkIos);
								quickReplyVO.setLinkMo(quickLinkMo);
								quickReplyVO.setLinkPc(quickLinkPc);
								
								quickReplyVOList.add(quickReplyVO);
							}
							
							
							if(quickReplyVOList != null) {
								kakaoReturnVO.setQuickReplyList(quickReplyVOList);	
							}
						}
					}*/
					
					//댓글 목록 정보 
					/*if(templateInfo.get("comments") != null) {
						
						JSONArray commentList = (JSONArray) templateInfo.get("comments");
						if(commentList.size() != 0) {
							List<KakaoCommentVO> commentVOList = new ArrayList<KakaoCommentVO>();
							for(int i=0; i < commentList.size(); i++) {
								JSONObject commentInfo = (JSONObject)commentList.get(i);
								KakaoCommentVO kakaoCommentVO = new KakaoCommentVO();
								
								String content = (commentInfo.get("content") == null) ? null : commentInfo.get("content").toString();
								String commentInfoCreatedAt = (commentInfo.get("createdAt") == null) ? null : commentInfo.get("createdAt").toString();
								String commentInfoStatus = (commentInfo.get("status") == null) ? null : commentInfo.get("status").toString();
								String userName = (commentInfo.get("userName") == null) ? null : commentInfo.get("userName").toString();
								
								kakaoCommentVO.setContent(content);
								kakaoCommentVO.setCreatedAt(commentInfoCreatedAt);
								kakaoCommentVO.setStatus(commentInfoStatus);
								kakaoCommentVO.setUserName(userName);
								
								if(commentInfo.get("attachment") != null) {
									
									List<KakaoCommentVO> attachVOList = new ArrayList<KakaoCommentVO>();
									JSONArray attachList = (JSONArray) commentInfo.get("attachment");
									for(int j=0; j < attachList.size(); j++) {
										JSONObject attachmentInfo = (JSONObject)attachList.get(i);
										KakaoCommentVO attachVO = new KakaoCommentVO();
										
										String fileName = (attachmentInfo.get("originalFileName") == null) ? null : attachmentInfo.get("originalFileName").toString();
										String filePath = (attachmentInfo.get("filePath") == null) ? null : attachmentInfo.get("filePath").toString();
										
										attachVO.setOriginalFileName(fileName);
										attachVO.setFilePath(filePath);
										
										attachVOList.add(attachVO);
									}
									
									if(attachVOList != null) {
										
										kakaoCommentVO.setAttachFileList(attachVOList);
									}
								}
								commentVOList.add(kakaoCommentVO);
							}
							
							if(commentVOList != null) {
								kakaoReturnVO.setCommentList(commentVOList);
							}
						}
					}*/
				}
				
			}else {
				kakaoReturnVO.setBizReturnMsg("400 : 명령을 실행 오류");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		Date endDate = new Date();
		System.out.println("++++++++++++++++++++++ end ::: "+endDate);
		
		return kakaoReturnVO;
	}
	
	
	
	/**
	* @Method Name : deleteKakaoApiTemplate
	* @작성일 : 2023. 2. 14.
	* @작성자 :  WYH
	* @Method 설명 : 등록  템플릿 삭제
	*/
	@SuppressWarnings("unchecked")
	public KakaoReturnVO deleteKakaoApiTemplate(KakaoVO kakaoVO) {
		KakaoReturnVO kakaoReturnVO = new KakaoReturnVO();
		try {
			
			String sendUrl = mjonBizUrl + "/v3/kakao/template/delete";
			 
			JSONObject jsonObject = new JSONObject(); 
			jsonObject.put("bizId", mjonBizId);
			jsonObject.put("apiKey", mjonBizKakaoApiKey);
			jsonObject.put("senderKey", kakaoVO.getSenderKey());
			jsonObject.put("templateCode", kakaoVO.getTemplateCode());
			
			
			HttpClient httpClient = HttpClientBuilder.create().build(); 
			HttpPost httpPost = new HttpPost(sendUrl); 
			httpPost.setEntity(new StringEntity(jsonObject.toString(), "UTF-8")); 
			httpPost.addHeader("Content-type", "application/json"); 
			httpPost.addHeader("Accept", "application/json");
			
			HttpResponse response = httpClient.execute(httpPost);

			String result = "";
			String statusCode = Integer.toString(response.getStatusLine().getStatusCode());
			
			if(statusCode.equals("200")) {
				
				result = EntityUtils.toString(response.getEntity()); 
				result = new String(result.getBytes("iso-8859-1"));//한글 깨짐 현상이 있어서 변환 해줌.
				JSONParser parser = new JSONParser();
				Object obj = parser.parse(result);
				JSONObject object = (JSONObject) obj;
				
				String code = object.get("code").toString();
				String msg = object.get("message").toString();
				kakaoReturnVO.setBizReturnCode(code);
				kakaoReturnVO.setBizReturnMsg(msg);
				
			}else {
				kakaoReturnVO.setBizReturnMsg("400 : 명령을 실행 오류");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return kakaoReturnVO;
	}
	
	
	/**
	* @Method Name : insertKakaoApiTemplateWithImage
	* @작성일 : 2023. 2. 16.
	* @작성자 :  우영두
	* @Method 설명 : 알림톡 이미지 포함 등록하기
	*/
	@SuppressWarnings("unchecked")
	public Map<String, String> insertKakaoApiTemplateWithImage(KakaoVO kakaoVO, Map<String, MultipartFile> files, int fileKeyParam) throws Exception {
		
		Map<String, String> resultMap = new HashMap<String, String>();
		
		try {
			
			int fileKey = fileKeyParam;
			String storePathString = propertyService.getString("Globals.fileStorePath");
			
			File saveFolder = new File(storePathString);

			if (!saveFolder.exists() || saveFolder.isFile()) {
			    saveFolder.mkdirs();
			}
			
			List<MultipartFile> tmp = new ArrayList<MultipartFile>(files.values());
			ListIterator<MultipartFile> itr = tmp.listIterator(tmp.size());
			
			MultipartFile file;
			String filePath = "";
			File imgFile = null;
			String newName = "";
			String fileExt = "";
			while (itr.hasPrevious()) {
				
				file = itr.previous();
			    
			    String orginFileName = file.getOriginalFilename();

			    //--------------------------------------
			    // 원 파일명이 없는 경우 처리
			    // (첨부가 되지 않은 input file type)
			    //--------------------------------------
			    if ("".equals(orginFileName)) {
			    	continue;
			    }
			    ////------------------------------------

			    int index = orginFileName.lastIndexOf(".");
			    fileExt = orginFileName.substring(index + 1);
			    newName = EgovStringUtil.getTimeStamp() + fileKey;
			    long _size = file.getSize();

			    //이미지 파일 처리라서 확장자까지 모두 붙여서 파일 생성 함
			    if (!"".equals(orginFileName)) {
					filePath = saveFolder + File.separator + newName + "." + fileExt;
					file.transferTo(new File(filePath));
					
					File newFile = new File(filePath);
				    InputStream inputStream = new FileInputStream(newFile);
			        Image img = new ImageIcon(newFile.toString()).getImage(); // 파일 정보 추출
			        
				    int orgWidth = img.getWidth(null);
				    int orgHeight = img.getHeight(null);
				    
				    long bytes = file.getSize();
			        long kilobyte = bytes / 1024;
			        long megabyte = kilobyte / 1024;
				    
				   
				    /*
				     * 	
						! 이미지
						파일규격 : JPG, JPEG, PNG 만 가능/ 용량 최대 500KB
						권장 사이즈 : 800px X 400px(가로 500px 미만, 가로:세로 비율이 2:1 미만 또는 3:4 초과 시 업로드 불가)
						
				     *
				     * */
				    //일반 이미지 최대 크기는 500KB를 넘을 수 없다. 실제 498KB여도 500이 넘었다고 등록이 안됨. ㅋ
			    	if(kilobyte > 497) {
				    	
				    	resultMap.put("code", "405");
			    		resultMap.put("msg", "파일 최대 용량은 초과하였습니다. 이미지 최대 용량은 500KB를 초과할 수 없습니다.");
			    		
			    		return resultMap;
				    	
				    }else if(orgWidth < 500) {//가로 사이즈가 500px 미만이면 안됨
				    	
				    	resultMap.put("code", "405");
			    		resultMap.put("msg", "일반 이미지의 최소 가로 사이즈는 500px 이상이어야 합니다.");
			    		
			    		return resultMap;
				    	
				    }
			    	
			    	
			    	//일반 이미지 권장사이즈 초과시 리사이즈 처리 후 저장
					//이미지를 강제로 800 / 400 으로 리사이즈 처리하면 이미지가 깨지는 부분이 있어서 처리 안하고 Fail 메세지를 보여주기로 함.
			    	//이미지 규격이 안맞으면 비즈 뿌리오 api에서 실패 메세지를 전달해줌.
			    	/*int MAX_WIDTH = 800;
					int MAX_HEIGHT = 400;
				    
					if(orgWidth > 800 || orgHeight > 400) {
				    	
				        if (orgWidth > MAX_WIDTH) {
				        	orgHeight = (int) (orgHeight * (MAX_WIDTH / (float) orgWidth));
				        	orgWidth = MAX_WIDTH;
				        }

				        if (orgHeight > MAX_HEIGHT) {
				        	orgWidth = (int) (orgWidth * (MAX_HEIGHT / (float) orgHeight));
				        	orgHeight = MAX_HEIGHT;
				        }
				        
				        //이미지 리사이징 요청
				        EgovFileMngUtil fileMngUtil = new EgovFileMngUtil();
				        BufferedImage resizedImage = fileMngUtil.resize(inputStream ,orgWidth , orgHeight );
				        
				        //리사이징된 파일 덮어쓰기
				        ImageIO.write(resizedImage, "jpg", new File(filePath));
				        
				    }*/
				    
					imgFile = new File(filePath);
					
			    }
			    
			}
			
			if(imgFile.exists()) {//파일이 존재하면 카카오로 전송 처리
				
				//첨부파일 등록 API 전송 요청
				
				String apiUrl = "/v3/kakao/template/create_with_image";
				String sendUrl = mjonBizUrl+ apiUrl;
				
				String fullFileName = newName + "." + fileExt;
				
				JSONObject jsonObject = new JSONObject(); 
				//버튼 추가를 위한 배열 변수 선언
				JSONArray btnJsonArr = new JSONArray();
				JSONObject btnJsonObj = new JSONObject();
				
				jsonObject.put("bizId", mjonBizId);
				jsonObject.put("apiKey", mjonBizKakaoApiKey);
				jsonObject.put("senderKey", kakaoVO.getSenderKey());
				jsonObject.put("templateName", kakaoVO.getTemplateName());
				jsonObject.put("templateMessageType", kakaoVO.getTemplateMessageType());
				jsonObject.put("templateEmphasizeType", kakaoVO.getTemplateEmphasizeType());
				jsonObject.put("templateContent", kakaoVO.getTemplateContent());
				jsonObject.put("categoryCode", kakaoVO.getCategoryCode());
				
				if(kakaoVO.getTemplateMessageType().equals("EX")) {
					jsonObject.put("templateExtra", kakaoVO.getTemplateExtra() );
				}else if(kakaoVO.getTemplateMessageType().equals("AD")) {
					jsonObject.put("templateAd", kakaoVO.getTamplateAd());

					//메세지 유형 채널추가형인 경우 채널추가 버튼 생성해주기
					btnJsonObj.put("name", "채널추가");
					btnJsonObj.put("linkType", "AC");
					btnJsonArr.add(btnJsonObj);
					
				}
				
				if(kakaoVO.getTemplateEmphasizeType().equals("TEXT")){
					jsonObject.put("templateTitle", kakaoVO.getTemplateTitle());
					jsonObject.put("templateSubtitle", kakaoVO.getTemplateSubtitle());
				}else if(kakaoVO.getTemplateEmphasizeType().equals("IMAGE")){
					jsonObject.put("templateImageUrl", kakaoVO.getTemplateImageUrl());
					jsonObject.put("templateImageName", kakaoVO.getTemplateImageName());
				}else if(kakaoVO.getTemplateEmphasizeType().equals("ITEM_LIST")){
					
				}

				
				List<KakaoButtonVO> buttonVOList = new ArrayList<KakaoButtonVO>();
				
				buttonVOList = kakaoVO.getButtonVOList();
				
				for(KakaoButtonVO buttonInfo : buttonVOList) {
					
					JSONObject btnTmpObj = new JSONObject();
					
					String linkType = buttonInfo.getLinkType();
					String name = buttonInfo.getName();
					String linkAnd = "";
					String linkIos = "";
					String linkMo = "";
					String linkPc = "";
					
					if(linkType.equals("WL")) {
						
						linkMo = buttonInfo.getLinkMo();
						linkPc = buttonInfo.getLinkPc();
						
						btnTmpObj.put("linkMo", linkMo);
						btnTmpObj.put("linkPc", linkPc);
						
					}else if(linkType.equals("AL")) {
						
						linkAnd = buttonInfo.getLinkAnd();
						linkIos = buttonInfo.getLinkIos();
						btnTmpObj.put("linkAnd", linkAnd);
						btnTmpObj.put("linkIos", linkIos);
						
					}
					
					btnTmpObj.put("name", name);
					btnTmpObj.put("linkType", linkType);
					btnJsonArr.add(btnTmpObj);
					
				}
				
				for(int i=0; i<btnJsonArr.size(); i++) {
					
					JSONObject tmpInfo = new JSONObject(); 
					
					tmpInfo = (JSONObject) btnJsonArr.get(i);
					
				}
				
				//버튼 정보가 있으면 추가
				if(btnJsonArr.size() > 0) {
					jsonObject.put("buttons", btnJsonArr);
				}
				
				CloseableHttpClient httpClient = HttpClients.createDefault();
				HttpPost httpPost = new HttpPost(sendUrl);
				HttpEntity httpEntity = MultipartEntityBuilder.create()
						.addTextBody("bizId", mjonBizId)
						.addTextBody("apiKey", mjonBizKakaoApiKey)
						.addTextBody("senderKey", kakaoVO.getSenderKey())
						.addTextBody("templateName", kakaoVO.getTemplateName())
						.addTextBody("templateMessageType", kakaoVO.getTemplateMessageType())
						.addTextBody("templateEmphasizeType", kakaoVO.getTemplateEmphasizeType())
						.addTextBody("templateContent", kakaoVO.getTemplateContent())
						.addTextBody("categoryCode", kakaoVO.getCategoryCode())
						.addTextBody("templateExtra", kakaoVO.getTemplateExtra())
						.addTextBody("templateAd", kakaoVO.getTamplateAd())
						.addTextBody("buttons", btnJsonArr.toString())
						.addTextBody("templateTitle", kakaoVO.getTemplateTitle())
						.addTextBody("templateSubtitle", kakaoVO.getTemplateSubtitle())
						.addTextBody("templateImageUrl", kakaoVO.getTemplateImageUrl())
						.addTextBody("templateImageName", kakaoVO.getTemplateImageName())
						.addBinaryBody("image", new File(filePath),ContentType.MULTIPART_FORM_DATA,fullFileName)
						.build();
				
				httpPost.setEntity(httpEntity);

		        CloseableHttpResponse response = httpClient.execute(httpPost);

				String result = "";
				
				String statusCode = Integer.toString(response.getStatusLine().getStatusCode());
				
				if(statusCode.equals("200")) {
					result = EntityUtils.toString(response.getEntity()); 
					
					result = new String(result.getBytes("iso-8859-1"));//한글 깨짐 현상이 있어서 변환 해줌.
					JSONParser parser = new JSONParser();
					Object obj = parser.parse(result);
					JSONObject object = (JSONObject) obj;
					
					String code = object.get("code").toString();
					String msg = object.get("message").toString();
					
					resultMap.put("code", code);
					resultMap.put("msg", msg);
					
				}else {
					
					result = EntityUtils.toString(response.getEntity()); 
					result = new String(result.getBytes("iso-8859-1"));//한글 깨짐 현상이 있어서 변환 해줌.
					JSONParser parser = new JSONParser();
					Object obj = parser.parse(result);
					JSONObject object = (JSONObject) obj;
					
					String code = object.get("status").toString();
					String msg = object.get("error").toString();
					
					resultMap.put("code", code);
					resultMap.put("msg", msg);
					
				}
		        
		        httpClient.close();
				
			}
			
		}catch (Exception e) {
			System.out.println("insertKakaoApiTemplateWithImage API Error !!! "+e);
			resultMap.put("code", "error");
			resultMap.put("msg", "Exception 오류가 발생하였습니다.");
			return resultMap;
		}
		return resultMap;
	}
	
}
