package com.madeu.batch;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.madeu.api.InBodyApiProvider;
import com.madeu.dao.web.webuser.WebUserSqlMapDAO;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class InsertUserPhysicalInbodyBatchExcute {
	
	@Autowired 
	private WebUserSqlMapDAO webUserSqlMapDAO;
	
	@Autowired 
	private InBodyApiProvider inBodyApiProvider;
	
	@Scheduled(cron = "0 0 2 * * ?") // 매일 02:00
	public void go() {
		log.debug("InsertUserPhysicalInbodyBatchExcute - run 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());
			
			
			// 1. 사용자 정보 조회
			List<Map<String, Object>> userList = webUserSqlMapDAO.selectListUserVisitLastMonthAll(paramMap);
			
			
			// 2. 인바디 정보 등록
			int insertedCount = 0;
			
			for(int i=0; i<userList.size(); i++) {
				
				// 고객 전화번호
				String muUserId  = String.valueOf(userList.get(i).get("muUserId"));
				String usertoken = String.valueOf(userList.get(i).get("phoneNumber"));
				
				// Inbody 날짜 정보 조회
				String inbodyTimeInfo = inBodyApiProvider.getDateTimes(usertoken);
				
				if(null!=inbodyTimeInfo && !("").equals(inbodyTimeInfo)) {
				
					// Inbody 정보 조회
					JSONParser parser = new JSONParser();
					Object inbodyTimeObj = parser.parse( inbodyTimeInfo );
					
					JSONArray inbodyTimeInfoObj = (JSONArray) inbodyTimeObj;
					
					for (int y= 0; y < inbodyTimeInfoObj.size(); y++) {
						String dataTimes = String.valueOf(inbodyTimeInfoObj.get(y));
						log.debug("dataTimes ["+i+"] :" + dataTimes);
						
						if(null!=dataTimes && !("").equals(dataTimes)) {
							String inbodyInfo = inBodyApiProvider.getFullInBodyData(usertoken, dataTimes);
							log.debug("inbodyInfo :" + inbodyInfo);
							
							JSONParser parser3 = new JSONParser();
							Object inbodyObj = parser3.parse( inbodyInfo );
							
							JSONObject inbodyInfoObj = (JSONObject) inbodyObj;
							
							String birthDay     = (String)inbodyInfoObj.get("birthday");
							String userName     = (String)inbodyInfoObj.get("name");
							String mobileNumber = (String)inbodyInfoObj.get("MobileNumber");
							String dateTime     = (String)inbodyInfoObj.get("TestDate/Time");
							String height       = (String)inbodyInfoObj.get("Height");
							String weight       = (String)inbodyInfoObj.get("Weight");
							String bfm          = (String)inbodyInfoObj.get("BFM(BodyFatMass)");
							String bmi          = (String)inbodyInfoObj.get("BMI(BodyMassIndex)");
							String smm          = (String)inbodyInfoObj.get("SMM(SkeletalMuscleMass)");
							String pbf          = (String)inbodyInfoObj.get("PBF(PercentBodyFat)");
		
							log.debug("birthDay          :"+birthDay);
							log.debug("userName          :"+userName);
							log.debug("mobileNumber      :"+mobileNumber);
							log.debug("dateTime          :"+dateTime);
							log.debug("height            :"+height);
							log.debug("weight            :"+weight);
							log.debug("bfm               :"+bfm);
							log.debug("bmi               :"+bmi);
							log.debug("smm               :"+smm);
							log.debug("pbf               :"+pbf);
							
		
							
							HashMap<String, Object> selectParamMap = new HashMap<String, Object>();
							selectParamMap.put("muUserId", muUserId);
							selectParamMap.put("inbodyDateTimes", dataTimes);
							List<Map<String, Object>> userPhysicalInbodyList = webUserSqlMapDAO.selectUserPhysicalInbodyDateTimes(selectParamMap);
							int userPhysicalInbodyListSize = Integer.parseInt(String.valueOf(userPhysicalInbodyList.get(0).get("totalCount")));
							
							if(0 == userPhysicalInbodyListSize) {
								HashMap<String, Object> insertParamMap = new HashMap<String, Object>();
		    					String muUserPhysicalId = ("UP").concat(String.valueOf(System.currentTimeMillis()));
		    					insertParamMap.put("muUserPhysicalId", muUserPhysicalId);
		    					insertParamMap.put("muUserId", muUserId);
		    					insertParamMap.put("height", height);
		    					insertParamMap.put("weight", weight);
		    					insertParamMap.put("muscleMass", smm);    // 골격근량
		    					insertParamMap.put("fatMass", bfm);       // 체지방량
		    					insertParamMap.put("fatPercent", pbf);    // 체지방률
		    					insertParamMap.put("bmi", bmi);           // bmi
		    					//insertParamMap.put("muMemberId", paramMap.get("loginMemberId"));
		    					insertParamMap.put("inbodyDateTimes", dataTimes);
		    					insertParamMap.put("tId", tId);
		    					insertParamMap.put("tDate", tDate);
		    					insertParamMap.put("regId", "BATCH_SYSTEM");
		    					insertParamMap.put("modId", "BATCH_SYSTEM");
		    	                webUserSqlMapDAO.insertPhysical(insertParamMap);
		    	                
		    					insertedCount++;
							}
							
						}
					}
				}
			}
			
			log.debug("InsertUserPhysicalInbodyBatchExcute - " + insertedCount + " record inserted");
			
			log.debug("InsertUserPhysicalInbodyBatchExcute - run end");
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
