package com.madeu.batch;

import com.madeu.dao.crm.crmmemberschedule.CrmMemberScheduleSqlMapDAO;
import com.madeu.dao.web.webreserve.WebReserveSqlMapDAO;
import com.madeu.dao.web.webuser.WebUserSqlMapDAO;
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.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class InsertReserveBatch {

	@Autowired
	private WebUserSqlMapDAO webUserSqlMapDAO;

	@Autowired
	private WebReserveSqlMapDAO webReserveSqlMapDAO;

	@Autowired
	private CrmMemberScheduleSqlMapDAO crmMemberScheduleSqlMapDAO;

//    @Scheduled(fixedDelay = 33000000) // 5분30초마다 실행
	public void go() {
		log.debug("****************** InsertReserveBatch START ******************");

		try{
			HashMap<String, Object> paramMap = new HashMap<String, Object>();
			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());

			paramMap.put("tId", tId);
			paramMap.put("tDate", tDate);


			// 대상자 조회 (PID 있는)
			HashMap<String, Object> selectMap = new HashMap<String, Object>();
			List<Map<String, Object>> listMap = webUserSqlMapDAO.selectListUserPid(selectMap);
			int listMapSize = listMap.size();

			if(0<listMapSize){
				for(int i=0; i<listMapSize; i++){
					log.debug("muUserId     : "+listMap.get(i).get("muUserId"));
					log.debug("crmMemberPid : "+listMap.get(i).get("crmMemberPid"));
					paramMap.put("muUserId", listMap.get(i).get("muUserId"));
					paramMap.put("crmMemberPid", listMap.get(i).get("crmMemberPid"));

					List<Map<String, Object>> reserveListMap = crmMemberScheduleSqlMapDAO.selectListMemberSchedule(paramMap);
					int reserveListMapSize = reserveListMap.size();
					if(0<reserveListMapSize){
						for(int j=0; j<reserveListMapSize; j++){
							paramMap.put("crmMemberSchedulePid", reserveListMap.get(j).get("crmMemberSchedulePid"));
							List<Map<String, Object>> checkListMap = webReserveSqlMapDAO.selectListReserveCheck(paramMap);

							if(0==checkListMap.size()){
								String muReserveId = ("R").concat(String.valueOf(System.currentTimeMillis()));

								paramMap.put("muReserveId", muReserveId);
								webReserveSqlMapDAO.insertReserveBatch(paramMap);
							}
						}
					}
				}
			}
		}catch(Exception e){
			log.debug("Exception InsertReserveBatch - run" + e.getMessage());
		}

		log.debug("****************** InsertReserveBatch  END  ******************");
	}
}
