package com.madeu.service.web.webpush.impl;

import com.google.gson.*;
import com.madeu.constants.Constants;
import com.madeu.dao.web.webappevent.WebAppEventSqlMapDAO;
import com.madeu.dao.web.webauthmenurelation.WebAuthMenuRelationSqlMapDAO;
import com.madeu.dao.web.webdevice.WebDeviceSqlMapDAO;
import com.madeu.dao.web.webpush.WebPushSqlMapDAO;
import com.madeu.dao.web.webmember.WebMemberSqlMapDAO;
import com.madeu.service.web.webpush.WebPushService;
import com.madeu.util.ValidationCheckUtil;
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.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service("WebPushService")
public class WebPushServiceImpl implements WebPushService {

    @Value("${url.homepage}")
	String HOMEPAGE_URL;

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

	@Autowired
	private WebPushSqlMapDAO webPushSqlMapDAO;

	@Autowired
	private WebMemberSqlMapDAO webMemberSqlMapDAO;
	
	@Autowired
	private WebAuthMenuRelationSqlMapDAO webAuthMenuRelationSqlMapDAO;

	@Autowired
	private WebAppEventSqlMapDAO webAppEventSqlMapDAO;
	
	@Autowired
	private WebDeviceSqlMapDAO webDeviceSqlMapDAO;

	/**
	 * 앱 푸시 리스트 조회
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectListPush(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebPushServiceImpl selectListPush START");

		HashMap<String, Object> map = new HashMap<String, Object>();

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("pushSearchKeywordParam  :"+paramMap.get("pushSearchKeywordParam"));
		log.debug("pushSort                :"+paramMap.get("pushSort"));
		log.debug("pushStart               :"+paramMap.get("pushStart"));
		log.debug("pushLimit               :"+paramMap.get("pushLimit"));
		log.debug("pushSort                :"+paramMap.get("pushSort"));
		log.debug("pushDir                 :"+paramMap.get("pushDir"));
		log.debug("pushCurrentPage         :"+paramMap.get("pushCurrentPage"));
		
		log.debug("pushSearchStartDate     :"+paramMap.get("pushSearchStartDate"));
		log.debug("pushSearchEndDate       :"+paramMap.get("pushSearchEndDate"));
		
		List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();

		try{
			boolean check  = true;
			
			if(true == check){
				// 사용자 확인
				List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
				int userListMapSize = userListMap.size();
				
				if(1==userListMapSize){
					paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
				}
			}
			
			if(true == check){
				// 정렬
				if(null==paramMap.get("pushDir")||("").equals(paramMap.get("pushDir"))){

				}
				else{
					String dir = String.valueOf(paramMap.get("pushDir"));
					if(("A").equals(dir)){
						paramMap.put("pushDir", "DESC");
					}
					else if(("B").equals(dir)){
						paramMap.put("pushDir", "ASC");
					}
					else {
						paramMap.put("pushDir", "DESC");
					}
				}

				paramMap.put("useYn", "Y");
				
				List<Map<String, Object>> totalCountListMap = webPushSqlMapDAO.selectTotalPushCount(paramMap);
				int totalCount = Integer.parseInt(String.valueOf(totalCountListMap.get(0).get("totalCount")));
				
				if(0 < totalCount) {
					// 리스트 조회
					listMap = webPushSqlMapDAO.selectListPush(paramMap);
				}
				
				map.put("msgCode", Constants.OK);
				map.put("success","true");
				map.put("totalCount", totalCount);
				map.put("rows",listMap);
			}
		}
		catch(Exception e){
			e.printStackTrace();
			throw e;
		}
		log.debug("WebPushServiceImpl selectListPush END");
		return map;
	}
	
	/**
	 * 앱 푸시 정보 등록
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception 
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> insertPush(
			HashMap<String, Object> paramMap) throws Exception{
		log.debug("WebPushServiceImpl insertPush START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("muAppEventId        :"+paramMap.get("muAppEventId"));
		log.debug("title               :"+paramMap.get("title"));
		log.debug("content             :"+paramMap.get("content"));
		log.debug("userArrData         :"+paramMap.get("userArrData"));

		try{
			boolean check  = true;
			String tId = String.valueOf(System.currentTimeMillis());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Calendar c1 = Calendar.getInstance();
			String tDate = sdf.format(c1.getTime());

			List<Map<String, Object>> templateListMap = null;

			String muAppEventId    = String.valueOf(paramMap.get("muAppEventId"));
			String title           = String.valueOf(paramMap.get("title"));
			String content         = String.valueOf(paramMap.get("content"));
			String userArrData     = String.valueOf(paramMap.get("userArrData"));
			String linkUrl         = "";
			double remainPoint = 0;

			if(true != ValidationCheckUtil.emptyCheck(muAppEventId)){

			}else{
				// 앱 이벤트 조회 후 url 생성
				templateListMap = webAppEventSqlMapDAO.selectAppEvent(paramMap);
				int size = templateListMap.size();
				if(0<size){
					// url 생성 (하드코딩)
					linkUrl = HOMEPAGE_URL.concat("/mobileevent/selectEventIntro.do?muAppEventId=").concat(muAppEventId);

				}else{
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc","앱 푸시 템플릿 정보가 없습니다.");
				}
			}

			if(true != ValidationCheckUtil.emptyCheck(title)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","제목 정보가 없습니다.");
			}

			if(true != ValidationCheckUtil.emptyCheck(content)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","내용 정보가 없습니다.");
			}

			if(true != ValidationCheckUtil.emptyCheck(userArrData)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","발송대상 정보가 없습니다.");
			}

			if(true == check){
				// 사용자 확인
				List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
				int userListMapSize = userListMap.size();
				
				if(1==userListMapSize){
					paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
				}
			}
			
			if(true == check){
				// 권한 조회
				HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
				authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
				authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
				List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);
				int authMenuRelationlistMapSize = authMenuRelationlistMap.size();
				
				if(1==authMenuRelationlistMapSize){
					
					if(("Y").equals(authMenuRelationlistMap.get(0).get("insertUseYn"))) {
						
					}
					else {
						check = false;
						map.put("msgCode", Constants.FAIL);
						map.put("msgDesc", "등록 권한 정보가 없습니다.");
					}
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "권한 정보가 없습니다.");
				}
			}

			if(true == check){
				paramMap.put("tDate", tDate);
				paramMap.put("tId", tId);

				//gson 변경 후 등록
				Gson gsonPaser = new GsonBuilder().setPrettyPrinting().create();
				String data = String.valueOf(paramMap.get("userArrData"));

				//json 변환
				JsonObject itemData = gsonPaser.fromJson(data, JsonObject.class);
				JsonArray itemArr = (JsonArray) itemData.get("itemArr");
				int itemArrSize = itemArr.size();

				String muUserIdList = "";

				// pushKey, phoneType 리스트 조회를 위해 muUserIdList 생성
				for(int i=0; i<itemArrSize; i++) {
					String muUserId = itemArr.get(i).getAsJsonObject().get("muUserId").getAsString();

					muUserIdList = muUserIdList.concat("'").concat(muUserId).concat("',");
				}

				// 맨 마지막 , 제거
				muUserIdList = muUserIdList.substring(0, muUserIdList.length()-1);


				log.debug("muUserIdList : "+muUserIdList);
				paramMap.put("muUserIdList", muUserIdList);

				// device 리스트 조회
				List<Map<String, Object>> deviceListMap = webDeviceSqlMapDAO.selectListDevice(paramMap);
				int deviceListMapSize = deviceListMap.size();

				if(0<deviceListMapSize){
					for(int i=0; i<deviceListMapSize; i++){

						HashMap<String, Object> insertDetailParamMap = new HashMap<String, Object>();
						insertDetailParamMap.put("muPushId", ("P").concat(String.valueOf(System.currentTimeMillis())));
						insertDetailParamMap.put("muAppEventId", muAppEventId);
						insertDetailParamMap.put("title", title);
						insertDetailParamMap.put("content", content);
						insertDetailParamMap.put("pushType", "MKT");
						insertDetailParamMap.put("state", "R");
						insertDetailParamMap.put("linkUrl", linkUrl);
						insertDetailParamMap.put("regId", paramMap.get("regId"));
						insertDetailParamMap.put("modId", paramMap.get("modId"));
						insertDetailParamMap.put("muDeviceId", deviceListMap.get(i).get("muDeviceId"));
						insertDetailParamMap.put("phoneType", deviceListMap.get(i).get("phoneType"));
						insertDetailParamMap.put("deviceUuid", deviceListMap.get(i).get("deviceUuid"));
						insertDetailParamMap.put("pushKey", deviceListMap.get(i).get("pushKey"));
						insertDetailParamMap.put("muUserId", deviceListMap.get(i).get("muUserId"));
						insertDetailParamMap.put("userName", deviceListMap.get(i).get("userName"));
						insertDetailParamMap.put("tId", tId);
						insertDetailParamMap.put("tDate", tDate);

						//등록
						webPushSqlMapDAO.insertPush(insertDetailParamMap);
					}
				}

				map.put("msgCode", Constants.OK);
				map.put("msgDesc", "발송되었습니다.");
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		log.debug("WebPushServiceImpl insertPush END");
		return map;
	}
}
