package com.madeu.service.common.autokakao.impl;

import com.madeu.constants.Constants;
import com.madeu.dao.web.webkakao.WebKakaoSqlMapDAO;
import com.madeu.service.common.autokakao.AutoKakaoService;
import com.popbill.api.KakaoService;
import com.popbill.api.PopbillException;
import com.popbill.api.kakao.KakaoButton;
import com.popbill.api.kakao.KakaoReceiver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;

@Slf4j
@Service("AutoKakaoService")
public class AutoKakaoServiceImpl implements AutoKakaoService {
	
    @Value("${popbill.corp-num}")
	String corpNum;

    @Value("${popbill.user-id}")
	String userId;

    @Value("${popbill.sender-nm}")
	String senderName;

    @Value("${popbill.sender-phone-num}")
	String senderPhoneNumber;

    @Autowired
    private WebKakaoSqlMapDAO webKakaoSqlMapDAO;

    @Autowired
    private KakaoService kakaoService;

	/**
	 * 푸시 전송
	 * 
	 * @param insertKakaoMap
	 * @return
	 * @throws Exception
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> send(
			String type, HashMap<String, Object> insertKakaoMap) throws Exception{
		log.debug("KakaoServiceImpl send START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		try{
			// R 등록
			webKakaoSqlMapDAO.insertKakao(insertKakaoMap);
			insertKakaoMap.put("muKakaoId", insertKakaoMap.get("id"));
			insertKakaoMap.put("regId", "SYSTEM");
			insertKakaoMap.put("modId", "SYSTEM");


			// R -> G 변경
			HashMap<String, Object> sendKakaoParamMap = new HashMap<String, Object>();
			sendKakaoParamMap.put("muKakaoId", insertKakaoMap.get("muKakaoId"));
			sendKakaoParamMap.put("oldState", "R");
			sendKakaoParamMap.put("chgState", "G");
			sendKakaoParamMap.put("modId", "SYSTEM");
			sendKakaoParamMap.put("sendDateYn", "N");
			webKakaoSqlMapDAO.updateKakaoState(sendKakaoParamMap);


			// 전송
			KakaoReceiver[] receivers = new KakaoReceiver[1];

			String muKakaoId    = String.valueOf(insertKakaoMap.get("muKakaoId"));
			String receiver     = String.valueOf(insertKakaoMap.get("phoneNumber")).replaceAll("-", "");
			String userName     = String.valueOf(insertKakaoMap.get("userName"));
			String content      = String.valueOf(insertKakaoMap.get("content"));
			String templateCode = String.valueOf(insertKakaoMap.get("templateCode"));

			log.debug("===== kakao INPUT START ====");
			log.debug("muKakaoId   :" + muKakaoId);
			log.debug("sender      :" + senderPhoneNumber);
			log.debug("receiver    :" + receiver);
			log.debug("userName    :" + userName);
			log.debug("content     :" + content);
			log.debug("templateCode:" + templateCode);
			log.debug("==== kakao INPUT END   ====");


			KakaoReceiver msg = new KakaoReceiver();
			msg.setReceiverNum(receiver);    // 수신번호
			msg.setReceiverName(userName);   // 수신자명
			msg.setMessage(content);         // 알림톡 템플릿 내용


			// 같은 템플릿끼리 receivers에 담겨야함
			receivers[0] = msg;
			
			String receiptNum = "미전송";
			
			// 예약전송일시, 형태(yyyyMMddHHmmss)
			String sndDT = "";

			// 전송요청번호
			// 파트너가 전송 건에 대해 관리번호를 구성하여 관리하는 경우 사용.
			// 1~36자리로 구성. 영문, 숫자, 하이픈(-), 언더바(_)를 조합하여 팝빌 회원별로 중복되지 않도록 할당.
			String requestNum = "";

			// 알림톡 버튼정보를 템플릿 신청시 기재한 버튼정보와 동일하게 전송하는 경우 null 처리.
			KakaoButton[] btns = null;

			// 대체문자 전송유형, 공백-미전송, C-알림톡 내용전송, A-대체문자 내용 전송
			String altSendType = "";

			try {
				receiptNum = kakaoService.sendATS(corpNum, templateCode, senderPhoneNumber, altSendType, receivers, sndDT,
						userId, requestNum, btns);

			} catch (PopbillException e) {
				log.debug("오류 코드   :" + e.getCode());
				log.debug("오류 메시지 :" + e.getMessage());
			}


			// G -> Y 변경
			sendKakaoParamMap = new HashMap<String, Object>();
			sendKakaoParamMap.put("muKakaoId", insertKakaoMap.get("muKakaoId"));
			sendKakaoParamMap.put("oldState", "G");
			sendKakaoParamMap.put("chgState", "Y");
			sendKakaoParamMap.put("modId", "SYSTEM");
			sendKakaoParamMap.put("sendDateYn", "Y");
			sendKakaoParamMap.put("receiptNum", receiptNum);

			webKakaoSqlMapDAO.updateKakaoState(sendKakaoParamMap);
			
		}catch(Exception e){
			map.put("msgCode", Constants.FAIL);
			map.put("msgDesc", map.get("msgDesc"));
			throw new Exception(e.getMessage());
		}
		
		log.debug("KakaoServiceImpl send END");
		return map;
	}
}
