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

import com.madeu.constants.Constants;
import com.madeu.dao.mobile.mobilejoin.MobileJoinSqlMapDAO;
import com.madeu.dao.mobile.mobilemembership.MobileMembershipSqlMapDAO;
import com.madeu.service.mobile.mobilejoin.MobileJoinService;
import com.madeu.util.SecurityUtil;
import com.madeu.util.ValidationCheckUtil;
import lombok.extern.slf4j.Slf4j;
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 java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Slf4j
@Service("MobileJoinService")
public class MobileJoinServiceImpl implements MobileJoinService {

	@Autowired
	private MobileJoinSqlMapDAO mobileJoinSqlMapDAO;

	@Autowired
	private MobileMembershipSqlMapDAO mobileMembershipSqlMapDAO;

	/**
	 * 로그인 아이디 중복체크 (아이디 중복확인)
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> checkMembershipId(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("JoinServiceImpl checkMembershipId START");

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

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

		try{
			boolean check  = true;
			String membershipAccount = String.valueOf(paramMap.get("membershipAccount"));

			if(true != ValidationCheckUtil.emptyCheck(membershipAccount)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","로그인 아이디 정보가 없습니다.");
			}else if(membershipAccount.length()<4){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","로그인 아이디는 최소 4자 이상 입력해야합니다.");
			}else{
				if(true != ValidationCheckUtil.lengthCheck(membershipAccount,255)){
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc","로그인 아이디 정보는 255자를 넘을 수 없습니다.");
				}
			}

			if(check){
				List<Map<String, Object>> listMap = mobileJoinSqlMapDAO.checkMembershipId(paramMap);
				int listMapSize = listMap.size();
				log.debug("listMapSize    : "+listMapSize);
				if(listMapSize>=1) {
					map.put("msgCode", Constants.OK);
					map.put("success", "false");
					map.put("rows", listMap);
				}else {
					map.put("msgCode", Constants.OK);
					map.put("success","true");
				}
			}else{
				map.put("msgCode", Constants.FAIL);
				map.put("success","false");
			}
		}
		catch(Exception e){
			throw new Exception(e.getMessage());
		}
		log.debug("WebJoinServiceImpl checkMembershipId END");
		return map;
	}

	/**
	 * 고객 가입
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> insertUser(
			HashMap<String, Object> paramMap) throws Exception{

		log.debug("WebJoinServiceImpl insertUser START");

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

		log.debug("phoneNumber         : " + paramMap.get("phoneNumber"));
		log.debug("marketingAgreement  : " + paramMap.get("marketingAgreement"));
		log.debug("membershipAccount   : " + paramMap.get("membershipAccount"));
		log.debug("membershipPassword  : " + paramMap.get("membershipPassword"));
		log.debug("passwordCheck       : " + paramMap.get("passwordCheck"));
		log.debug("userName            : " + paramMap.get("userName"));
		log.debug("loginType       	   : " + paramMap.get("loginType"));
		log.debug("modId               : " + "mobile");
		log.debug("regId               : " + "mobile");

		try{
			boolean check  = true;
			String tId = String.valueOf(System.currentTimeMillis());

			String phoneNumber = String.valueOf(paramMap.get("phoneNumber"));
			String marketingAgreement = String.valueOf(paramMap.get("marketingAgreement"));
			String membershipAccount = String.valueOf(paramMap.get("membershipAccount"));
			String membershipPassword = String.valueOf(paramMap.get("membershipPassword"));
			String passwordCheck = String.valueOf(paramMap.get("passwordCheck"));
			String userName = String.valueOf(paramMap.get("userName"));
			String loginType = String.valueOf(paramMap.get("loginType"));

			if(true != ValidationCheckUtil.emptyCheck(membershipAccount)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","로그인 아이디 정보가 없습니다.");
			}else if(membershipAccount.length()<4){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","로그인 아이디는 최소 4자 이상 입력해야합니다.");
			}else{
				if(true != ValidationCheckUtil.lengthCheck(membershipAccount,255)){
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc","로그인 아이디 정보는 255자를 넘을 수 없습니다.");
				}
			}

			if(("MU").equals(loginType)){
				if(true != ValidationCheckUtil.emptyCheck(membershipPassword)){
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc","비밀번호 정보가 없습니다.");
				}else{
					if(true != ValidationCheckUtil.passwordCheck(membershipPassword)) {
						check = false;
						map.put("msgCode", Constants.FAIL);
						map.put("msgDesc","비밀번호는 숫자,영문,특수문자 조합 최소 8자리 최대 20자리로 입력해야합니다.");
					}
					else if(true != ValidationCheckUtil.lengthCheck(membershipPassword,20)){
						check = false;
						map.put("msgCode", Constants.FAIL);
						map.put("msgDesc","비밀번호 정보는 20자를 넘을 수 없습니다.");
					}
					else if(!passwordCheck.equals(membershipPassword)){
						check = false;
						map.put("msgCode", Constants.FAIL);
						map.put("msgDesc","비밀번호 정보가 일치하지 않습니다.");
					}
				}
			}

			if(true != ValidationCheckUtil.emptyCheck(marketingAgreement)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","마케팅 수신동의 정보가 없습니다.");
			}

			if(true != ValidationCheckUtil.emptyCheck(userName)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","성함 정보가 없습니다.");
			}else if(userName.length()<2){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","성함은 최소 2자 이상 입력해야합니다.");
			}

			if (!ValidationCheckUtil.emptyCheck(userName) || !ValidationCheckUtil.nickNameCheck(userName)) {
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","유효하지 않은 이름 형식입니다.");
			}
			// 전화번호 형식 검증
			if (!ValidationCheckUtil.emptyCheck(phoneNumber) || !ValidationCheckUtil.phoneNumberCheck(phoneNumber)) {
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","유효하지 않은 전화번호 형식입니다.");
			}

			if(check == true){
				List<Map<String, Object>> userInfoMap =mobileJoinSqlMapDAO.selectUserInfo(paramMap);
				int userInfoMapSize = userInfoMap.size();
				paramMap.put("regId", "mobile");
				paramMap.put("modId", "mobile");
				if(("MU").equals(loginType)){
					paramMap.put("membershipPassword", SecurityUtil.encryptSHA256((String) paramMap.get("membershipPassword")));
				}
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Calendar c1 = Calendar.getInstance();
				String tDate = sdf.format(c1.getTime());

				log.debug("userInfoMapSize : " + userInfoMapSize);
				if(userInfoMapSize>=1) {
					String appStatus = String.valueOf(userInfoMap.getFirst().get("appStatus"));
					String lastVisitDate = String.valueOf(userInfoMap.getFirst().get("lastVisitDate"));
					String membershipYn = String.valueOf(userInfoMap.getFirst().get("membershipYn"));
					String muUserId = String.valueOf(userInfoMap.getFirst().get("muUserId"));

					if(("C").equals(appStatus)) {
						check = false;
						map.put("msgCode", Constants.FAIL);
						map.put("msgDesc","이미 가입된 회원입니다.");
					}else if(("D").equals(appStatus)||true != ValidationCheckUtil.emptyCheck(appStatus)){
						if(true != ValidationCheckUtil.emptyCheck(lastVisitDate)) {
							//방문 기록 없는 앱 탈퇴회원
							paramMap.put("appIntroType", "C");
						}else{
							paramMap.put("appIntroType", "U");
						}
						mobileJoinSqlMapDAO.updateUserInfo(paramMap);
						map.put("msgCode", Constants.OK);
						map.put("msgDesc", "등록되었습니다.");

						//멤버십테이블에 존재하는지 확인
						// 존재하지 않으면 추가
//						HashMap<String, Object> paramData = new HashMap<String, Object>();
//						if(("N").equals(membershipYn)){
//							paramData.put("modId",paramMap.get("modId"));
//							paramData.put("muUserId",muUserId);
//							mobileMembershipSqlMapDAO.updateMembershipYn(paramData);
//							paramData.clear();
//							//멤버십테이블 추가
//							String muMembershipId = ("M").concat(String.valueOf(System.currentTimeMillis()));
//							paramData.put("muMembershipId",muMembershipId);
//							paramData.put("muUserId",muUserId);
//							paramData.put("regId",paramMap.get("regId"));
//							paramData.put("modId",paramMap.get("modId"));
//							paramData.put("tId",paramMap.get("tId"));
//							mobileMembershipSqlMapDAO.insertMembership(paramData);
//						}

//						HashMap<String, Object> deviceData = new HashMap<String, Object>();
//						String muDeviceId = ("D").concat(String.valueOf(System.currentTimeMillis()));
//						deviceData.put("muDeviceId",muDeviceId);
//						deviceData.put("muUserId",muUserId);
//						deviceData.put("phoneType",paramMap.get("phoneType"));
//						deviceData.put("deviceUuid",paramMap.get("deviceUuid"));
//						deviceData.put("pushKey",paramMap.get("pushKey"));
//						deviceData.put("modelName",paramMap.get("modelName"));
//						deviceData.put("osVersion",paramMap.get("osVersion"));
//						deviceData.put("regId",paramMap.get("regId"));
//						deviceData.put("modId",paramMap.get("modId"));
//						deviceData.put("tId",paramMap.get("tId"));
//						mobileMembershipSqlMapDAO.insertDevice(deviceData);

						map.put("msgCode", Constants.OK);
						map.put("success","true");
					}
				}else{
					String muUserId = ("U").concat(String.valueOf(System.currentTimeMillis()));
					paramMap.put("muUserId", muUserId);
					paramMap.put("appIntroType", "C");
					paramMap.put("tId", tId);
					paramMap.put("tDate", tDate);
					mobileJoinSqlMapDAO.insertUser(paramMap);
					map.put("msgCode", Constants.OK);
					map.put("msgDesc", "등록되었습니다.");
					/*Object getMuUserId = "";
					Object userNumberObject = paramMap.get("userNumber");
					if (userNumberObject instanceof HashMap) {
						HashMap<String, Object> userNumber = (HashMap<String, Object>) userNumberObject;
						getMuUserId = userNumber.get("id");
					}

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

					paramData.put("modId",paramMap.get("modId"));
					paramData.put("muUserId",getMuUserId);
					mobileMembershipSqlMapDAO.updateMembershipYn(paramData);

					//멤버십테이블 추가
					String muMembershipId = ("M").concat(String.valueOf(System.currentTimeMillis()));
					paramData.put("muMembershipId",muMembershipId);
					paramData.put("regId",paramMap.get("regId"));
					paramData.put("modId",paramMap.get("modId"));
					paramData.put("tId",paramMap.get("tId"));
					mobileMembershipSqlMapDAO.insertMembership(paramData);*/

//					HashMap<String, Object> deviceData = new HashMap<String, Object>();
//					String muDeviceId = ("D").concat(String.valueOf(System.currentTimeMillis()));
//					deviceData.put("muDeviceId",muDeviceId);
//					deviceData.put("muUserId",muUserId);
//					deviceData.put("phoneType",paramMap.get("phoneType"));
//					deviceData.put("deviceUuid",paramMap.get("deviceUuid"));
//					deviceData.put("pushKey",paramMap.get("pushKey"));
//					deviceData.put("modelName",paramMap.get("modelName"));
//					deviceData.put("osVersion",paramMap.get("osVersion"));
//					deviceData.put("regId",paramMap.get("regId"));
//					deviceData.put("modId",paramMap.get("modId"));
//					deviceData.put("tId",paramMap.get("tId"));
//					mobileMembershipSqlMapDAO.insertDevice(deviceData);

					map.put("msgCode", Constants.OK);
					map.put("success","true");
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
			throw e;
		}

		log.debug("WebJoinServiceImpl insertUser END");
		return map;
	}
}
