<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"
	  xmlns:th="http://www.thymeleaf.org"
	  xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
	  layout:decorate="~{/mobile/layout/layout}">
<th:block layout:fragment="layout_css">
	<link rel="stylesheet" href="/css/mobile/loginCallback.css?v1.1">
</th:block>

<th:block layout:fragment="layout_top_script">
<script>

</script>
</th:block>

<th:block layout:fragment="layout_content">
<div class="project_wrap">
		<div class="content_wrap">
			<div class="content_box">
				<img class="center_logo" src="/image/mobile/logo.svg">
	
				<div class="form_wrap">
					<!--input-->
					<div class="input_wrap">
						<p id="commentP"></p>
						<p id="email"></p>
					</div>
				</div>
	
				<div class="button_wrap" id="buttonWrap">
				</div>
			</div>
		</div>
	</div>
</th:block>
<th:block layout:fragment="layout_script">
<script src="https://t1.kakaocdn.net/kakao_js_sdk/2.1.0/kakao.min.js" integrity="sha384-dpu02ieKC6NUeKFoGMOKz6102CLEWi9+5RQjWSV0ikYSFFd8M3Wp2reIcquJOemx" crossorigin="anonymous"></script>
<script type="text/javascript">
$(function(){
	getDeviceInfo();
});

// 참고 : https://kindloveit.tistory.com/107
Kakao.init('5b8e8d554e06d9b6cd5f1fb628ed301a'); // 사용하려는 앱의 JavaScript 키 입력
//Kakao.init('9e31b5d35f4839ee691ec1ae8708ea08');

let kakaoCode = '[[${param.code}]]';
let muUserId = '';
let email = '';
let snsEmail = '';


$.ajax({
    type: "POST",
    url: 'https://kauth.kakao.com/oauth/token',
    data: {
        grant_type : 'authorization_code',
        client_id : '5d423b802dd87624f2bee084740cb97a',
        redirect_uri : 'http://nrm.madeu.co.kr/mobilesnslogin/kakaoLoginCallBackIntro.do',
        // redirect_uri : 'http://localhost:8080/mobilesnslogin/kakaoLoginCallBackIntro.do',
        code : kakaoCode
    },
    contentType: 'application/x-www-form-urlencoded;charset=utf-8',
    dataType: null,
    success: function(response) {
        Kakao.Auth.setAccessToken(response.access_token);

        fn_getUserInfo();
    },
    error: function(jqXHR, error) {

    }
});

function fn_getUserInfo(){

	Kakao.API.request({
		url: '/v2/user/me'
	})
        .then(function(res){
            let snsUserId = res.id;
            let userEmail = res.kakao_account.email;
            snsEmail = res.kakao_account.email;
            
			fn_selectEmailCheck(userEmail);

        })
        .catch(function(err){
        	modalEvent.danger("", ""+err.code);
        });
}

/****************************************************************************
* 아이디 확인
****************************************************************************/
function fn_selectEmailCheck(param){
	let formData = new FormData();
	formData.append("email", param);
	formData.append("loginType", "K");

	$.ajax({
		url: '/mobileuser/selectEmailCheck.do',
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		success: function(data){
			if(data.msgCode=='0'){
				if(0<data.rows.length){
					muUserId = data.rows[0].muUserId;
					fn_snsLogin();
					// if('Y'==data.rows[0].kakaoYn){
					// 	fn_snsLogin();
					// }else{
					// 	$('#commentP').text("이미 가입된 아이디가 있습니다.");
					// 	$('#buttonWrap').append('<button type="button" class="btn" onclick="javascript:fn_insertSnsLogin();">카카오로 연결하기</button>');
					// }
					// $('#email').val(email);
				}else{
					$('#commentP').text("회원을 찾을 수 없습니다. 회원가입을 하시겠습니까?");
					$('#buttonWrap').append('<button type="button" class="btn" onclick="javascript:fn_insertSnsUser(\''+param+'\');">가입하기</button>');		
				}
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("로그인 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		}
	});
}

/*****************************************
* sns 회원가입 이동
******************************************/
function fn_insertSnsUser(param){
	fn_leftFormAction("/mobilejoin/joinIntro.do?snsEmail="+param+"&loginType=K");
}

/*****************************************
* sns 로그인
******************************************/
function fn_snsLogin(){

    // 로그인할 때 한 번 더 호출
    getDeviceInfo();

	let formData = new FormData();
	formData.append("loginType", "K");
	formData.append("loginId", snsEmail);
	formData.append("deviceUuid", deviceUuid1);
	formData.append("phoneType", phoneType1);
	formData.append("modelName", modelName1);
	formData.append("osVersion", osVersion1);
	formData.append("pushKey", pushKey1);
	formData.append("appVersion", appVersion1);
	formData.append("deviceYn", deviceYn);
	
	$.ajax({
		url: '/mobilelogin/snsLogin.do',
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		success: function(data){
			if(data.msgCode=='0'){
				setLoginInfo(snsEmail, "", "K");
				// fn_leftFormAction("/mobilehome/homeIntro.do");
				fn_leftFormAction("/home");
			}else{
				modalEvent.danger("로그인 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("로그인 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		}
	});
}
</script>
</th:block>
</html>