<!DOCTYPE html>
<html lang="ko"
	  xmlns:th="http://www.thymeleaf.org"
	  xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
	  layout:decorator="web/common/layout/MypageLayoutWeb">
<!--
 *******************************************************************************
 * @source  : MypageCustModifyFormWeb.html
 * @desc    : 마이페이지 > 회원정보 수정 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2021 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.03.15   jsshin      최초 작성
 *******************************************************************************
 -->
<body>
<th:block layout:fragment="content">
	<div class="content myManage"> <!-- 페이지특정 클래스 = myManage -->
		<div class="cont_body">
			<!-- CONT-BODY -->
			<div class="lnb">
				<div class="lnb_tit">
					<h2>마이페이지</h2>
				</div>
				<div class="lnb_list">
					<ul id="mypageLnbList"></ul>
				</div>
			</div>
			<div class="cont">
				<div class="sec_head">
					<h3 class="subH1">내 정보 관리</h3>
				</div>
				<form id="custModiFyForm" class="form_wrap" role="form" method="post" action="/mypage/account/check" accept-charset="EUC-KR" onsubmit="document.charset='euc-kr';">
					<div class="sec_body">
						<div class="modify_box">
							<h4 class="subH3">회원정보</h4>
							<button type="button" class="btn btn_default btn_sm" onclick="cfnOpenCellphoneCertify();"><span>개명 본인인증</span></button>
							<div class="tbl type1">
								<table>
									<colgroup>
										<col width="210">
										<col width="*">
									</colgroup>
									<tr>
										<th>이름</th>
										<td id="custNm" name="custNm"></td>
									</tr>
									<tr>
										<th>생년월일</th>
										<td id="birthYmd" name="birthYmd"></td>
									</tr>
								</table>
							</div>
							<div class="txt_info">
								<ul>
									<li>
										본인 인증을 통해 자동으로 수집되는 정보 입니다.
									</li>
								</ul>
							</div>
						</div>
						<div class="modify_box">
							<h4 class="sr-only">회원정보 수정</h4>
							<div class="tbl type1">
								<table>
									<colgroup>
										<col width="210">
										<col width="*">
									</colgroup>
									<tbody>
										<tr>
											<th>
												<span>아이디</span>
											</th>
											<td>
												<div class="form_field">
													<div class="input_wrap">
														<input type="text" id="custId" name="custId" class="form_control" placeholder="" readonly="readonly"/>
													</div>
												</div>
											</td>
										</tr>
										<tr>
											<th>
												<span>비밀번호</span>
											</th>
											<td>
												<button type="button" class="btn btn_primary_line" onclick="cfnPasswordModify();">
													<span>변경하기</span>
												</button>
											</td>
										</tr>
										<tr>
											<th>이메일</th>
											<td>
												<div class="form_field">
													<div class="input_wrap">
														<input type="text" id="email" name="email" data-valid-type="email" class="form_control"/>
													</div>
												</div>
											</td>
										</tr>
										<tr>
											<th>휴대폰 번호</th>
											<td>
												<div class="form_field">
													<div class="input_wrap">
														<input type="text" id="cellPhnno" name="cellPhnno" class="form_control" placeholder="휴대폰 인증을 해주세요" readonly="readonly"/>
													</div>
													<button type="button" class="btn btn_dark" onclick="cfnOpenCellphoneCertify();">
														<span>휴대폰 인증</span>
													</button>
												</div>
											</td>
										</tr>
									</tbody>
								</table>
							</div>
						</div>
						<div class="modify_box">
							<h4 class="subH3">환불계좌 정보</h4>
							<div class="tbl type1">
								<table>
									<colgroup>
										<col width="210">
										<col width="*">
									</colgroup>
									<tbody>
										<tr>
											<th class="ver_top">예금주</th>
											<td>
												<div class="form_field">
													<div class="input_wrap">
														<input type="text" id="accountNm" name="accountNm" class="form_control" placeholder="" readonly="readonly"/>
													</div>
												</div>
												<div class="txt_info">
													<ul>
														<li>
															회원명 본인이 예금주인 통장으로만 환불이 가능합니다.
														</li>
													</ul>
												</div>
											</td>
										</tr>
										<tr>
											<th>
												<span>은행명</span>
											</th>
											<td>
												<div class="form_field">
													<div class="select_custom select_bank">
														<div class="combo">
															<div class="select">선택</div>
															<ul class="list">
																<li id="bankCd_" class="selected">
																	<div>선택</div>
																	<input type="hidden" name="bankCd" value=""/>
																</li>
																<th:block th:if="${bankList}" th:each="oneData, status : ${bankList}">
																<li th:id="|bankCd_${oneData.cd}|" th:with="cd = ${oneData.cd}">
																	<div th:text="${oneData.cdNm}"></div>
																	<input type="hidden" name="bankCd" th:value="${cd}"/>
																</li>
																</th:block>
															</ul>
														</div>
													</div>
												</div>
											</td>
										</tr>
										<tr>
											<th>
												<span>계좌번호</span>
											</th>
											<td>
												<div class="form_field">
													<div class="input_wrap">
														<input type="text" id="accountNo" name="accountNo" class="form_control" maxlength="20" data-valid-type="numeric"  placeholder="계좌번호를 입력해 주세요"/>
													</div>
													<button type="button" id="btnAccountCheck" class="btn btn_dark">
														<span>계좌인증</span>
													</button>
												</div>
											</td>
										</tr>
									</tbody>
								</table>
							</div>
						</div>
						<div class="modify_box">
							<h4 class="subH3">
								마케팅 정보 수신설정
								<span class="tit_info">특가상품, 할인쿠폰, 이벤트 소식 수신 동의</span>
							</h4>
							<div class="tbl type1">
								<table>
									<colgroup>
										<col width="210">
										<col width="*">
									</colgroup>
									<tr>
										<th>수신설정</th>
										<td>
											<div class="form_field">
												<div>
													<input type="checkbox" id="emailAgreeYn" name="emailAgreeYn" value="Y"/><label for="emailAgreeYn"><span>이메일</span></label>
												</div>
												<div>
													<input type="checkbox" id="smsAgreeYn" name="smsAgreeYn" value="Y"/><label for="smsAgreeYn"><span>SMS</span></label>
												</div>
											</div>
										</td>
									</tr>
								</table>
							</div>
							<div class="txt_info">
								<ul>
									<li>
										회원 정보, 구매 정보 및 서비스 주요 정책 관련 내용은 수신 동의 여부와 관계없이 발송됩니다.
									</li>
								</ul>
							</div>
						</div>
						<div class="btn_footer_area">
							<button type="button" id="btnConfirm" class="btn btn_dark btn_md">
								<span>확인</span>
							</button>
						</div>
					</div>
				</form>
			</div>
		</div>
	</div>
<script th:src="@{'/biz/customer.js?v=' + ${#calendars.format(#calendars.createNow(), 'yyyyMMddHHmmss')}}" src="/biz/customer.js"></script>
<script th:inline="javascript">
	/*<![CDATA[*/
	let orgCustInfo;
	let accountCheck = false;
	let orgAccountNo;
	let orgBankCd;


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

	// 고객정보 데이터
	var fnGetCustInfoCallback = function (custInfo) {
		orgCustInfo = custInfo; // 원본 데이터저장 수정시 비교 작업
		$('#custModiFyForm td[name=custNm]').text(custInfo.custNm);
		$('#custModiFyForm td[name=birthYmd]').text(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) {
		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 fnConvertToValue = function(data, cd, isCodeDisplay) {
		if (data.length === 0) {
			return "";
		}
		if (typeof(isCodeDisplay) == 'undefined') {
			isCodeDisplay = false;
		}
		let arrValue = {};
		$.each(data, function(idx, item) {
			arrValue[item.cd] = (isCodeDisplay ? '[' + item.cd + '] ' : '') + item.cdNm;
		});
		return arrValue[cd];
	};

	$(document).ready(function() {
		var return_bank_selecter = new sCombo('.modify_box .select_custom.select_bank');

		// 마이페이지 LNB 설정
		fnSetMypageLnbList(10);

		// 마이페이지 location 설정
		fnSetMypageLocation('내정보 관리','_PAGE_MYPAGE_CUSTOMER','회원정보 수정');

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


	});


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


