package com.madeu.service.mobile.mobilelogin.impl;

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

import com.madeu.dao.mobile.mobiledevice.MobileDeviceSqlMapDAO;
import com.madeu.dao.mobile.mobilelogin.MobileLoginSqlMapDAO;
import com.madeu.dao.mobile.mobileuser.MobileUserSqlMapDAO;
import com.madeu.service.mobile.mobilelogin.MobileLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.madeu.constants.Constants;
import com.madeu.util.SecurityUtil;
import com.madeu.util.ValidationCheckUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("MobileLoginService")
public class MobileLoginServiceImpl implements MobileLoginService {
	
	@Autowired
	private MobileLoginSqlMapDAO mobileLoginSqlMapDAO;

	@Autowired
	private MobileUserSqlMapDAO mobileUserSqlMapDAO;
	@Autowired
	private MobileDeviceSqlMapDAO mobileDeviceSqlMapDAO;

	/**
	 * 로그인 
	 * 
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception 
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> userLogin(
			HashMap<String, Object> paramMap,  HashMap<String, Object> visitLogParamMap) throws Exception {
		log.debug("MobileLoginServiceImpl userLogin START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		log.debug("loginId    :"+paramMap.get("loginId"));
		log.debug("password   :"+paramMap.get("password"));

		log.debug("phoneType    :"+paramMap.get("phoneType"));
		log.debug("modelName    :"+paramMap.get("modelName"));
		log.debug("osVersion    :"+paramMap.get("osVersion"));
		log.debug("pushKey      :"+paramMap.get("pushKey"));
		log.debug("appVersion   :"+paramMap.get("appVersion"));
		log.debug("deviceUuid   :"+paramMap.get("deviceUuid"));

		
		try{
			boolean check  = true;
			
			String loginId           = String.valueOf(paramMap.get("loginId"));
			String password          = String.valueOf(paramMap.get("password"));
			String phoneType         = String.valueOf(paramMap.get("phoneType"));
			String modelName         = String.valueOf(paramMap.get("modelName"));
			String osVersion         = String.valueOf(paramMap.get("osVersion"));
			String pushKey           = String.valueOf(paramMap.get("pushKey"));
			String appVersion        = String.valueOf(paramMap.get("appVersion"));
			String deviceUuid        = String.valueOf(paramMap.get("deviceUuid"));

			if(true != ValidationCheckUtil.emptyCheck(loginId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc", "아이디 정보가 없습니다.");
			}
			
			if(true != ValidationCheckUtil.emptyCheck(password)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc", "비밀번호 정보가 없습니다.");
			}
			
			if(true == check){
				paramMap.put("password", SecurityUtil.encryptSHA256((String) paramMap.get("password")));
				List<Map<String, Object>> listMap = mobileLoginSqlMapDAO.userLogin(paramMap);

				int listMapSize = listMap.size();

				if(null==listMap ||0 == listMapSize){
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
				}
				else if(1 < listMapSize){
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "중복된 사용자가 있습니다. 관리자에게 문의하시기 바랍니다.");
				}
				else{
					String muUserId                  = String.valueOf(listMap.get(0).get("muUserId"));
					String name                      = String.valueOf(listMap.get(0).get("name"));
					String appUseYn                  = String.valueOf(listMap.get(0).get("appUseYn"));

					if(("Y").equals(appUseYn)){
						paramMap.put("muUserId", muUserId);
						List<Map<String, Object>> deviceListMap = mobileDeviceSqlMapDAO.selectListDevice(paramMap);
						int deviceListMapSize = deviceListMap.size();

						if(deviceListMapSize==0) {
							String tId 			= String.valueOf(System.currentTimeMillis());
							String muDeviceId 	= ("D").concat(String.valueOf(System.currentTimeMillis()));

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

							//device정보 저장
							deviceMap.put("muDeviceId", muDeviceId);
							deviceMap.put("muUserId", muUserId);
							deviceMap.put("phoneType", phoneType);
							deviceMap.put("appVersion", appVersion);
							deviceMap.put("deviceUuid", deviceUuid);
							deviceMap.put("pushKey", pushKey);
							deviceMap.put("modelName", modelName);
							deviceMap.put("osVersion", osVersion);
							deviceMap.put("useYn", "Y");
							deviceMap.put("status", "Y");
							deviceMap.put("regId", muUserId);
							deviceMap.put("modId", muUserId);
							deviceMap.put("tId", tId);

							mobileDeviceSqlMapDAO.insertDevice(deviceMap);
						}else {
							HashMap<String, Object> deviceMap = new HashMap<String, Object>();

							//device정보 수정
							deviceMap.put("muDeviceId", deviceListMap.get(0).get("muDeviceId"));
							deviceMap.put("muUserId", muUserId);
							deviceMap.put("phoneType", phoneType);
							deviceMap.put("appVersion", appVersion);
							deviceMap.put("deviceUuid", deviceUuid);
							deviceMap.put("pushKey", pushKey);
							deviceMap.put("modelName", modelName);
							deviceMap.put("osVersion", osVersion);
							deviceMap.put("useYn", "Y");
							deviceMap.put("status", "Y");
							deviceMap.put("modId", muUserId);

							mobileDeviceSqlMapDAO.updateDevice(deviceMap);
						}

						map.put("msgCode", Constants.OK);
						map.put("muUserId", muUserId);
						map.put("loginId", loginId);
						map.put("userName", name);
						map.put("deviceUuid", deviceUuid);

						paramMap.put("muUserId", muUserId);
						paramMap.put("modId", muUserId);
						paramMap.put("visitIp", visitLogParamMap.get("visitIp"));
						// 최근 로그인 날짜 저장
						mobileLoginSqlMapDAO.updateLastLoginDate(paramMap);
					}
					else{
						map.put("msgCode", Constants.FAIL);
						map.put("msgDesc","서비스 제한 상태입니다. 관리자에게 문의하시기 바랍니다.");
					}
				}
			}
		}
		catch(Exception e){
			throw new Exception(e.getMessage());
		}
		log.debug("MobileLoginServiceImpl userLogin END");
		return map;
	}

	/**
	 * 로그인 (sns)
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> snsLogin(
			HashMap<String, Object> paramMap,  HashMap<String, Object> visitLogParamMap) throws Exception {
		log.debug("WebLoginServiceImpl snsLogin START");

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

		log.debug("loginId    	:"+paramMap.get("loginId"));
		log.debug("loginType    :"+paramMap.get("loginType"));

		log.debug("phoneType    :"+paramMap.get("phoneType"));
		log.debug("modelName    :"+paramMap.get("modelName"));
		log.debug("osVersion    :"+paramMap.get("osVersion"));
		log.debug("pushKey      :"+paramMap.get("pushKey"));
		log.debug("appVersion   :"+paramMap.get("appVersion"));
		log.debug("deviceUuid   :"+paramMap.get("deviceUuid"));

		log.debug("deviceYn     :"+paramMap.get("deviceYn"));

		try{
			boolean check  = true;
			String loginId         	 = String.valueOf(paramMap.get("loginId"));
			String loginType         = String.valueOf(paramMap.get("loginType"));
			String phoneType         = String.valueOf(paramMap.get("phoneType"));
			String modelName         = String.valueOf(paramMap.get("modelName"));
			String osVersion         = String.valueOf(paramMap.get("osVersion"));
			String pushKey           = String.valueOf(paramMap.get("pushKey"));
			String appVersion        = String.valueOf(paramMap.get("appVersion"));
			String deviceUuid        = String.valueOf(paramMap.get("deviceUuid"));

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

			if(check == true){
				List<Map<String, Object>> listMap = mobileLoginSqlMapDAO.snsLogin(paramMap);

				int listMapSize = listMap.size();

				if(null==listMap ||listMapSize==0){
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
				}else if(listMapSize>1){
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "중복된 사용자가 있습니다. 관리자에게 문의하시기 바랍니다.");
				}else{
					String muUserId          = String.valueOf(listMap.get(0).get("muUserId"));
					String name              = String.valueOf(listMap.get(0).get("name"));
					String appUseYn          = String.valueOf(listMap.get(0).get("appUseYn"));

					if(("Y").equals(appUseYn)) {
						paramMap.put("muUserId", muUserId);
						List<Map<String, Object>> deviceListMap = mobileDeviceSqlMapDAO.selectListDevice(paramMap);
						int deviceListMapSize = deviceListMap.size();

						if(deviceListMapSize==0) {
							String tId 			= String.valueOf(System.currentTimeMillis());
							String muDeviceId 	= ("D").concat(String.valueOf(System.currentTimeMillis()));

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

							//device정보 저장
							deviceMap.put("muDeviceId", muDeviceId);
							deviceMap.put("muUserId", muUserId);
							deviceMap.put("phoneType", phoneType);
							deviceMap.put("appVersion", appVersion);
							deviceMap.put("deviceUuid", deviceUuid);
							deviceMap.put("pushKey", pushKey);
							deviceMap.put("modelName", modelName);
							deviceMap.put("osVersion", osVersion);
							deviceMap.put("useYn", "Y");
							deviceMap.put("status", "Y");
							deviceMap.put("regId", muUserId);
							deviceMap.put("modId", muUserId);
							deviceMap.put("tId", tId);

							mobileDeviceSqlMapDAO.insertDevice(deviceMap);
						}else {
							HashMap<String, Object> deviceMap = new HashMap<String, Object>();

							//device정보 수정
							deviceMap.put("muDeviceId", deviceListMap.get(0).get("muDeviceId"));
							deviceMap.put("muUserId", muUserId);
							deviceMap.put("phoneType", phoneType);
							deviceMap.put("appVersion", appVersion);
							deviceMap.put("deviceUuid", deviceUuid);
							deviceMap.put("pushKey", pushKey);
							deviceMap.put("modelName", modelName);
							deviceMap.put("osVersion", osVersion);
							deviceMap.put("useYn", "Y");
							deviceMap.put("status", "Y");
							deviceMap.put("modId", muUserId);

							mobileDeviceSqlMapDAO.updateDevice(deviceMap);
						}

						map.put("msgCode", Constants.OK);
						map.put("muUserId", muUserId);
						map.put("loginId", loginId);
						map.put("userName", name);
						map.put("deviceUuid", deviceUuid);

						paramMap.put("muUserId", muUserId);
						paramMap.put("modId", muUserId);
						paramMap.put("visitIp", visitLogParamMap.get("visitIp"));
						// 최근 로그인 날짜 저장
						mobileLoginSqlMapDAO.updateLastLoginDate(paramMap);
					}else{
						map.put("msgCode", Constants.FAIL);
						map.put("msgDesc","서비스 제한 상태입니다. 관리자에게 문의하시기 바랍니다.");
					}
				}
			}
		}catch(Exception e){
			throw new Exception(e.getMessage());
		}

		log.debug("WebLoginServiceImpl snsLogin END");
		return map;
	}

	/**
	 * 모바일 앱 탈퇴
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> deleteUser(
			HashMap<String, Object> paramMap) throws Exception{
		log.debug("MobileLoginServiceImpl deleteMember START");

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

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));

		log.debug("menuClass           :"+paramMap.get("menuClass"));

		// ,로 구분
		log.debug("selectId            :"+paramMap.get("selectId"));

		try{
			boolean check  = true;

			if(true == check){
				// 사용자 확인
				List<Map<String, Object>> userListMap = mobileUserSqlMapDAO.checkUser(paramMap);
				int userListMapSize = userListMap.size();

				if(1==userListMapSize){
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
				}
			}

			if(true == check){
					HashMap<String, Object> deleteParamMap = new HashMap<String, Object>();
					deleteParamMap.put("muUserId", paramMap.get("muUserId"));
					deleteParamMap.put("modId", paramMap.get("modId"));
					mobileLoginSqlMapDAO.deleteUser(deleteParamMap);
					mobileLoginSqlMapDAO.deleteDevice(deleteParamMap);

				map.put("msgCode", Constants.OK);
				map.put("msgDesc", "삭제 되었습니다.");
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		log.debug("MobileLoginServiceImpl deleteUser END");
		return map;
	}

	/**
	 * 모바일 앱 탈퇴
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> userLogout(
			HashMap<String, Object> paramMap) throws Exception{
		log.debug("MobileLoginServiceImpl userLogout START");

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

		log.debug("muUserId       :"+paramMap.get("muUserId"));
		log.debug("deviceUuid     :"+paramMap.get("deviceUuid"));

		try{
			boolean check  = true;

			if(true == check){
				// 사용자 확인
				List<Map<String, Object>> userListMap = mobileUserSqlMapDAO.checkUser(paramMap);
				int userListMapSize = userListMap.size();

				if(1==userListMapSize){
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
				}
			}

			if(true == check){
				paramMap.put("status", "N");
				mobileDeviceSqlMapDAO.updateDeviceStatus(paramMap);

				map.put("msgCode", Constants.OK);
				map.put("msgDesc", "로그아웃 되었습니다.");
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		log.debug("MobileLoginServiceImpl userLogout END");
		return map;
	}

}
