<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
	layout:decorator="mob/common/layout/MypageLayoutMob">
<!--
 *******************************************************************************
 * @source  : MypageCustModifyFormMob.html
 * @desc    : 마이페이지 > 회원정보 수정 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2021 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.04.26   jsshin      최초 작성
 *******************************************************************************
 -->
<body>
<th:block layout:fragment="content">
<main class="container my">
	<section class="content my_page_edit">
		<form id="custModiFyForm" name="custModiFyForm" class="form_wrap">
			<div class="inner">
				<div class="tbl_wrap">
					<div class="tbl_tit">
						<h3>회원 정보</h3>
						<button type="button" id="btnNameCertify" class="btn_popup">
							<span>개명 본인인증</span>
						</button>
					</div>
					<div class="tbl">
						<div class="tbl_row">
							<table>
								<colgroup>
									<col width="*">
								</colgroup>
								<tr>
									<th>이름</th>
									<td>
										<div class="form_field">
											<input type="text" id="custNm" name="custNm" class="form_control" readonly="readonly">
										</div>
									</td>
								</tr>
								<tr>
									<th>생년월일</th>
									<td>
										<div class="form_field">
											<input type="text" id="birthYmd" name="birthYmd" class="form_control" readonly="readonly"/>
										</div>
									</td>
								</tr>
							</table>
							<p class="desc_txt">본인인증을 통해 자동으로 수집되는 정보입니다.</p>
						</div>
						<div class="tbl_row">
							<table>
								<colgroup>
									<col width="*">
								</colgroup>
								<tr>
									<th>아이디</th>
									<td>
										<div class="form_field">
											<input type="text" id="custId" name="custId" class="form_control" placeholder="" readonly="readonly"/>
										</div>
									</td>
								</tr>
								<tr>
									<th>비밀번호</th>
									<td>
										<div class="form_field password">
											<button type="button" id="btn_password_pop" class="btn btn_primary" onclick="cfnPasswordModify();">
												<span>비밀번호 변경하기</span>
											</button>
										</div>
									</td>
								</tr>
								<tr>
									<th>이메일</th>
									<td>
										<div class="form_field">
											<input type="text" id="email" name="email" data-valid-type="email" class="form_control"/>
										</div>
									</td>
								</tr>
								<tr>
									<th>휴대폰 인증</th>
									<td>
										<div class="input_wrap certi_wrap">
											<input type="text" id="cellPhnno" name="cellPhnno" class="form_control" readonly="readonly"/>
											<button type="button" id="btnCellCertify" class="btn btn_dark">
												<span>본인인증</span>
											</button>
										</div>
									</td>
								</tr>
							</table>
						</div>
					</div>
				</div>
			</div>
			<div class="inner">
				<div class="tbl_wrap">
					<div class="tbl_tit">
						<h3>마케팅 정보 수신설정</h3>
					</div>
					<div class="tbl tbl_radio">
						<table>
							<colgroup>
								<col width="*">
							</colgroup>
							<tr>
								<th class="sr-only">이름</th>
								<td>
									<div class="form_field">
										<input type="checkbox" id="emailAgreeYn" name="emailAgreeYn" value="Y"/>
										<label for="emailAgreeYn"><span>이메일</span></label>
									</div>
								</td>
							</tr>
							<tr>
								<th class="sr-only">생년월일</th>
								<td>
									<div class="form_field">
										<input type="checkbox" id="smsAgreeYn" name="smsAgreeYn" value="Y"/>
										<label for="smsAgreeYn"><span>SMS</span></label>
									</div>
								</td>
							</tr>
						</table>
						<p class="desc_txt">회원정보, 구매 정보 및 서비스 주요 정책 관련 내용은 수신동의 여부와<br>관계없이 발송됩니다.</p>
					</div>
				</div>
			</div>
			<div class="inner">
				<div class="tbl_wrap">
					<div class="tbl_tit">
						<h3>환불 계좌정보</h3>
					</div>
					<div class="tbl type1">
						<table>
							<colgroup>
								<col width="*">
							</colgroup>
							<tr>
								<th>예금주</th>
								<td>
									<div class="form_field">
										<input type="text" id="accountNm" name="accountNm" class="form_control" placeholder="" readonly="readonly"/>
									</div>
								</td>
							</tr>
							<tr>
								<th>은행명</th>
								<td>
									<div class="form_field">
										<div class="select_custom select_bank"> <!-- 210408_ 수정 : select_bank 클래스 변경  -->
											<div class="combo">
												<div class="select">선택</div>
												<input type="hidden" name="bankCd" value=""/>
											</div>
										</div>
									</div>
								</td>
							</tr>
							<tr>
								<th>계좌번호</th>
								<td>
									<div class="input_wrap certi_wrap">
										<input type="number" pattern="\d*" id="accountNo" name="accountNo" class="form_control" maxlength="20" data-valid-type="numeric"  placeholder="계좌번호를 입력해 주세요"/>
										<button type="button" id="btnAccountCheck" class="btn btn_dark">
											<span>계좌인증</span>
										</button>
									</div>
								</td>
							</tr>
						</table>
					</div>
				</div>
				<div class="btn_group_flex">
					<div class="">
						<button type="button" id="btnConfirm" class="btn btn_dark btn_block">
							<span>확인</span>
						</button>
					</div>
				</div>
			</div>
		</form>
	</section>
</main>
<!-- 210408_ 추가 : 은행 선택 팝업 -->
<div id="refundBankPop" class="popup_box refundBankPop">
	<div class="lap">
		<div class="popup_close">카테고리닫기</div>
		<div class="popup_head sr-only">
			<h2 class="">은행 선택 팝업</h2>
		</div>
		<div class="popup_con">
			<div class="button_list clear">
				<th:block th:if="${bankList}" th:each="oneData, status : ${bankList}">
					<button type="button" th:id="|bankCd_${oneData.cd}|" th:with="cd = ${oneData.cd}">
						<span th:text="${oneData.cdNm}"></span>
						<input type="hidden" name="bankCd" th:value="${cd}"/>
					</button>
				</th:block>
			</div>
		</div>
	</div>
</div>
<!-- //210408_ 추가 : 은행 선택 팝업 -->
<script th:src="@{'/biz/customer.js?v=' + ${#calendars.format(#calendars.createNow(), 'yyyyMMddHHmmss')}}" src="/biz/customer.js"></script>
<script th:inline="javascript">
	/*<![CDATA[*/
	let sEncData = [[${sEncData}]];   //인증 후 해당 페이지로 리다이렉트함
	let authMethod = [[${authMethod}]]; //인증 후 해당 페이지로 리다이렉트함

	let orgCustInfo;
	let accountCheck = false;
	let orgBankCd;
	let orgAccountNo;

	// 고객정보
	var fnGetCustInfo = function () {
		$.get('/mypage/customer/info', fnGetCustInfoCallback);
	}

	// 고객정보 데이터
	var fnGetCustInfoCallback = function (custInfo) {
		orgCustInfo = custInfo; // 원본 데이터저장 수정시 비교 작업
		$('#custModiFyForm input[name=custNm]').val(custInfo.custNm);
		$('#custModiFyForm input[name=birthYmd]').val(custInfo.birthYmd);
		let custId = custInfo.custId;
		if (custInfo.snsType === 'NV') {
			custId = '네이버 간편가입회원'
		}
		if (custInfo.snsType === 'KK') {
			custId = '카카오 간편가입회원'
		}
		if (custInfo.snsType === 'YS') {
			custId = 'YES24 간편가입회원'
		}
		$('#custModiFyForm input[name=custId]').val(custId);
		$('#custModiFyForm input[name=email]').val(custInfo.email);
		$('#custModiFyForm input[name=cellPhnno]').val(custInfo.cellPhnno);
		$('#custModiFyForm input[name=accountNm]').val(custInfo.custNm);

		fnDisplayEmailAgree(custInfo.emailAgreeYn);
		fnDisplaySmsAgree(custInfo.smsAgreeYn);

		// 회원(고객) 계좌 조회
		fnGetCustAccountInfo();

	}

	// 이메일 수신동의
	var fnDisplayEmailAgree = function (emailAgreeYn) {
		const $emailAgreeYn = $('#custModiFyForm input[name=emailAgreeYn]');
		if (emailAgreeYn === 'Y') {
			$emailAgreeYn.prop('checked', true);
		} else {
			$emailAgreeYn.prop('checked', false);
		}

	};

	// SMS 수신동의
	var fnDisplaySmsAgree = function (smsAgreeYn) {
		const $smsAgreeYn = $('#custModiFyForm input[name=smsAgreeYn]');
		if (smsAgreeYn === 'Y') {
			$smsAgreeYn.prop('checked', true);
		} else {
			$smsAgreeYn.prop('checked', false);
		}

	};

	// 고객계좌정보
	var fnGetCustAccountInfo = function () {
		$.get('/mypage/customer/account/info', fnGetCustAccountInfoCallback);
	}

	// 고객계좌 정보 데이터
	var fnGetCustAccountInfoCallback = function (result) {
		orgAccountInfo = {};
		var $accountNm = $('#custModiFyForm input[name=accountNm]');
		if (!gagajf.isNull(result)) {
			orgAccountNo = result.accountNo;
			orgBankCd = result.bankCd;
			//1. 고객명과 환불계좌 예금주가 다른 경우 현재 고객명을 적어주고 계좌번호, 은행코드 초기화 처리
			let $bankCd = '';
			if ($accountNm.val() === result.accountNm) {
				$('#custModiFyForm input[name=accountNo]').val(result.accountNo);
				$bankCd = '#bankCd_'+result.bankCd;

			} else {
				$('#custModiFyForm input[name=accountNo]').val('');
				$bankCd = '#bankCd_';

			}
			$($bankCd).trigger('click'); // 셀렉트 박스 트리거
		} else {
			orgAccountNo = '';
			orgBankCd ='';
		}
	}

	// 나이스 본인인증 후 콜백
	var fnNiceCallBack = function(encData) {
		if (!gagajf.isNull(encData)) {
			let custInfo = {};
			custInfo.encData = encData;
			let jsonData = JSON.stringify(custInfo);
			gagajf.ajaxJsonSubmit('/mypage/customer/auth/update', jsonData, fnUpdateAuthInfoCallback);
		}
	};

	var fnUpdateAuthInfoCallback = function (result) {
		if (result.isSuccess) {
			fnGetCustInfo();
			mcxDialog.alert("본인인증을 통해 정보가 변경 되었습니다.");
			return;
		} else {
			mcxDialog.alert("실패하였습니다.<br/>고객센터에 문의하시 바랍니다.");
			return;
		}
	}

	// 계좌인증
	$('#btnAccountCheck').on('click', function () {
		if (!fnGetAccountValidation()) {
			return;
		}
		let custInfo = {};
		custInfo.accountNm = $('#custModiFyForm input[name=accountNm]').val();
		custInfo.accountNo = $('#custModiFyForm input[name=accountNo]').val();
		custInfo.bankCd = $('#custModiFyForm input[name=bankCd]').val();
		let jsonData = JSON.stringify(custInfo);
		//console.log(jsonData);
		gagajf.ajaxJsonSubmit('/mypage/account/check', jsonData, fnAccountCheckCallback);
	});

	// 계좌인증 콜백
	var fnAccountCheckCallback = function (result) {
		let msg = '계좌인증에 성공했습니다.'
		if (result.isValid) { // 유효하면 true
			accountCheck = true;
		} else {
			accountCheck = false;
			msg = '계좌정보를 다시 확인해주세요.'
		}
		mcxDialog.alertC(msg ,{
			sureBtnText: "확인",
			sureBtnClick: function() {
			}
		});
	};

	// 수정 버튼
	$('#btnConfirm').on('click', function () {
		let custModiFy = $('#custModiFyForm').serializeObject();
		let $bankCd = $('#custModiFyForm input[name=bankCd]');
		let $accountNo = $('#custModiFyForm input[name=accountNo]');

		let marketingModifyYn = 'N';
		let accountModifyYn = 'N';
		let emailModifyYn = 'N';

		if (gagajf.isNull(custModiFy.email)) {
			mcxDialog.alertC('이메일 주소를 입력해주세요.',{
				sureBtnText: "확인",
				sureBtnClick: function() {
					$('#custModiFyForm input[name=email]').focus();
				}
			});
			return;
		}

		if (!fnCheckValidationEmail(custModiFy.email)) {
			mcxDialog.alertC('이메일 형식에 맞게 입력해주세요.',{
				sureBtnText: "확인",
				sureBtnClick: function() {
					$('#custModiFyForm input[name=email]').focus();
				}
			});
			return;
		}

		if (orgCustInfo.email !== custModiFy.email) {
			emailModifyYn = 'Y';
		}

		if (!fnGetAccountValidation()) {
			return;
		}


		// 은행코드가 바꼈는지
		if (orgBankCd !== $bankCd.val()) {
			accountModifyYn = 'Y';
		}

		if (orgAccountNo !== $accountNo.val()) {
			accountModifyYn = 'Y';
		}

		if (accountModifyYn === 'Y') { // 환불계좌정보 변경 됐으면
			if (!gagajf.isNull($bankCd.val()) && !gagajf.isNull($accountNo.val())) {
				if (!accountCheck) {
					mcxDialog.alertC('계좌인증이 필요합니다.',{
						sureBtnText: "확인",
						sureBtnClick: function() {
						}
					});
					return;
				}
			}
		}

		if (gagajf.isNull(custModiFy.smsAgreeYn)) {
			custModiFy.smsAgreeYn = 'N';
		}

		if (gagajf.isNull(custModiFy.emailAgreeYn)) {
			custModiFy.emailAgreeYn = 'N';
		}

		// SMS 수신여부
		if (orgCustInfo.smsAgreeYn !== custModiFy.smsAgreeYn) {
			marketingModifyYn = 'Y';
		}

		// 이메일 수신여부
		if (orgCustInfo.emailAgreeYn !== custModiFy.emailAgreeYn) {
			marketingModifyYn = 'Y';
		}

		custModiFy.bankCd = $bankCd.val();
		custModiFy.emailModifyYn = emailModifyYn ;
		custModiFy.marketingModifyYn = marketingModifyYn;
		custModiFy.accountModifyYn = accountModifyYn;

		let jsonData = JSON.stringify(custModiFy);
		// console.log('jsonData',jsonData);
		gagajf.ajaxJsonSubmit('/mypage/customer/info/save', jsonData, fnSaveCustomerInfoCallback)
	});

	// 수정 콜백
	var fnSaveCustomerInfoCallback = function (result) {
		accountCheck = false;
		if (result.isSuccess) {
			mcxDialog.alert("회원정보가 수정되었습니다.");
			fnGetCustInfo();
			fnGetCustAccountInfo();
			return;
		} else {
			let msg = '실패하였습니다.<br/>고객센터에 문의하시 바랍니다.'
			if (result.resultType === 'INVALID_ACCOUNT') {
				msg = '환불 계좌정보를 다시 확인하시고 계좌인증을 해주세요.'
			}
			mcxDialog.alert(msg);
			return;
		}
	}

	// 은행계좌 유효성체크
	var fnGetAccountValidation = function () {
		let $bankCd = $('#custModiFyForm input[name=bankCd]');
		let $accountNo = $('#custModiFyForm input[name=accountNo]');

		if (gagajf.isNull($bankCd.val()) && !gagajf.isNull($accountNo.val())) {
			mcxDialog.alertC('은행을 선택해주세요.',{
				sureBtnText: "확인",
				sureBtnClick: function() {
					$bankCd.focus();
				}
			});
			return false
		}
		if (!gagajf.isNull($bankCd.val()) && gagajf.isNull($accountNo.val())) {
			mcxDialog.alertC('계좌번호를 입력해주세요.',{
				sureBtnText: "확인",
				sureBtnClick: function() {
					$accountNo.focus();
				}
			});
			return false;
		}
		return true;
	};

		// 나이스 본인인증 후 콜백
	var fnNiceCallBack = function(encData) {
		if (!gagajf.isNull(encData)) {
			let custInfo = {};
			custInfo.encData = encData;
			let jsonData = JSON.stringify(custInfo);
			gagajf.ajaxJsonSubmit('/mypage/customer/auth/update', jsonData, fnUpdateAuthInfoCallback);
		}
	};

	var fnUpdateAuthInfoCallback = function (result) {
		if (result.isSuccess) {
			fnGetCustInfo();
			mcxDialog.alert("본인인증을 통해 정보가 변경 되었습니다.");
			return;
		} else {
			mcxDialog.alert("실패하였습니다.<br/>고객센터에 문의하시 바랍니다.");
			return;
		}
	}

	//개명 본인인증
	$('#btnNameCertify').on('click', function () {
		cfnOpenCellphoneCertify(_PAGE_MYPAGE_CUSTOMER_MODIFY+'?confirmYn=Y');
	});

	$('#btnCellCertify').on('click', function () {
		cfnOpenCellphoneCertify(_PAGE_MYPAGE_CUSTOMER_MODIFY+'?confirmYn=Y');
	});

	$(document).ready(function(){

		if (!gagajf.isNull(sEncData)) {
			fnNiceCallBack(sEncData, authMethod);
		}

		$('#htopTitle').text('내 정보 관리');

		// 회원(고객) 조회
		fnGetCustInfo();

		//버튼 색
		$(document).on('click','.popup_box .button_list button',function(){
			$('.popup_box .button_list button').removeClass('on');
			$(this).addClass('on');
			$('.combo .select').html($(this)[0].innerHTML); // 값변경
		});

		//210408_ 추가 : 은행선택 팝업 스크립트
		$(document).on("click",".select_bank",function(e){
			$('#refundBankPop').show().addClass("active");
			$('#refundBankPop').css({"z-index":"1000"});
			$("body").css({"overflow":"hidden"});
		});

		//210408_ 추가 : 은행선택 팝업 스크립트 닫기
		$('.refundBankPop .popup_close').on("click",function(){
			$('.refundBankPop').hide().removeClass('active');
			$("body").css({"overflow":"visible"});
		});

		$(document).on('click','.popup_box.refundBankPop .button_list button',function(){
			$(this).parents('.popup_box.refundBankPop').hide().removeClass('active');
			$("body").css({"overflow":"visible"});
		})


	})
	/*]]>*/
</script>
</th:block>
</body>
</html>