package com.madeu.batch;

import com.madeu.dao.web.webpush.WebPushSqlMapDAO;
import com.madeu.push.FCMProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class PushAutoSendBatch {

	@Autowired
	private WebPushSqlMapDAO webPushSqlMapDAO;

//    @Scheduled(fixedDelay = 60000) // 1분마다
	public void go() {

		log.debug("PushAutoSendBatch - run start");

		try {
			// 푸시 전송할 대상자 조회 (group)
			HashMap<String, Object> selectMap = new HashMap<String, Object>();
			selectMap.put("state","R");
			selectMap.put("pushType","A");

			List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();

			HashMap<String, Object>  messageParamMap = new HashMap<String, Object>();
			messageParamMap.put("linkUrl",null);

			List<Map<String, Object>> pushList2 = webPushSqlMapDAO.selectListPushTime2(selectMap);
			int pushList2Size = pushList2.size();

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

					// R -> G
					String muPushId = String.valueOf(pushList2.get(i).get("muPushId"));

					// 상태를 변경함. pushYn : G(진행중)
					HashMap<String, Object> sendPushParamMap = new HashMap<String, Object>();
					sendPushParamMap.put("muPushId", muPushId);
					sendPushParamMap.put("oldState", "R");
					sendPushParamMap.put("chgState", "G");
					sendPushParamMap.put("modId", "BatchSystem");
					sendPushParamMap.put("sendDateYn", "N");
					webPushSqlMapDAO.updatePushState(sendPushParamMap);

					String phoneType = String.valueOf(pushList2.get(i).get("phoneType"));
					String pushKey   = String.valueOf(pushList2.get(i).get("pushKey"));
					String title     = String.valueOf(pushList2.get(i).get("title"));
					String content   = String.valueOf(pushList2.get(i).get("content"));

					HashMap<String, Object>  userParamMap = new HashMap<String, Object>();
					userParamMap.put("pushKey", pushKey);
					userParamMap.put("phoneType", phoneType);

					// pushKey, phoneType 리스트에 담음
//					userList.add(userParamMap);

					// 푸시 발송
					FCMProvider fcmProvider = new FCMProvider();
					fcmProvider.provider(phoneType, pushKey, title, content, messageParamMap);


					// G -> Y
					// 상태를 변경함. pushYn : Y(전송완료)
					sendPushParamMap = new HashMap<String, Object>();
					sendPushParamMap.put("muPushId", muPushId);
					sendPushParamMap.put("oldState", "G");
					sendPushParamMap.put("chgState", "Y");
					sendPushParamMap.put("modId", "BatchSystem");
					sendPushParamMap.put("sendDateYn", "Y");
					webPushSqlMapDAO.updatePushState(sendPushParamMap);
				}
			}

		}catch(Exception e){
			e.printStackTrace();
			log.error("Exception PushAutoSendBatch - run", e);
		}
		log.debug("PushAutoSendBatch - run end");

	}

}
