
/* ##############################################################
	설  명 : [Modal]예약 건 수납 및 수납내역 조회 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/
//미수납내역 체크박스 선택 데이터
let rowData = [];
//할인적용 데이터
let discountData = [];
//멤버십 적용 데이터
let membershipData = [];
//수납내역 데이터
let paymentData = [];
//방문타입
let firstVisitYn='';
//결제수단 선택버튼 활성화 여부
let payTypeBtnActive = true;
//결제 식별자
let muPaymentId = '';

let reservePaymentInsertModal = {

	callback: null,
	reqParam: null,
	dataList: [],
	paymentNumber: getCurrentTimeString(),
	//결제될 최종 데이타
	resultDataList: [],

	/* 모달 초기화 작업 */
	init: function () {
		muPaymentId='';
		//선택한 결제 항목 데이타
		rowData = [];
		//할인 적용 데이타
		discountData = [];
		//멤버십 적용 데이타
		membershipData = [];
		//수납내역 데이터
		paymentData=[];
		//결제 데이타
		reservePaymentInsertModal.resultDataList = [];
		//미납 내역 전체 데이터
		reservePaymentInsertModal.dataList = [];
		$('#reservePaymentInsertModal').remove();
		payTypeBtnActive = true;
		$('body').append(this.HtmlTemplate);
		// 그리드 이벤트
		this.setEvent();
		fn_paymentBtnActive();
	},

	/* 그리드 이벤트 설정 */
	setEvent: function () {
		// 취소 버튼 클릭
		$('#reservePaymentInsertModal .btnCancle').on("click", function () {
			reservePaymentInsertModal.close();
		});

		//결제하기 버튼 클릭
		$('#reservePaymentInsertModal .btnSave').on("click", function (e) {
			//선택한 수납 데이터 확인
			if (0 === rowData.length) {
				modalEvent.warning("등록", "결제할 내역을 선택하세요.");
				return;
			}else if(1<rowData.length){
				// 합결제 중
				// 미수가 하나라도 있으면
				// 부분결제가 하나라도 있으면
				// 완납할 건이 하나라도 있으면

				let payFlag = "Y";
				let paramData = JSON.parse(JSON.stringify(rowData));
				paramData.forEach( row => {
					let status = row["9"];

					if("미수" == status){
						// 미수가 하나라도 있으면
						payFlag = "N";

						modalEvent.warning("등록", "미수건은 합결제가 불가합니다.\n개별 결제해 주시기 바랍니다.");

						return true;
					}else if("부분결제" == status){
						// 부분결제가 하나라도 있으면
						payFlag = "N";

						modalEvent.warning("등록", "부분결제건은 합결제가 불가합니다.\n개별 결제해 주시기 바랍니다.");

						return true;
					}
				});

				// 완납할 건이 하나라도 있으면
				let payCnt = 0;
				let resultDataList = reservePaymentInsertModal.resultDataList;
				if(0<resultDataList.length){
					for(let i=0; i<resultDataList.length; i++){
						let membershipAmount = resultDataList[i].membershipAmount;
						let totalAmount = resultDataList[i].totalAmount;

						// 멤버십 사용했을 때
						if(0<membershipAmount){
							// 완납 건이 있을 경우
							if(0 == totalAmount){
								payCnt++;

								// 진료명 문구 추가
							}
						}
					}

					if(0 < payCnt && resultDataList.length != payCnt){
						payFlag = "N";

						modalEvent.warning("등록", "완납 가능 건은 부분,합결제가 불가합니다.\n개별 결제해 주시기 바랍니다.");
					}
				}

				if("N" == payFlag){
					// 합결제 중
					// 미수가 하나라도 있으면
					// 부분결제가 하나라도 있으면
					// 완납할 건이 하나라도 있으면
					return;
				}
			}


			//결제 타입 확인.
			/*return = { splitType : 선택된 분할결제 타입
									  (분할결제:splitPayment, 멤버십 사용금액만:split1, 선결제:split2, 미수처리:split3)
		    			 ,paymentType: 결제수단 (카드,현금,계좌이체,qr)
						 }*/
			let paymentType = fn_checkPaymentType();

			//분할결제 아이템(멤버십 사용금액만:split1, 선결제:split2, 미수처리:split3) 선택 안한경우
			if (payTypeBtnActive) {
				//분할 결제 여부
				let isSplitPayment = paymentType.splitType==='splitPayment'
				//분할 결제 금액
				let splitAmount = parseFloat($('#reservePaymentInsertModal #splitAmount').val().replace(/,/g, ''));

				if (isSplitPayment && !splitAmount) {
					modalEvent.warning("오류", '결제금액을 입력하세요');
					return;
				} else if (isSplitPayment && splitAmount) {
					//결제 데이타에 분할 결제 금액 저장
					reservePaymentInsertModal.resultDataList.splitAmount = splitAmount;
				}

				switch (paymentType.paymentType) {
					case '카드':
						fn_payment('card')
						break;
					case '현금':
						let cashReqParam = reservePaymentInsertModal.resultDataList;

						//현금결제 모달
						monetizationModal.popup(function (obj) {
							//분할결제 진행 시
							if(obj.status==='G'){
								firstVisitYn='N';
								//분할결제 금액
								let splitAmount = $('#reservePaymentInsertModal #splitPayment p').eq(1).text()?.replace(/[^\d]/g, '')
								//총 결제한 분할 금액
								splitAmount = (parseInt(splitAmount, 0)||0)+obj.splitAmount;
								//분할 결제 데이터 저장
								fn_setSplitData(splitAmount);
								//분할 결제 데이터 표출 업데이트
								$('#reservePaymentInsertModal #splitPayment').remove();
								$('#reservePaymentInsertModal .amount_detail_list').append(
									`<li id="splitPayment">
										<p>분할결제 금액</p>
										<p>-${splitAmount.toLocaleString()}원</p>
									</li>`)
								//결제중 모달 이동 불가
								fn_nonTouchModal();
							}else{
								//남은 미납항목 체크
								fn_checkRemainPaymentList();
							}
						}, cashReqParam);
						break;
					case '계좌이체':
						let accountReqParam = reservePaymentInsertModal.resultDataList;
						//계좌이체 모달
						accountModal.popup(function (obj) {
							//분할결제 진행 시
							if(obj.status==='G'){
								firstVisitYn='N';
								//분할결제 금액
								let splitAmount = $('#reservePaymentInsertModal #splitPayment p').eq(1).text()?.replace(/[^\d]/g, '')
								//총 결제한 분할 금액
								splitAmount = (parseInt(splitAmount, 0)||0)+obj.splitAmount;
								//분할 결제 데이터 저장
								fn_setSplitData(splitAmount);
								//분할 결제 데이터 표출 업데이트
								$('#reservePaymentInsertModal #splitPayment').remove();
								$('#reservePaymentInsertModal .amount_detail_list').append(
									`<li id="splitPayment">
										<p>분할결제 금액</p>
										<p>-${splitAmount.toLocaleString()}원</p>
									</li>`)
								//결제중 모달 이동 불가
								fn_nonTouchModal();
							}else{
								//남은 미납항목 체크
								fn_checkRemainPaymentList();
							}
						}, accountReqParam);
						break;
					case 'QR결제':
						fn_payment('qr')
						break;
					default:
						modalEvent.warning("오류", '결제수단을 선택하세요');
						break;
				}
			} else {
				switch (paymentType.splitType) {
					//멤버십 사용금액만 결제
					case 'split1':
						let splitReqParam = reservePaymentInsertModal.resultDataList;
						//멤버십 결제 모달
						membershipPartialModal.popup(function (obj) {
							fn_checkRemainPaymentList();
						}, splitReqParam);
						break;
					//선결제 처리
					case 'split2':
						if( reservePaymentInsertModal.resultDataList.reduce((sum, item) => sum + item.nonPayment, 0) > 0 ){
							modalEvent.warning("오류", '미수 상태인 내역은 선결제 처리 할 수 없습니다.');
							return;
						}
						fn_payment('split2');
					break;
					//미수처리
					case 'split3':
						if( reservePaymentInsertModal.resultDataList.reduce((sum, item) => sum + item.nonPayment, 0) > 0 ){
							modalEvent.warning("오류", '이미 미수 처리 내역이 존재합니다.');
							return;
						}else if(1<reservePaymentInsertModal.resultDataList.length){
							modalEvent.warning("오류", '합미수 처리가 불가합니다.\n개별 결제해 주시기 바랍니다.');
							return;
						}
						fn_payment('split3');
						break;
					case 'discountOnly':
						fn_payment('discountOnly');
						break;
				}
			}
		});

		//할인적용 이벤트
		$('#reservePaymentInsertModal .discount_btn').on("click", function () {
			if( 0 === rowData.length ){
				modalEvent.warning("등록", "할인을 적용할 시술을 선택하세요.");
				return;
			}

			let paramData = JSON.parse(JSON.stringify(rowData));
			paramData.forEach( row => {
				let matchedMembership = reservePaymentInsertModal.resultDataList.find(membership => membership.muReserveId === row[0].substring(6));
				if ( matchedMembership ) {
					row["10"] = matchedMembership.amount.toLocaleString();
					row["11"] = matchedMembership.vat.toLocaleString();
					row["12"] = matchedMembership.totalAmount.toLocaleString();
				}
			});
			discountInsertModal.popup(function (obj) {
				discountData = obj;
				fn_setDiscountData(obj);
			}, paramData);
		});

		//할인적용 취소 이벤트
		$('#reservePaymentInsertModal .discount_box button').on("click", function () {
			$('#reservePaymentInsertModal .discount_btn').css('display', 'block');
			$('#reservePaymentInsertModal .discount_box').css('display', 'none');
			$('#reservePaymentInsertModal #payment .payment_right tbody tr').find('td:nth-child(3)').text('-');
			discountData = [];
			if (membershipData.length > 0) {
				fn_setMembershipData(membershipData);
			} else {
				updateRightPane();
				fn_initResultDataList();
			}
		});

		//멤버십 적용 취소 이벤트
		$('#reservePaymentInsertModal .membership_box button').on("click", function () {
			$('#reservePaymentInsertModal .membership_btn').css('display', 'block');
			$('#reservePaymentInsertModal .membership_box').css('display', 'none');
			$('#reservePaymentInsertModal #payment .payment_right tbody tr').find('td:nth-child(4)').text('-');
			membershipData = [];
			if (discountData.length > 0) {
				fn_setDiscountData(discountData);
			} else {
				updateRightPane();
				fn_initResultDataList();
			}
		});
		//멤버십 적용 이벤트
		$('#reservePaymentInsertModal .membership_btn').on("click", function () {
			if(0===rowData.length){
				modalEvent.warning("등록", "멤버십을 적용할 시술을 선택하세요.");
				return;
			}
			let membershipYn = $('#reservePaymentInsertModal .membership_btn').data('membership');
			let paramData = JSON.parse(JSON.stringify(rowData));
			paramData.forEach(row => {
				let matchedDiscount = reservePaymentInsertModal.resultDataList.find(discount => discount.muReserveId === row[0].substring(6));
				if (matchedDiscount) {
					row["10"] = matchedDiscount.amount.toLocaleString();
					row["11"] = matchedDiscount.vat.toLocaleString();
					row["12"] = matchedDiscount.totalAmount.toLocaleString();
				}
			});
			let reqParam = {
				'muUserId': reservePaymentInsertModal.reqParam.muUserId,
				'rowData': paramData,
			};
			if (membershipYn === 'N') {
				modalEvent.warning("조회 오류", '멤버십고객이 아닙니다.');
				return;
			} else {
				paymentMembershipModal.popup(function (obj) {
					membershipData = obj;
					fn_setMembershipData(obj);
				}, reqParam);
			}
		});

		//결제취소 버튼 클릭
		$('#reservePaymentInsertModal .payment_cancel_btn').on("click", function () {
			if($('#reservePaymentInsertModal .tbodyPaymentHistory tr.selected').length===0){
				modalEvent.warning('오류','결제취소 처리할 수납 내역이 선택되지 않았습니다.');
				return;
			}
			//결제취소 팝업
			cancellationModal.popup(function (obj) {
				paymentData=[];
				reservePaymentInsertModal.paymentNumber = getCurrentTimeString();
				reservePaymentInsertModal.historySearch();
			}, paymentData);
		});

		//환불 버튼 클릭
		$('#reservePaymentInsertModal .refund_btn').on("click", function () {
			if($('#reservePaymentInsertModal .tbodyPaymentHistory tr.selected').length===0){
				modalEvent.warning('오류','환불 처리할 수납 내역이 선택되지 않았습니다.');
				return;
			}
			refundModal.popup(function (obj) {
				paymentData=[];
				reservePaymentInsertModal.paymentNumber = getCurrentTimeString();
				reservePaymentInsertModal.historySearch();
			}, paymentData);
		});

		// 취소 재결제 버튼 클릭
		$('#reservePaymentInsertModal .payment_repay_btn').on("click", function () {
			if($('#reservePaymentInsertModal .tbodyPaymentHistory tr.selected').length===0){
				modalEvent.warning('오류','취소 재결제 처리할 수납 내역이 선택되지 않았습니다.');
				return;
			}
			//결제취소 팝업
			cancellationPayModal.popup(function (obj) {
				paymentData=[];
				reservePaymentInsertModal.paymentNumber = getCurrentTimeString();
				reservePaymentInsertModal.historySearch();
			}, paymentData);
		});

		//분할결제버튼 클릭(활성화)
		$('#reservePaymentInsertModal .split_up_btn').on('click', function () {
			$('#reservePaymentInsertModal .splitType input[type="checkbox"]').prop('checked', false);
			payTypeBtnActive = true;
			fn_paymentBtnActive();
			$(this).toggleClass('active').children().toggleClass('active');
			let isActive = $(this).hasClass('active');
			$('#splitAmount').prop('disabled', !isActive).css('background', isActive ? 'white' : '#E9ECF0');
			if (!isActive) {
				$('#splitAmount').val('');
			}
		});

		//결제옵션 체크박스 선택 ( 멤버십, 선결제, 미수 )
		$('#reservePaymentInsertModal .splitType input[type="checkbox"]').on('change', function () {
			let isChecked = $(this).is(':checked');
			let splitTypeId = $(this).attr('id');
			if(splitTypeId==='split2'||splitTypeId==='split3'){
				updateRightPane();
			}
			if(splitTypeId==='split1'){
				let membershipYn = $('#reservePaymentInsertModal .membership_btn').data('membership');
				if('Y'!==membershipYn||0===membershipData.length){
					modalEvent.warning("등록", "결제할 멤버십 정보가 없습니다.");
					$(this).prop('checked', false);
					return;
				}
			}
			if (!isChecked) {
				payTypeBtnActive=true;
				fn_paymentBtnActive();
				$(this).prop('checked', false);
			} else {
				$('#reservePaymentInsertModal .splitType input[type="checkbox"]').prop('checked', false);
				$(this).prop('checked', true);
				// 분할결제 버튼 활성/비활성 토글
				$('#reservePaymentInsertModal .split_up_btn').removeClass('active').find('img').removeClass('active');
				// splitAmount 활성/비활성 처리
				$('#splitAmount').val('').css('background', '#E9ECF0');
				fn_paymentBtnDeactive();
			}
		});
        //분할결제 금액 입력 시
		$('#reservePaymentInsertModal #splitAmount').on('change', function () {
			let totalAmount =  parseInt($('#reservePaymentInsertModal #payment .total_amount p').eq(1).text().replace(/,/g, '').replace('원', ''),10);
			if($('#splitAmount').val()>totalAmount){
				modalEvent.warning("등록", "결제 금액이 초과했습니다.");
				$('#splitAmount').val('')
				return;
			}
			let splitAmount = $('#splitAmount').val().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
			$('#splitAmount').val(splitAmount);
			fn_paymentBtnActive();
		});

		$('#reservePaymentInsertModal #splitAmount').on('input', function () {
			let inputValue = '';
			inputValue = $('#splitAmount').val();
			let numericValue = inputValue.replace(/\D/g, '');
			$('#splitAmount').val(numericValue);
		});

		$('#reservePaymentInsertModal #checkAll').on('change', function () {
			let checkboxes = $('#reservePaymentInsertModal .tbodyPayment input[type="checkbox"]');
			checkboxes.prop('checked', $(this).is(':checked')).trigger('change');
		});

		$('#reservePaymentInsertModal #payment .tbodyPayment').on('change','input[type="checkbox"]',(e)=>{
			fn_checkAll();
			let isChecked = e.target.checked;

			let data = {};
			$(e.target).closest('tr').find('td').each(function () {
				let key = $(this).index();
				data[key] = $(this).text().trim();
				if (key === 0) {
					data[key] = $(this).find('input').attr('id');
				}
				if(key === 3){
					data['muTreatmentId'] = $(this).data('treatment');
					data['muTreatmentProcedureId'] = $(this).data('procedure');
				}
				if(key === 4){
					data['reserveMemberId'] = $(this).data('reservemember');
				}
				if(key === 9){
					data['muPaymentId'] = $(this).data('mupaymentid');
				}
			});

			if (isChecked) {
				if (!rowData.some(item => isEquivalent(item, data))) {
					rowData.push(data); // 배열에 추가
				}
				if(data['muPaymentId']) {
					muPaymentId = data['muPaymentId'];
				}
			} else {
				// 배열에서 해당 데이터 제거
				rowData = rowData.filter(function (item) {
					if(muPaymentId===data['muPaymentId']){
						muPaymentId='';
					}
					return !isEquivalent(item, data);
				});
			}

			fn_splitReset();
			updateRightPane();
		});

		$('#reservePaymentInsertModal .card_btn').on("click", function () {
			let isActive = $('#reservePaymentInsertModal .card_btn').hasClass('active');
			fn_paymentBtnActive();
			if (payTypeBtnActive) {
				$('#reservePaymentInsertModal .card_btn').toggleClass('active', !isActive).css('background', isActive ? 'white' : '#3985EA');
			}
		});

		$('#reservePaymentInsertModal .monetization_btn').on("click", function () {
			let isActive = $('#reservePaymentInsertModal .monetization_btn').hasClass('active');
			fn_paymentBtnActive();
			if (payTypeBtnActive) {
				$('#reservePaymentInsertModal .monetization_btn').toggleClass('active', !isActive).css('background', isActive ? 'white' : 'orange');
			}
		});

		$('#reservePaymentInsertModal .account_btn').on("click", function () {
			let isActive = $('#reservePaymentInsertModal .account_btn').hasClass('active');
			fn_paymentBtnActive();
			if (payTypeBtnActive) {
				$('#reservePaymentInsertModal .account_btn').toggleClass('active', !isActive).css('background', isActive ? 'white' : 'red');
			}
		});

		$('#reservePaymentInsertModal .qr_btn').on("click", function () {
			let isActive = $('#reservePaymentInsertModal .qr_btn').hasClass('active');
			fn_paymentBtnActive();
			if (payTypeBtnActive) {
				$('#reservePaymentInsertModal .qr_btn').toggleClass('active', !isActive).css('background', isActive ? 'white' : 'grey');
			}
		});

		$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
			let target = $(e.target).attr("href");
			if ('#payment' === target) {
				reservePaymentInsertModal.search();
			} else if ('#payment_detail' === target) {
				reservePaymentInsertModal.historySearch();
			}
		});
		$('#reservePaymentInsertModal .tbodyPaymentHistory').on("click",'tr', function () {
			$(this).toggleClass('selected');
			let clickId = $(this).attr('id');
			$('#reservePaymentInsertModal .tbodyPaymentHistory tr').css('background','white');
			if($(this).hasClass('selected')){
				$(this).css('background','rgb(57 133 234 / 15%)')
				reservePaymentInsertModal.historySearch(clickId);
			}else{
				reservePaymentInsertModal.historySearch();
			}
		})
	},

	// 상태 표시
	setReserveStatus: function (param) {
		const statuses = {
			'T': '예약',
			'TN': '예약취소',
			'R': '접수',
			'RN': '접수취소',
			'G': '진료중',
			'Y': '진료완료'
		};
		return statuses[param] || '';
	},
	setReservepayTypeBtnActive: function (param) {
		const statuses = {
			'N': '미납',
			'CN': '재결제(취소)',
			'Y': '결제완료',
			'C': '결제취소',
			'P': '부분결제',
			'NP': '미수',
			'NY': '미수결제',
			'PY': '부분결제(완납)',
			'R': '환불',
			'PP': '선결제'
		};
		return statuses[param] || '';
	},
	// 미 수납건 조회
	search: function (state) {
		init();
		let { reserveDate, muUserId } = reservePaymentInsertModal.reqParam;

		if (!fn_emptyCheck(muUserId)) {
			modalEvent.warning("수정", "고객 정보가 없습니다.");
			return;
		}

		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("muUserId", muUserId);
		formData.append("reserveDate", reserveDate);

		$.ajax({
			url: encodeURI('/webreserve/selectListReserveUserNoPayment.do'),
			data: formData,
			dataType: "json",
			processData: false,
			contentType: false,
			type: 'POST',
			async: true,
			success: function (data) {
				if ('0' == data.msgCode) {
					// 예약자 정보
					let user = data.userRows[0];
					$('#reservePaymentInsertModal .modal-body p.user_name .modalUserName').text(user.userName);
					$('#reservePaymentInsertModal .modal-body p.user_name .modalBirthday').text(user.birthday);
					$('#reservePaymentInsertModal .modal-body p.user_name .modalNationality').text(user.nationalityName);
					$('#reservePaymentInsertModal .modal-body p.user_name .modalPhoneNumber').text(fn_setFormatPhone(user.phoneNumber));
					$('#reservePaymentInsertModal .membership_btn').data('membership', user.membershipYn === '미가입' ? 'N' : 'Y');

					// 미수납건 조회
					let listHTML = '';

					if (data.rows.length > 0) {
						if(0===data.rows.reduce((sum, item) => sum + item.nonPayment, 0)){
							listHTML += `
							<tr>
								<td colspan="10" style="text-align: center;">조회 결과가 없습니다.</td>
							</tr>`;
						}
						for (let i = 0; i < data.rows.length; i++) {
							let row = data.rows[i];
							let { muReserveId
								, reserveDate
								, reserveTime
								, status
								, status2
								, muTreatmentId
								, treatmentName
								, muTreatmentProcedureId
								, reserveMemberId
								, treatmentProcedureName
								, reserveMemberName
								, price
								, vat
								, totalAmount
								, nonPayment
								, muPaymentId:rowPaymentId } = row;

							if (nonPayment === 0) continue;

							// if(rowPaymentId){
							// 	muPaymentId = rowPaymentId;
							// }
							reservePaymentInsertModal.dataList.push(row);

							listHTML += `<tr>
											<td>
												<label for="check_${muReserveId}" class="chk_box">
													<input type="checkbox" id="check_${muReserveId}" name="check_reserve" value="${muReserveId}">
													<span class="on"></span>
												</label>
											</td>
											<td>${reserveDate}, ${reserveTime}</td>
											<td class="${status === 'Y' ? '' : 'bcolor'}">${reservePaymentInsertModal.setReserveStatus(status)}</td>
											<td data-treatment="${muTreatmentId}" data-procedure="${muTreatmentProcedureId}"><p>${treatmentName} - ${treatmentProcedureName}</p></td>
											<td data-reservemember="${reserveMemberId}">${reserveMemberName}</td>
											<td class="number">${fn_numberFormat(price)}</td>
											<td class="number">${fn_numberFormat(vat)}</td>
											<td class="number">${fn_numberFormat(totalAmount)}</td>
											<td class="number">${fn_numberFormat(nonPayment ?? '-')}</td>
											<td class="${['P','NP'].includes(status2) ? 'color_red' : ''}"style="font-weight: 700;" data-mupaymentid=${rowPaymentId}>${reservePaymentInsertModal.setReservepayTypeBtnActive(status2)}</td>
										</tr>`;
						}

					} else {
						listHTML += `
							<tr>
								<td colspan="10" style="text-align: center;">조회 결과가 없습니다.</td>
							</tr>`;
					}
					$('#reservePaymentInsertModal #payment .table_box table tbody.tbodyPayment').html(listHTML);
				} else {
					modalEvent.danger("조회 오류", data.msgDesc);
				}
			},
			error: function (xhr, status, error) {
				modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend: function () { },
			complete: function () { }
		});
	},

	// 수납내역 조회
	historySearch: function (paymentNumber) {
		let { muUserId, reserveDate } = reservePaymentInsertModal.reqParam;

		if (!fn_emptyCheck(muUserId)) {
			modalEvent.warning("수정", "고객 정보가 없습니다.");
			return;
		}

		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("muUserId", muUserId);
		if(paymentNumber)
			formData.append("paymentNumber", paymentNumber);
		formData.append("reserveDate", reserveDate);

		$.ajax({
			url: encodeURI('/webpayment/selectListPaymentUser.do'),
			data: formData,
			dataType: "json",
			processData: false,
			contentType: false,
			type: 'POST',
			async: true,
			success: function (data) {
				if ('0' == data.msgCode) {
					// 수납 이력 조회
					let listHTML = '';
					let listHTML2 = '';
					let listHTML3 = '';
					let etc = '';
					let refundEtc = '';

					if (data.rows.length > 0) {
						let procedureData = data.procedureList.map(row => ({
							muReserveId: row['muReserveId'],
							treatmentProcedureName: row['treatmentProcedureName'],
							treatmentName: row['treatmentName'],
							muTreatmentId: row['muTreatmentId'],
							muTreatmentProcedureId: row['muTreatmentProcedureId'],
							reserveMemberId: row['reserveMemberId'],
							totalAmount: row['totalAmount'],
							amount: row['amount'],
							vat: row['vat'],
							paymentNumber: row['paymentNumber']
						}));
						let paymentDetailData = data.paymentDetail.map(row => ({
							amount: row['amount'],
							vat: row['vat'],
							totalAmount: row['totalAmount'],
							paymentCategoryItemId: row['paymentCategoryItemId'],
							paymentCategoryItemName: row['paymentCategoryItemNm'],
							paymentCardInfo: row['paymentCardInfo'],
							cardInstallments: row['cardInstallments'],
							cardInstallmentsCode: row['cardInstallmentsCode'],
							paymentNumber: row['paymentNumber'],
							paymentApprovalId: row['paymentApprovalId'],
							paymentApprovalDate: row['paymentApprovalDate'],
							muPaymentId: row['muPaymentId'],
							status: row['status'],
							membershipPrice: row['membershipPrice'],
							cardInfo: row['cardInfo']
						}));
						let paymentAmount = data.rows.reduce((sum, item) => sum + item.paymentAmount, 0);
						let userName = $('#reservePaymentInsertModal .modalUserName').text();
						let procedureName = data.procedureList[0].treatmentName+'-'+data.procedureList[0].treatmentProcedureName+(data.procedureList.length-1>0?(' 외 '+(data.procedureList.length-1)+'건'):'');
						paymentData.reserveDate=reserveDate;
						paymentData.paymentAmount=paymentAmount;
						paymentData.userName=userName;
						paymentData.procedureName=procedureName;
						paymentData.procedureData=procedureData;
						paymentData.paymentDetailData=paymentDetailData;

						for (let i = 0; i < data.rows.length; i++) {
							let row = data.rows[i];
							let { paymentNumber
								, writeTime
								, treatmentProcedureNm
								, paymentCategoryItemNm
								, amount
								, vat
								, discountPrice
								,membershipPrice
								, nonpayAmount
								, totalAmount
								, paymentAmount
								,refundAmount
								, status1
								, status2
								, etc: rowEtc } = row;

							let refundColor = refundAmount<0?'red':'black'

							if (rowEtc) {
								etc += rowEtc;
								if (i < data.rows.length - 1)
									etc += '\n';
							}

							listHTML += `
								<tr id="${paymentNumber}">
									<td><p>${writeTime}</p></td>
									<td><p>${fn_removeDuplicateWord(paymentCategoryItemNm)||'-'}</p></td>
									<td class="number"><p>${formatTreatmentProcedure(treatmentProcedureNm)}</p></td>
									<td class="number"><p>${fn_numberFormat(totalAmount)||'-'}</p></td>
									<td class="number"><p>${discountPrice>0?('-'+fn_numberFormat(discountPrice)):'-'}</p></td>
									<td class="number"><p>${membershipPrice?(fn_numberFormat(membershipPrice)):'-'}</p></td>
									<td class="number"><p>${nonpayAmount?(fn_numberFormat(nonpayAmount)):'-'}</p></td>
									<td class="number"><p>${fn_numberFormat(paymentAmount)||'-'}</p></td>
									<td class="number"><p>${amount?fn_numberFormat(amount):'-'}</p></td>
									<td class="number"><p>${vat?fn_numberFormat(vat):'-'}</p></td>
									<td class="number"><p style="color:${refundColor}">${fn_numberFormat(refundAmount)||'-'}</p></td>
									<td><p>${status2==='P'&&treatmentProcedureNm===''?'미수':status1}</p></td>
								</tr>`;
						}
					} else {
						listHTML += `
							<tr>
								<td colspan="10" style="text-align: center;">조회 결과가 없습니다.</td>
							</tr>`;
					}

					if (data.paymentDetail.length > 0) {
						for (let i = 0; i < data.paymentDetail.length; i++) {
							let detail = data.paymentDetail[i];
							let { writeTime
								, paymentApprovalId='-'
								, amount
								, vat
								, discountPrice
								,membershipPrice
								, totalAmount
								, paymentCardInfo
								, paymentCategoryItemNm
								, cardInstallments='-'
								, status
								, refundAccount
								, refundEtc:rowRefundEtc } = detail;

							refundEtc += rowRefundEtc||'';

							if (i < data.rows.length - 1 && rowRefundEtc) {
								refundEtc += '\n';
							}

							let itemHTML=''
							if(status==='환불'||status==='결제취소'){
								itemHTML=`<p class="cancelP">(${status})</p>`
							}

							listHTML2 += `
								<ul class="payment_detail_list">
									<li class="first">
										<p>결제총액${itemHTML}</p>
										<p>${fn_numberFormat(totalAmount)}원</p>
									</li>
									<li>
										<p>공급가</p>
										<p>${amount?(amount.toLocaleString()+'원'):'-'}</p>
									</li>
									<li>
										<p>부가세</p>
										<p>${vat?(vat.toLocaleString()+'원'):'-'}</p>
									</li>
									<li>
										<p>멤버십</p>
										<p>${membershipPrice?(membershipPrice.toLocaleString()+'원'):'-'}</p>
									</li>
									<li>
										<p>할인</p>
										<p>${discountPrice?(discountPrice.toLocaleString()+'원'):'-'}</p>
									</li>
									<li>
										<p>결제시간</p>
										<p>${writeTime}</p>
									</li>
									<li>
										<p>결제수단</p>
										<p>${status==='환불'?refundAccount||paymentCategoryItemNm:paymentCardInfo?.trim() || paymentCategoryItemNm}</p>
									</li>
									<li>
										<p>결제구분</p>
										<p>${cardInstallments}</p>
									</li>
									<li>
										<p>승인번호</p>
										<p>${paymentApprovalId}</p>
									</li>
									<li>
										<p>승인상태</p>
										<p>${status}</p>
									</li>
								</ul>`;
						}
					}

					if (data.procedureList.length > 0) {
						for (let i = 0; i < data.procedureList.length; i++) {
							let procedure = data.procedureList[i];
							let { writeTime, writeDate, treatmentProcedureName, treatmentName, totalAmount, status } = procedure;
							let statusString = '('+status+')'
							listHTML3 += `
								<tr>
									<td>
										<p>${writeDate}<span>${writeTime}</span></p>
									</td>
									<td>
										<p>${treatmentName}<span>${treatmentProcedureName}</span></p>
									</td>
									<td>
										<p>${totalAmount.toLocaleString()}원<span style="color: red">${(status==='환불'||status==='결제취소')?statusString:''}</span></p>
									</td>
								</tr>`;
						}
					}
					if(!paymentNumber){
						$('#reservePaymentInsertModal #payment_detail .table_box table tbody.tbodyPaymentHistory').html(listHTML);
						if(data.rows.length>0)
							$('#reservePaymentInsertModal #payment_detail .table_box table tbody.tbodyPaymentHistory tr').eq(0).click();
					}

					$('#reservePaymentInsertModal #payment_detail .right_bottom ul').remove();
					$('#reservePaymentInsertModal #payment_detail .right_bottom').prepend(listHTML2);
					$('#reservePaymentInsertModal #payment_detail .right_bottom .table_box tbody').html(listHTML3);
					$('#reservePaymentInsertModal #payment_detail .textarea_box textarea').eq(0).val(etc);
					//환불메모가 있을 때 TEXTAREA 활성화
					if(refundEtc) {
						$('#reservePaymentInsertModal #payment_detail .textarea_box label').eq(1).css('display', 'block');
						$('#reservePaymentInsertModal #payment_detail .textarea_box textarea').eq(1).css('display', 'block');
						$('#reservePaymentInsertModal #payment_detail .textarea_box textarea').eq(1).val(refundEtc);
					}else{
						$('#reservePaymentInsertModal #payment_detail .textarea_box label').eq(1).css('display', 'none');
						$('#reservePaymentInsertModal #payment_detail .textarea_box textarea').eq(1).css('display', 'none');
					}
				} else {
					modalEvent.danger("조회 오류", data.msgDesc);
				}
			},
			error: function (xhr, status, error) {
				modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend: function () { },
			complete: function () { }
		});
	},

	/*
	 * 팝업
	 * callback : 콜백함수, reqParam: 팝업파라미터
	 */
	popup: function (callback, reqParam) {
		// 초기화 후 열기
		reservePaymentInsertModal.init();

		// 콜백함수 지정.
		reservePaymentInsertModal.callback = callback;
		reservePaymentInsertModal.reqParam = reqParam;
		reservePaymentInsertModal.dataList = [];

		firstVisitYn = reqParam.visitYn==='Y'?'N':'Y';
		// 진료 콤보데이타 설정
		reservePaymentInsertModal.search();

		setTimeout(function () {
			$('#reservePaymentInsertModal').modal({ keyboard: false, backdrop: 'static' });
		}, 200);
	},

	save: function () {
		reservePaymentInsertModal.close();
	},

	/*
	 * 팝업 닫기
	 */
	close: function (type) {
		$('#reservePaymentInsertModal').modal('hide');

		if('R'==type){
			if( reservePaymentInsertModal.callback )  {
				reservePaymentInsertModal.callback();
			}
		}

		setTimeout(function(){
			$('#reservePaymentInsertModal').remove();
		},500);
	},

	HtmlTemplate : `
	<div id="reservePaymentInsertModal" class="modal payment_modal fade" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-body">
					<p class="user_name">
						<span class="user modalUserName"></span>
						<span class="modalBirthday"></span>
						<span class="modalNationality"></span>
						<span class="modalPhoneNumber"></span>
					</p>

					<!-- Nav tabs -->
					<div class="nav_box">
						<ul class="nav nav-tabs" role="tablist">
							<li role="presentation" class="active"><a href="#payment" aria-controls="payment" role="tab" data-toggle="tab">수납</a></li>
							<li role="presentation"><a href="#payment_detail" aria-controls="payment_detail" role="tab" data-toggle="tab">수납내역</a></li>
						</ul>
					</div>
					<!-- Tab panes -->
					<div class="tab-content">
						<div role="tabpanel" class="tab-pane active" id="payment">
							<div class="payment_left">
								<div class="table_box">
									<table>
										<thead>
											<tr>
												<th>
													<label for="checkAll" class="chk_box">
														<input type="checkbox" id="checkAll">
														<span class="on"></span>
													</label>
												</th>
												<th>예약일시</th>
												<th>상태</th>
												<th>진료내용</th>
												<th>담당의사</th>
												<th>공급가</th>
												<th>Vat</th>
												<th>총액</th>
												<th>미수금액</th>
												<th>수납상태</th>
											</tr>
										</thead>
										<tbody class="tbodyPayment">
											<tr>
												<td colspan="10" style="text-align:center;">조회 결과가 없습니다.</td>
											</tr>
										</tbody>
									</table>
								</div>
								
								<div class="btn_box">
									<button type="button" class="cancel_btn btnCancle"><p>취소</p></button>
								</div>
							</div>
							<div class="payment_right">
								<div class="right_top">
									<p class="label">수납</p>
								</div>
								<div class="right_wrap">
                                    <ul class="amount_detail_list">
                                        <li>
                                            <p>진료금액</p>
                                            <p>0원</p>
                                        </li>
                                        <li>
                                            <p>할인</p>
                                            <button class="discount_btn" style="transition: all 0.2s ease-in-out 0s;"><p>할인 적용</p></button>
                                            <div class="discount_box amount_applied">
                                                <p>-200,000원</p>
                                                <button><img src="/image/web/cancel.svg" alt="cancel"/></button>
                                            </div>
                                        </li>
                                        <li>
                                            <p>멤버십</p>
                                            <button class="membership_btn" style="transition: all 0.2s ease-in-out 0s;"><p>멤버십 적용</p></button>
                                            <div class="membership_box amount_applied">
                                                <p>-200,000원</p>
                                                <button><img src="/image/web/cancel.svg" alt="cancel"/></button>
                                            </div>
                                        </li>
                                    </ul>
                                    <ul class="amount_detail_sub">
                                        <li class="total_amount">
                                            <p>결제금액</p>
                                            <p>0원</p>
                                        </li>
                                        <li class="total_amount_list">
                                            <p>공급가액</p>
                                            <p>0원</p>
                                        </li>
                                        <li class="total_amount_list">
                                            <p>부가세</p>
                                            <p>0원</p>
                                        </li>
                                    </ul>
                                    <div class="list_table">
                                        <label>수납항목</label>
                                        <div class="table_box">
                                        <table>
                                            <thead>
                                                <tr>
                                                    <th>진료내용</th>
                                                    <th>총액</th>
                                                    <th>할인</th>
                                                    <th>멤버십</th>
                                                </tr>
                                            </thead>
                                            <tbody></tbody>
                                        </table>
                                        </div>
                                    </div>
                                    <div class="split_box">
                                        <div class="split_top">
                                            <button class="split_up_btn"><img src="/image/web/split_up.svg" alt="분할결제"/>분할결제</button>
                                            <div class="input_box">
                                                <input type="text" id="splitAmount" disabled/>원
                                            </div>
                                        </div>
                                        <ul>
                                            <li>
                                                <label for="split1" class="chk_box splitType">
                                                    <input type="checkbox" id="split1">
                                                    <span class="on"></span>
                                                </label>
                                                멤버십 사용금액만 결제 <span>(잔여 금액은 미수처리됩니다)</span>
                                            </li>
                                            <li>
                                                <label for="split2" class="chk_box splitType">
                                                    <input type="checkbox" id="split2">
                                                    <span class="on"></span>
                                                </label>
                                                선결제 처리 <span>(선결제 고객 결제 처리)</span>
                                            </li>
                                            <li>
                                                <label for="split3" class="chk_box splitType">
                                                    <input type="checkbox" id="split3">
                                                    <span class="on"></span>
                                                </label>
                                                미수처리 <span>(선택 후 결제하기 버튼클릭)</span>
                                            </li>
                                        </ul>
									</div>
									<div class="box_wrap">
										<div class="textarea_box">
											<label>수납메모</label>
											<textarea></textarea>
										</div>
										<div class="button_box button_modal">
											<button class="card_btn payType"><img class="b" src="/image/web/card.svg" alt="카드"/><img class="w" src="/image/web/cardW.svg" alt="카드"/>카드</button>
											<button class="monetization_btn payType" style="transition: all 0.2s ease-in-out 0s;"><img class="b" src="/image/web/monetization.svg" alt="카드"/><img class="w" src="/image/web/monetizationW.svg" alt="카드"/>현금</button>
											<button class="account_btn payType" style="transition: all 0.2s ease-in-out 0s;"><img class="b" src="/image/web/account.svg" alt="계좌이체"/><img class="w" src="/image/web/accountW.svg" alt="계좌이체"/>계좌이체</button>
											<button class="qr_btn payType" style="transition: all 0.2s ease-in-out 0s;"><img class="b" src="/image/web/qr.svg" alt="QR결제"/><img class="w" src="/image/web/qrW.svg" alt="QR결제"/>QR결제</button>
											<button class="pay_btn btnSave" style="transition: all 0.2s ease-in-out 0s;">결제하기</button>
										</div>
									</div>
								</div>
							</div>
						</div>
						<div role="tabpanel" class="tab-pane" id="payment_detail">
							<div class="payment_detail_left">
								<div class="table_box">
									<table>
										<thead>
											<tr>
												<th>결제일시</th>
												<th>결제수단</th>
												<th>진료내용</th>
												<th>결제총액</th>
												<th>할인</th>
												<th>멤버십</th>
												<th>미수</th>
												<th>결제금액</th>
												<th>공급가</th>
												<th>Vat</th>
												<th>취소/환불</th>
												<th>결제상태</th>
											</tr>
										</thead>
										<tbody class="tbodyPaymentHistory">
										</tbody>
									</table>
								</div>
								
								<div class="btn_box">
									<button type="button" class="cancel_btn btnCancle">취소</button>
								</div>
							</div>
							<div class="payment_detail_right">
								<div class="right_top">
									<p class="label">수납상세</p>
									<div class="button_box">
										<button class="payment_repay_btn" style="transition: all 0.2s ease-in-out 0s;">취소 재결제</button>
										<button class="payment_cancel_btn" style="transition: all 0.2s ease-in-out 0s;">결제취소</button>
                                        <button class="refund_btn" style="transition: all 0.2s ease-in-out 0s;">환불</button>
									</div>
								</div>
								<div class="right_bottom">
									<div class="table_box">
										<table>
											<caption>수납항목</caption>
											<thead>
												<tr>
													<th>진료일시</th>
													<th>진료/시술</th>
													<th>금액</th>
												</tr>
											</thead>
											<tbody>
											</tbody>
										</table>
									</div>
									<div class="textarea_box">
										<label>수납메모</label>
										<textarea readonly></textarea>
										<label style="display: none">환불메모</label>
										<textarea readonly style="display: none"></textarea>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	`
};
/****************************************************************************
 * 수납 번호 생성
 ****************************************************************************/
function getCurrentTimeString() {
	let now = new Date();
	let year = now.getFullYear().toString();
	let month = (now.getMonth() + 1).toString().padStart(2, '0');
	let day = now.getDate().toString().padStart(2, '0');
	let hours = now.getHours().toString().padStart(2, '0');
	let minutes = now.getMinutes().toString().padStart(2, '0');
	let seconds = now.getSeconds().toString().padStart(2, '0');
	let milliseconds = now.getMilliseconds().toString().padStart(3, '0');
	let currentTimeString = year + month + day + hours + minutes + seconds + milliseconds;
	return 'PM' + currentTimeString;
}

/****************************************************************************
 * 수납 모달 -오른쪽 데이터 업데이트
 ****************************************************************************/
function updateRightPane() {
	//할인적용 및 멤버십 적용 초기화
	fn_discountMembershipReset();

	fn_initResultDataList();
	payTypeBtnActive=true;
	fn_paymentBtnActive();

    let rightListHtml = '';
    let totalPayment = 0;
	let amount = 0;
	let vatAmount = 0;
	$('#reservePaymentInsertModal #payment .textarea_box textarea').val('');
    rowData.forEach(item => {
        let { '0':muReserveId, "3":treatmentName, "7": itemTotalAmount, "8":nonPayment, "6":vat } = item;
		let total = 0;
		let itemAmount = 0;
		let itemVat = 0;
		let itemNonPayment = 0;

		itemVat = parseInt(vat.replace(/,/g, ''), 10);
		itemAmount = parseInt(itemTotalAmount.replace(/,/g, ''), 10);
		itemNonPayment = parseInt(nonPayment.replace(/,/g, ''), 10);
		total = itemVat>0?Math.round((itemNonPayment||itemAmount)/1.1):(itemNonPayment||itemAmount);

        rightListHtml += `
            <tr>
                <td id="${muReserveId}"><p>${treatmentName}</p></td>
                <td><p>${(itemNonPayment||itemAmount).toLocaleString()}</p></td>
                <td class="color_red"><p>-</p></td>
                <td class="color_red"><p>-</p></td>
            </tr>`;


		totalPayment += itemNonPayment||itemAmount;
		amount += total
		vatAmount+=itemVat>0?(itemNonPayment||itemAmount)-total:0
    });

    $('#reservePaymentInsertModal #payment .payment_right tbody').html(rightListHtml);
    $('#reservePaymentInsertModal #payment .amount_detail_list li:first-child p').eq(1).html(totalPayment.toLocaleString() + '원');
	fn_setPaymentData(totalPayment, amount, vatAmount);
}

/****************************************************************************
 * 결제될 데이터 저장
 ****************************************************************************/
function fn_initResultDataList() {
	// 기존 결제데이터 초기화
	reservePaymentInsertModal.resultDataList = [];
	//수납 리스트 선택 데이터
	let paramData = JSON.parse(JSON.stringify(rowData));

	paramData.forEach(row => {
		//미수금액
		let rowNonPayment =parseInt(row["8"].replace(/,/g, ''), 10)
		//총액
		let rowTotalAmount =parseInt(row["7"].replace(/,/g, ''), 10)
		//할인 적용금액
		let matchedDiscount = discountData.find(discount => discount.id === row["0"]);
		//멤버십 적용금액
		let matchedMembership = membershipData.find(membership => membership.id === row["0"]);
		//수수료
		let vatAmount = parseInt(row["6"].replace(/,/g, ''), 10);

		//결제총액
		/*미수금액이 있다면 미수금이 총액.
		 *총액에서 할인된 금액과 멤버십 적용된 금액을 제함 */
		let paymentAmount = (rowNonPayment|| rowTotalAmount) - (matchedDiscount?.discountAmount || 0) - (matchedMembership?.discountAmount || 0);
		//공급가.
		/* 수수료가 있다면 공급가는 결제총액/1.1 (할인,멤버십 적용 후 다시 계산)
		* 없다면 결제총액===공급가*/
		let amount = vatAmount > 0 ? Math.round(paymentAmount / 1.1) : paymentAmount;
		//수수료.
		/* 기존 수수료가 있다면 결제총액-공급가 (할인,멤버십 적용 후 다시 계산)
		* 없다면 0 적용*/
		let vat = vatAmount > 0 ? paymentAmount - amount : 0;

		let rowData = {
			muReserveId: row[0].substring(6),							// 예약 식별자
			muTreatmentId: row["muTreatmentId"],						// 진료구분 식별자
			muTreatmentProcedureId: row["muTreatmentProcedureId"],      // 시술 식별자
			treatmentName: row["3"].split(" - ")[0],			// 진료명
			treatmentProcedureName: row["3"].split(" - ")[1],  // 시술명
			membershipAmount: (matchedMembership?.discountAmount || 0), // 멤버십 적용 금액
			discountAmount: (matchedDiscount?.discountAmount || 0),     // 할인 적용 금액
			amount: amount,												// 공급가
			vat: vat,                                                   // 수수료
			nonPayment: rowNonPayment,									// 미수금
			totalAmount: paymentAmount,								    // 결제 총액
			reserveMemberId: row["reserveMemberId"],				    // 담당 직원 식별자
			reserveMemberName: row["4"],								// 담당 직원명
			orgStatusName: row["9"]                                     // 기존 수납상태값
		}
		reservePaymentInsertModal.resultDataList.push(rowData);
	});
	//결제번호
	reservePaymentInsertModal.resultDataList.paymentNumber = reservePaymentInsertModal.paymentNumber;
	//결제 식별자. 기존 미수처리가 아닌 신규 결제데이터면 undefined
	reservePaymentInsertModal.resultDataList.muPaymentId = muPaymentId;
	//초진. 재진 구분
	reservePaymentInsertModal.resultDataList.firstVisitYn = firstVisitYn;
}

/****************************************************************************
 * 중복 데이터 제거
 ****************************************************************************/
function isEquivalent(obj1, obj2) {
    const keys1 = Object.keys(obj1);
    const keys2 = Object.keys(obj2);

    if (keys1.length !== keys2.length) {
        return false;
    }

    for (const key of keys1) {
        if (obj1[key] !== obj2[key]) {
            return false;
        }
    }
    return true;
}

/****************************************************************************
 * 할인적용 데이터 저장
 ****************************************************************************/
function fn_setDiscountData(data) {
	//기존 데이터 초기화
    reservePaymentInsertModal.resultDataList = [];
    //총 할인액
    let totalDiscount = data.reduce((sum, item) => sum + item.discountAmount, 0);
    // 총 공급가
    let totalAmount = 0;
    //총 부가세
    let totalVat = 0;

    let paramData = JSON.parse(JSON.stringify(rowData));
    paramData.forEach(row => {
        //미수금액
		let rowNonPayment =parseInt(row["8"].replace(/,/g, ''), 10)
		//총액
		let rowTotalAmount =parseInt(row["7"].replace(/,/g, ''), 10)
		//할인 적용금액
		let matchedDiscount = discountData.find(discount => discount.id === row["0"]);
		//멤버십 적용금액
        let matchedMembership = membershipData.find(membership => membership.id === row["0"]);
        //수수료
        let vatAmount = parseInt(row["6"].replace(/,/g, ''), 10);
        //공급가
        let rowAmount = parseInt(row["5"].replace(/,/g, ''), 10);

        //결제총액
		/*미수금액이 있다면 미수금이 총액.
		 *총액에서 할인된 금액과 멤버십 적용된 금액을 제함 */
        let paymentAmount = (rowNonPayment|| rowTotalAmount) - (matchedDiscount?.discountAmount || 0) - (matchedMembership?.discountAmount || 0);

        //공급가.
		/* 수수료가 있다면 공급가는 결제총액/1.1 (할인,멤버십 적용 후 다시 계산)
		* 없다면 결제총액===공급가*/
        let amount = vatAmount > 0 ? Math.round(paymentAmount / 1.1) : paymentAmount;

        //수수료.
		/* 기존 수수료가 있다면 결제총액-공급가 (할인,멤버십 적용 후 다시 계산)
		* 없다면 0 적용*/
        let vat = vatAmount > 0 ? paymentAmount - amount : 0;

        totalAmount += amount;
        totalVat += vat;

        let rowData = {
            muReserveId: row[0].substring(6),                           // 예약 식별자
            muTreatmentId: row["muTreatmentId"],                        // 진료구분 식별자
            muTreatmentProcedureId: row["muTreatmentProcedureId"],      // 시술 식별자
			treatmentName: row["3"].split(" - ")[0],           // 진료명
			treatmentProcedureName: row["3"].split(" - ")[1],  // 시술명
            membershipAmount: (matchedMembership?.discountAmount || 0), // 멤버십 적용 금액
            discountAmount: (matchedDiscount?.discountAmount || 0),     // 할인 적용 금액
            amount: amount,                                             // 결제 공급가
            vat: vat,                                                   // 결제 수수료
            totalAmount: paymentAmount,									// 결제 총액
            originAmount: rowAmount,                                    // 공급가
            originVat: vatAmount,                                       // 수수료
            originTotalAmount:rowTotalAmount,                           // 총액
            nonPayment: rowNonPayment,                                  // 미수금
            membershipBalance: membershipData.finalMembershipBalance,   // 멤버십 잔액
            reserveMemberId: row["reserveMemberId"],                    // 담당 직원 식별자
            reserveMemberName: row["4"],                                // 담당 직원명
			orgStatusName: row["9"]                                     // 기존 수납상태값
        }
        reservePaymentInsertModal.resultDataList.push(rowData);
    });
    //결제번호
    reservePaymentInsertModal.resultDataList.paymentNumber = reservePaymentInsertModal.paymentNumber;
    //결제 식별자. 기존 미수처리가 아닌 신규 결제데이터면 undefined
    reservePaymentInsertModal.resultDataList.muPaymentId = muPaymentId;
    //초진. 재진 구분
    reservePaymentInsertModal.resultDataList.firstVisitYn =firstVisitYn;

    //할인적용버튼 숨김
    $('#reservePaymentInsertModal .discount_btn').hide();
    //할인 적용금액 표출
    $('#reservePaymentInsertModal .discount_box p').text('-' + totalDiscount.toLocaleString() + '원');
     //할인취소버튼 보임
    $('#reservePaymentInsertModal .discount_box').show();

    let result = totalAmount + totalVat;

    fn_setPaymentData(result, totalAmount, totalVat);
	fn_splitReset();
    $('#reservePaymentInsertModal #payment .payment_right tbody tr').each(function () {
        let $row = $(this);
        let itemId = $row.find('td:nth-child(1)').attr('id');

        let matchedData = data.find(data => data.id === itemId);

        if (matchedData) {
            $row.find('td:nth-child(3)').text('-' + matchedData.discountAmount.toLocaleString());
        }
    });
}

/****************************************************************************
 * 멤버십 적용 데이터 저장
 ****************************************************************************/
function fn_setMembershipData(data) {
    //기존 데이터 초기화
	reservePaymentInsertModal.resultDataList = [];
	//총 할인액
    let totalDiscount = data.reduce((sum, item) => sum + item.discountAmount, 0);
    // 총 공급가
    let totalAmount = 0;
    //총 부가세
    let totalVat = 0;

    let paramData = JSON.parse(JSON.stringify(rowData));
    paramData.forEach(row => {
        //미수금액
        let rowNonPayment =parseInt(row["8"].replace(/,/g, ''), 10)
        //총액
		let rowTotalAmount =parseInt(row["7"].replace(/,/g, ''), 10)
        //할인 적용금액
        let matchedDiscount = discountData.find(discount => discount.id === row["0"]);
        //멤버십 적용금액
        let matchedMembership = membershipData.find(membership => membership.id === row["0"]);
        //수수료
        let vatAmount = parseInt(row["6"].replace(/,/g, ''), 10);
         //공급가
        let rowAmount = parseInt(row["5"].replace(/,/g, ''), 10);

        //결제총액
		/*미수금액이 있다면 미수금이 총액.
		 *총액에서 할인된 금액과 멤버십 적용된 금액을 제함 */
        let paymentAmount = (rowNonPayment|| rowTotalAmount) - (matchedDiscount?.discountAmount || 0) - (matchedMembership?.discountAmount || 0);

        //공급가.
		/* 수수료가 있다면 공급가는 결제총액/1.1 (할인,멤버십 적용 후 다시 계산)
		* 없다면 결제총액===공급가*/
        let amount = vatAmount > 0 ? Math.round(paymentAmount / 1.1) : paymentAmount;

        //수수료.
		/* 기존 수수료가 있다면 결제총액-공급가 (할인,멤버십 적용 후 다시 계산)
		* 없다면 0 적용*/
        let vat = vatAmount > 0 ? paymentAmount - amount : 0;

        totalAmount += amount;
        totalVat += vat;

		let rowData = {
			muReserveId: row[0].substring(6),                           // 예약 식별자
			muTreatmentId: row["muTreatmentId"],                        // 진료구분 식별자
			muTreatmentProcedureId: row["muTreatmentProcedureId"],      // 시술 식별자
			treatmentName: row["3"].split(" - ")[0],                    // 진료명
			treatmentProcedureName: row["3"].split(" - ")[1],           // 시술명
			membershipAmount: (matchedMembership?.discountAmount || 0), // 멤버십 적용 금액
			discountAmount: (matchedDiscount?.discountAmount || 0),     // 할인 적용 금액
			amount: amount,                                             // 결제 공급가
			vat: vat,                                                   // 결제 수수료
			originAmount: rowAmount,                                    // 공급가
			originVat: vatAmount,                                       // 수수료
			originTotalAmount: rowTotalAmount,                          // 총액
			nonPayment: rowNonPayment,                                  // 미수금
			totalAmount: paymentAmount,                                 // 결제 총액
			membershipBalance: membershipData.finalMembershipBalance,   // 멤버십 잔액
			reserveMemberId: row["reserveMemberId"],                    // 담당 직원 식별자
			reserveMemberName: row["4"],                                // 담당 직원명
			orgStatusName: row["9"]                                     // 기존 수납상태값
		}
		reservePaymentInsertModal.resultDataList.push(rowData);
	});
	//결제번호
	reservePaymentInsertModal.resultDataList.paymentNumber = reservePaymentInsertModal.paymentNumber;
	//결제 식별자. 기존 미수처리가 아닌 신규 결제데이터면 undefined
	reservePaymentInsertModal.resultDataList.muPaymentId = muPaymentId;
	//초진. 재진 구분
	reservePaymentInsertModal.resultDataList.firstVisitYn =firstVisitYn;

    //멤버십 적용버튼 숨김
	$('#reservePaymentInsertModal .membership_btn').hide();
	//멤버십 적용금액 표출
	$('#reservePaymentInsertModal .membership_box p').text('-' + totalDiscount.toLocaleString() + '원');
	//멤버십취소버튼 보임
	$('#reservePaymentInsertModal .membership_box').show();

	let result = totalAmount + totalVat;

	fn_setPaymentData(result, totalAmount, totalVat);
	fn_splitReset();
	$('#reservePaymentInsertModal #payment .payment_right tbody tr').each(function () {
		let $row = $(this);
		let itemId = $row.find('td:nth-child(1)').attr('id');
		let matchedData = data.find(data => data.id === itemId);
		if (matchedData) {
			$row.find('td:nth-child(4)').text('-' + matchedData.discountAmount.toLocaleString());
		}
	});
}

/****************************************************************************
 * 분할결제 데이터 저장
 ****************************************************************************/
function fn_setSplitData(splitAmount) {
	reservePaymentInsertModal.resultDataList = [];
	//분할결제 완료된 값
	let totalAmount = 0;
	let totalVat = 0;
	let paramData = JSON.parse(JSON.stringify(rowData));
	let remainData = splitAmount;

	paramData.forEach(row => {
		// 항목별 미수 금액
		let rowNonPayment =parseInt(row["8"].replace(/,/g, ''), 10)
		// 항목별 총액
		let rowTotalAmount =parseInt(row["7"].replace(/,/g, ''), 10)
		// 해당항목에 적용된 할인
		let matchedDiscount = discountData.find(discount => discount.id === row["0"]);
		// 해당항목에 적용된 멤버십
		let matchedMembership = membershipData.find(membership => membership.id === row["0"]);
		// 결제금액 계산
		let paymentAmount = (rowNonPayment|| rowTotalAmount) - (matchedDiscount?.discountAmount || 0) - (matchedMembership?.discountAmount || 0);

        // 남은 결제 금액 계산
		if(remainData>0){
			remainData-=paymentAmount
			if(remainData>=0){
				paymentAmount = 0
			}else if(remainData<0){
				paymentAmount=Math.abs(remainData);
			}
		}
        // VAT 및 공급가 계산 (VAT가 있으면 부가세 포함 금액을 계산)
		let vatAmount = parseInt(row["6"].replace(/,/g, ''), 10);// VAT
		let rowAmount = parseInt(row["5"].replace(/,/g, ''), 10);// 공급가
		let amount = vatAmount > 0 ? Math.round(paymentAmount / 1.1) : paymentAmount; // VAT가 있으면 1.1로 나눠서 공급가 계산
		let vat = vatAmount > 0 ? paymentAmount - amount : 0; // VAT가 있으면 결제 금액에서 공급가를 뺀 부가세 계산
		totalAmount += amount;
		totalVat += vat;

		let rowData = {
			muReserveId: row[0].substring(6),                           // 예약 식별자
			muTreatmentId: row["muTreatmentId"],                        // 진료 식별자
			muTreatmentProcedureId: row["muTreatmentProcedureId"],      // 시술식별자
			treatmentName: row["3"].split(" - ")[0],                    // 진료명
			treatmentProcedureName: row["3"].split(" - ")[1],           // 시술명
			membershipAmount:0,                                         // 멤버십 초기화
			discountAmount:0,                                           // 할인적용 초기화
			amount: amount,                                             // (분할결제 적용)공급가
			vat: vat,                                                   // (분할결제 적용)VAT
			totalAmount: paymentAmount,                                 // (분할결제 적용)결제 총액
			originAmount: rowAmount,                                    // (분할결제 적용 전) 공급가
			originVat: vatAmount,                                       // (분할결제 적용 전) VAT
			originTotalAmount:rowTotalAmount,                           // (분할결제 적용 전) 총액
			nonPayment: rowNonPayment,                                  // 미수 금액
			reserveMemberId: row["reserveMemberId"],                    // 담당직원 식별자
			reserveMemberName: row["4"],                                // 예약된 멤버 이름
			orgStatusName: row["9"]                                     // 기존 수납상태값
		};

		// 결과 데이터를 배열에 추가
		reservePaymentInsertModal.resultDataList.push(rowData);
	});

	// 결제 정보에 결제 번호와 결제 식별자, 재방문 여부 추가
	reservePaymentInsertModal.resultDataList.paymentNumber = reservePaymentInsertModal.paymentNumber;
	reservePaymentInsertModal.resultDataList.muPaymentId = muPaymentId;
	reservePaymentInsertModal.resultDataList.firstVisitYn = firstVisitYn;


	let result = totalAmount + totalVat;

	//결제모달 오른쪽 결제금액 데이터 업데이트
	fn_setPaymentData(result, totalAmount, totalVat);
}

/****************************************************************************
 * 결제모달 오른쪽 결제금액 데이터 표출
 ****************************************************************************/
function fn_setPaymentData(total, amount, vat) {
	$('#reservePaymentInsertModal #payment .total_amount p').eq(1).html(total.toLocaleString() + '원');
	$('#reservePaymentInsertModal #payment .total_amount_list p').eq(1).html(amount.toLocaleString() + '원');
	$('#reservePaymentInsertModal #payment .total_amount_list p').eq(3).html(vat.toLocaleString() + '원');
	//결제금액이 없으면 버튼 비활성화
	if(total===0){
		fn_paymentBtnDeactive();
	}else{
		fn_paymentBtnActive();
	}
}

/****************************************************************************
 * 분할결제 및 결제 타입 체크
 ****************************************************************************/
function fn_checkPaymentType() {
	//분할결제 or 미수,선결제,멤버십만
	//분할결제 버튼 미활성화라면 미수,선결제,멤버십중 선택된 값
    let splitType = $('#reservePaymentInsertModal .split_up_btn img').hasClass('active') ? 'splitPayment' :
        $('#reservePaymentInsertModal .split_box input[type="checkbox"]:checked').attr('id');

	//결제수단
    let paymentType = '';
	//분할결제이거나 분할결제 항목중 선택된 항목이 없다면 결제수단 확인.
    if (!splitType || 'splitPayment' === splitType) {
		paymentType = $('#reservePaymentInsertModal .button_modal .payType.active').text();
		//결제 데이터에서 총 결제금액 확인
		if(reservePaymentInsertModal.resultDataList.reduce((sum, item) => sum + item.totalAmount, 0)===0){
			//결제할 금액이 0원 이라면 (멤버십 or 할인 적용)
			if(reservePaymentInsertModal.resultDataList.reduce((sum, item) => sum + item.membershipAmount, 0)>0){
				//멤버십 적용 되어있을 경우 멤버십 사용금액만 결제로 처리.
				splitType='split1';
			}else{
				//할인으로만 결제할 경우
				splitType = 'discountOnly'
			}
		}
    }
    return { splitType: splitType, paymentType: paymentType };
}

/****************************************************************************
 * 결제 수단 선택 버튼 활성화
 ****************************************************************************/
function fn_paymentBtnActive() {
    if (payTypeBtnActive) {
        $('#reservePaymentInsertModal .button_modal .payType').css('background', 'white');
        $('#reservePaymentInsertModal .button_modal .payType').css('border', '1px solid #E9ECF0');
        $('#reservePaymentInsertModal .button_modal .payType').css('padding', '0');
        $('#reservePaymentInsertModal .button_modal .payType').removeClass('active');
    }
}

/****************************************************************************
 * 결제 수단 선택 버튼 비활성화
 ****************************************************************************/
function fn_paymentBtnDeactive() {
    $('#reservePaymentInsertModal .button_modal .payType').css('background', '#E9ECF0');
    $('#reservePaymentInsertModal .button_modal .payType').removeClass('active');
    payTypeBtnActive = false;
}

/****************************************************************************
 * 수납내역 진료내용 항목 렌더링
 ****************************************************************************/
function formatTreatmentProcedure(treatmentProcedureNm) {
    let procedures = treatmentProcedureNm.split(',');
    let mainProcedure = procedures[0];
    let additionalCount = procedures.length - 1;
    let result = mainProcedure;
    if (additionalCount > 0) {
        result += ` 외 ${additionalCount}건`;
    }
    return result;
}

/****************************************************************************
 * 부분결제 시 결제총액과 부분결제금액을 대비하여 공급가와 부가세 계산.
 ****************************************************************************/
function fn_calculatePartialPayment(totalPayment, supplyAmount, partialPayment) {
	// 부분결제 금액의 비율을 계산
	let partialRatio = partialPayment / totalPayment;

	// 부분공급가액과 부분부가세액을 계산
	let partialSupplyAmount = Math.floor(supplyAmount * partialRatio);
	let partialVatAmount = partialPayment - partialSupplyAmount;

	return {
		partialSupplyAmount: partialSupplyAmount,
		partialVatAmount: partialVatAmount
	};
}

function fn_calculatePartialPayment2(totalPayment, partialPayment) {
	let supplyRatio = Math.round(totalPayment / 1.1) / totalPayment;
	let vatRatio = (totalPayment - Math.round(totalPayment / 1.1)) / totalPayment;
	let partialSupplyAmount = Math.round(partialPayment * supplyRatio);
	let partialVatAmount = partialPayment - partialSupplyAmount;
	return {
		partialSupplyAmount: partialSupplyAmount,
		partialVatAmount: partialVatAmount
	};
}

/****************************************************************************
 * 수납 모달 초기화
 ****************************************************************************/
function init() {
	//결제 수단 선택 버튼 활성화
	fn_paymentBtnActive();
	payTypeBtnActive = true;
	//분할결제 입력 금액 제거
	$('#splitAmount').val('');
	//분할결제 항목 체크 초기화
	fn_splitReset();
	//결제번호 생성
	reservePaymentInsertModal.paymentNumber = getCurrentTimeString();
	//수납내역 체크 초기화
	$('#reservePaymentInsertModal #checkAll').prop('checked', false);
	$('#reservePaymentInsertModal #payment .tbodyPayment input[type="checkbox"]').prop('checked', false);
	//멤버십, 할인 적용 초기화
	fn_discountMembershipReset();
	//데이터 리스트 초기화
	rowData = [];
	reservePaymentInsertModal.resultDataList = [];
	reservePaymentInsertModal.dataList = [];
	//모달 이벤트 제거
	removeEvents();
	//모달 오른쪽 표출 데이터 업데이트
	updateRightPane();

	$('#reservePaymentInsertModal #splitPayment').remove();
	$('#reservePaymentInsertModal .modal-body a').prop('disabled', false);
	$('#reservePaymentInsertModal .amount_detail_list button').prop('disabled', false);
	$('#reservePaymentInsertModal .split_top button').prop('disabled', false);
	$('#reservePaymentInsertModal .btn_box button.btnCancle').prop('disabled', false);
	$('#reservePaymentInsertModal .chk_box input').prop('disabled', false);
	$('#reservePaymentInsertModal textArea').prop('disabled', false);
}

/****************************************************************************
 * 수납 데이터 전체 선택 여부 확인
 ****************************************************************************/
function fn_checkAll(){
	let allChecked = $('#reservePaymentInsertModal .tbodyPayment input[type="checkbox"]').length === $('#reservePaymentInsertModal .tbodyPayment input[type="checkbox"]:checked').length;
	$('#reservePaymentInsertModal #checkAll').prop('checked', allChecked);
	updateRightPane();
}

/****************************************************************************
 * 할인 및 멤버십 적용 초기화
 ****************************************************************************/
function fn_discountMembershipReset(){
	$('#reservePaymentInsertModal .membership_btn').css('display', 'block');
	$('#reservePaymentInsertModal .membership_box').css('display', 'none');
	$('#reservePaymentInsertModal .discount_btn').css('display', 'block');
	$('#reservePaymentInsertModal .discount_box').css('display', 'none');
	membershipData=[];
	discountData=[];
}

/****************************************************************************
 * 분할결제 및 분할 결제 선택 항목 초기화
 ****************************************************************************/
function fn_splitReset(){
	$('#reservePaymentInsertModal .split_up_btn').removeClass('active', $(this).is(':checked')).find('img').removeClass('active', $(this).is(':checked'));
	$('#splitAmount').val('').css('background', '#E9ECF0');
	$('#reservePaymentInsertModal .splitType input[type="checkbox"]').prop('checked', false);
}

/****************************************************************************
 * 결제 진행 중 조건 변경 불가.
 ****************************************************************************/
function fn_nonTouchModal(){
	$('#reservePaymentInsertModal .modal-body a').prop('disabled', true);
	$('#reservePaymentInsertModal .amount_detail_list button').prop('disabled', true);
	$('#reservePaymentInsertModal .split_top button').prop('disabled', true);
	$('#reservePaymentInsertModal .btn_box button.btnCancle').prop('disabled', true);
	$('#reservePaymentInsertModal .chk_box input').prop('disabled', true);
	$('#reservePaymentInsertModal textArea').prop('disabled', true);
	fn_paymentBtnActive();
	$('#reservePaymentInsertModal #splitAmount').val('');
	$('#reservePaymentInsertModal .chk_box span').on('click',function(){modalEvent.warning('오류','결제 진행중에 선택 조건을 변경 할 수 없습니다.')})
	$('#reservePaymentInsertModal .amount_detail_list p').on('click',function(){modalEvent.warning('오류','결제 진행중에 금액 조건을 변경 할 수 없습니다.')});
	$('#reservePaymentInsertModal .nav-tabs li').on('click',function(){modalEvent.warning('오류','결제 진행중에 메뉴이동을 할 수 없습니다.')})
	$('#reservePaymentInsertModal .btnCancle p').on('click',function(){modalEvent.warning('오류','결제 진행중에 창을 닫을 수 없습니다.')})
}

/****************************************************************************
 * 이벤트 제거.
 ****************************************************************************/
function removeEvents() {
	$('#reservePaymentInsertModal .chk_box span').off('click');
	$('#reservePaymentInsertModal .amount_detail_list p').off('click');
	$('#reservePaymentInsertModal .nav-tabs li').off('click');
	$('#reservePaymentInsertModal .btnCancle p').off('click');
}

/****************************************************************************
 * 결제하기
 ****************************************************************************/
async function fn_payment(mode) {
	let data = reservePaymentInsertModal.resultDataList;
	let muUserId = reservePaymentInsertModal.reqParam.muUserId;
	let reverseData = [];
	let detailData = [];
	let paymentData = [];
	let paymentResponseData = {};

	//결제금액 (할인 및 멤버십 차감 후)
	let totalAmount = 0
	//공급가 (할인 및 멤버십 차감 후)
	let itemAmount = 0;
	//vat (할인 및 멤버십 차감 후)
	let itemVat = 0;
	//결제수단 코드
	let paymentCategoryItemId = ''
	//결제수단명
	let paymentCategoryItemName = ''
	// 분할결제중 상태값 (분할결제중:G)
	let status = ''
	//결제 상태값
	let status2 = ''
	//단말기 응답 식별자
	let muPaymentResponseHistoryId = '';
	//단말기 요청 식별자
	let muPaymentRequestHistoryId = '';
	//단말기 승인번호
	let muApprovalId = '';

	//split2(선결제) or split3(미수처리) 경우엔 미사용
	//멤버십 잔액
	let membershipBalance = data[0].membershipBalance;
	//분할결제금액
	let splitAmount = data.splitAmount
	//멤버십 결제금액
	let membershipAmount = data.reduce((sum, item) => sum + item.membershipAmount, 0);

	//선결제일 경우
	if (mode === 'split2') {
		totalAmount = data.reduce((sum, item) => sum + item.totalAmount, 0);
		itemAmount = data.reduce((sum, item) => sum + item.amount, 0);
		itemVat = data.reduce((sum, item) => sum + item.vat, 0);
		//결제완료 처리
		status2 = 'Y';
		paymentCategoryItemId = 'PP'
		paymentCategoryItemName = '선결제'

	}
	//미수처리일 경우
	else if (mode === 'split3') {
		//결제 미수처리
		status2 = 'NP';
		//미수여서 결제 수단 없음.
		paymentCategoryItemId = ''
		paymentCategoryItemName = ''

	}
	// 카드결제시
	else if (mode === 'card') {

		//단말기 전송 데이터 생성
		let posRequestParam = {
			S01: 'D1', 				// 전문 구분코드 2자리 (카드결제 요청 시: D1)
			S03: '',
			S04: '',
			S07: '',				// 금액 8자리
			S08: '00000000',		// 봉사료 8자리
			S09: '',			    // 부가세 8자리
		}

		totalAmount = data.reduce((sum, item) => sum + item.totalAmount, 0);
		itemAmount = data.reduce((sum, item) => sum + item.amount, 0);

		//부분결제 공급가, vat 계산.
		let calculatePartialPayment
			= fn_calculatePartialPayment(totalAmount, itemAmount, splitAmount || totalAmount);
		//부분결제 시 공급가 변경.
		itemAmount = calculatePartialPayment.partialSupplyAmount;
		itemVat = calculatePartialPayment.partialVatAmount;

		//결제 총액
		posRequestParam.S07 = String(itemAmount + itemVat);
		//부가세
		posRequestParam.S09 = String(itemVat);

		//고객정보
		let userName = $('#reservePaymentInsertModal .modalUserName').text();
		let userData = {muUserId:muUserId
											       ,userName:userName};

		//단말기 연동 여부 확인
		if(terminalLinkage){
			completeFlag = true;
			//단말기 요청 정보 디비 저장
			muPaymentRequestHistoryId = fn_saveRequestParam(posRequestParam,userData);
			try {
				//단말기로 결제 요청 후 응답데이터 return
				paymentResponseData = await sendData(createDataString(posRequestParam));

				//요청 실패했을 경우
				if('0000'!==paymentResponseData.responseCode){
					modalEvent.warning("결제 오류",paymentResponseData.msg);
					return false;
				}
				// 디비에 응답 데이터 저장 후 식별자 return
				muPaymentResponseHistoryId = fn_saveResponseData(muPaymentRequestHistoryId, paymentResponseData);
			} catch (error) {
				console.error('Error in sendData:', error);
				return;
			}
		}
		//미수금액
		let nonPayment = data.reduce((sum, item) => sum + item.nonPayment, 0);

		status = splitAmount && (totalAmount !== splitAmount) ? 'G' : 'Y';

		// 미수금액이 있다면 상태값은 미수결제.
		let amountStat = nonPayment > 0 ? 'NY' : 'Y';
		if ('G' === status) {
			status2 = 'Y';
		} else {
			status2 = amountStat;
		}

		paymentCategoryItemId = 'C';
		paymentCategoryItemName = '카드';

	}
	// QR 결제시
	else if (mode === 'qr') {
		let posRequestParam = {
			S01: 'D1', 	     // 전문 구분코드 2자리 (카드결제 요청과 동일하게 요청: D1)
			S03: '',
			S04: '',
			S07: '',		 // 금액 8자리
			S08: '00000000', // 봉사료 8자리
			S09: '',		 // 부가세 8자리
		}

		totalAmount = data.reduce((sum, item) => sum + item.totalAmount, 0);
		itemAmount = data.reduce((sum, item) => sum + item.amount, 0);

		//부분결제 공급가, vat 계산.
		let calculatePartialPayment
			= fn_calculatePartialPayment(totalAmount, itemAmount, splitAmount || totalAmount);
		//부분결제 시 공급가 변경.
		itemAmount = calculatePartialPayment.partialSupplyAmount;
		itemVat = calculatePartialPayment.partialVatAmount;

		//결제 총액
		posRequestParam.S07 = String(itemAmount + itemVat);
		//부가세
		posRequestParam.S09 = String(itemVat);

		//고객정보
		let userName = $('#reservePaymentInsertModal .modalUserName').text();
		let userData = {muUserId: muUserId, userName: userName};

		//단말기 연동 여부 확인
		if (terminalLinkage){
			completeFlag = true;
			//단말기 요청 정보 디비 저장
			muPaymentRequestHistoryId = fn_saveRequestParam(posRequestParam, userData);
			try {
				// 디비에 요청 데이터 저장 후 식별자 return
				paymentResponseData = await sendData(createDataString(posRequestParam));

				//요청 실패했을 경우
				if ('0000' !== paymentResponseData.responseCode) {
					modalEvent.warning("결제 오류", paymentResponseData.msg);
					return false;
				}
				// 디비에 응답 데이터 저장 후 식별자 return
				muPaymentResponseHistoryId = fn_saveResponseData(muPaymentRequestHistoryId, paymentResponseData);
			} catch (error) {
				console.error('Error in sendData:', error);
				return;
			}
	    }
        //미수금액
		let nonPayment = data.reduce((sum, item) => sum + item.nonPayment, 0);

		status = splitAmount && (totalAmount !== splitAmount) ? 'G' : 'Y';

	    // 미수금액이 있다면 상태값은 미수결제.
		let amountStat = nonPayment > 0 ? 'NY' : 'Y';
		if ('G' === status) {
			status2 = 'Y';
		} else {
			status2 = amountStat;
		}

		paymentCategoryItemId = 'Q';
		paymentCategoryItemName = '간편결제';

	}
	//할인적용으로 결제금액이 0이 됐을경우.
	else if (mode === 'discountOnly') {
		totalAmount = data.reduce((sum, item) => sum + item.totalAmount, 0);
		itemAmount = data.reduce((sum, item) => sum + item.amount, 0);
		itemVat = data.reduce((sum, item) => sum + item.vat, 0);
		status2 = 'Y';
		paymentCategoryItemId = ''
		paymentCategoryItemName = ''
	}
	//결제 금액
	let paymentMoney = splitAmount || totalAmount;
	//카드번호
	let cardNumber='';
	//카드사
	let cardCompanyName='';
	//
	let cardInstallments='';
	let cardInstallmentsCode='';

	//단말기 응답 전문이 있을 경우
	if ( paymentResponseData.transactionType ) {
		//카드일 경우
		if ('I1' === paymentResponseData.transactionType) {
			cardNumber = formatCardNumber(paymentResponseData.cardNumber);
			cardCompanyName = paymentResponseData.issuerName;
			//할부 데이터 있을경우
			if (paymentResponseData.paymentOptionCode) {
				cardInstallments = paymentResponseData.paymentOptionCode + '개월';
				cardInstallmentsCode = paymentResponseData.paymentOptionCode;
			} else {
				cardInstallments = '일시불';
			}
		}
		//승인번호
		muApprovalId = paymentResponseData.approvalNo;
	}
	//
	data.forEach(row => {
		// 현재 항목의 결제 금액
		let detailAmount = 0;
		// 결제금액(paymentMoney)이 남아 있을 때만 처리
		if (paymentMoney > 0) {
		    // 결제금액에서 현재 항목의 금액(totalAmount)을 차감
			paymentMoney -= row["totalAmount"]
			// 결제 금액이 항목의 액수와 같거나 클 경우, 현재 항목의 금액을 모두 결제
			if (paymentMoney >= 0) {
				detailAmount = row["totalAmount"]
			}
			// 결제 금액이 부족한 경우, 남은 금액만큼만 결제
			else if (paymentMoney < 0) {
				detailAmount = row["totalAmount"] + paymentMoney;
			}
		}
        //예약 테이블 업데이트 데이터
		let rowData = {
			muReserveId: row["muReserveId"],
			status2: status2,
		}

		//수납 상세 테이블 insert 데이터
		let rowData2 = {
			muReserveId: row["muReserveId"],
			muTreatmentId: row["muTreatmentId"],
			muTreatmentProcedureId: row["muTreatmentProcedureId"],
			treatmentName: row["treatmentName"],
			treatmentProcedureName: row["treatmentProcedureName"],
			reserveMemberId: row["reserveMemberId"],
			amount: 0,
			vat: 0,
			totalAmount: detailAmount,
			discountPrice: row["discountAmount"] || 0,
			membershipPrice: parseInt('-' + (row["membershipAmount"] || 0)),
		}
		rowData2.amount = row['vat'] > 0 ? Math.round(detailAmount / 1.1) : detailAmount
		rowData2.vat = detailAmount - rowData2.amount;
		reverseData.push(rowData);
		detailData.push(rowData2);
	})

	//수납 테이블 insert 데이터
	let rowData3 = {
		paymentNumber: data.paymentNumber,
		muUserId: reservePaymentInsertModal.reqParam.muUserId,
		paymentApprovalId: muApprovalId,
		paymentCategoryItemId: paymentCategoryItemId,
		paymentCategoryItemName: paymentCategoryItemName,
		paymentCardInfo: cardCompanyName+' '+cardNumber,
		cardInstallments: cardInstallments,
		cardInstallmentsCode: cardInstallmentsCode,
		amount: itemAmount,
		vat: itemVat,
		paymentAmount: splitAmount || totalAmount,
		etc: $('#reservePaymentInsertModal #payment .textarea_box textarea').val(),
		status: status2,
		muPaymentId: data.muPaymentId,
		firstVisitYn: firstVisitYn,
		muPaymentRequestHistoryId: muPaymentRequestHistoryId,
		muPaymentResponseHistoryId: muPaymentResponseHistoryId
	}
	paymentData.push(rowData3);

	//멤버십 적용한 경우
	if (membershipAmount > 0) {
		let calculatePartialPayment2 = fn_calculatePartialPayment(totalAmount, itemAmount, membershipAmount);
		let amount2 = calculatePartialPayment2.partialSupplyAmount;
		let vat2 = calculatePartialPayment2.partialVatAmount;
		rowData3 = {
			paymentNumber: data.paymentNumber,
			muUserId: reservePaymentInsertModal.reqParam.muUserId,
			paymentCategoryItemId: 'MM',
			paymentCategoryItemName: '멤버십',
			amount: parseInt('-' + amount2, 0),
			vat: parseInt('-' + vat2, 0),
			paymentAmount: parseInt('-' + membershipAmount, 0),
			etc: $('#reservePaymentInsertModal #payment .textarea_box textarea').val(),
			status: status2,
			muPaymentId: data.muPaymentId,
		};
		paymentData.push(rowData3);
	}

	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("reserveData", JSON.stringify(reverseData));
	formData.append("detailData", JSON.stringify(detailData));
	formData.append("paymentData", JSON.stringify(paymentData));
	formData.append("membershipBalance", membershipBalance);

	$.ajax({
		url: encodeURI('/webpayment/insertPayment.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: false,
		success: function (data) {
			if ('0' == data.msgCode) {
				modalEvent.success("등록", '결제가 완료되었습니다.', function () {
					//잔여 금액 있는지 체크
					let result = splitAmount && (totalAmount !== splitAmount) ? 'G' : 'Y'
					//잔여 결제금액이 있는 경우
					if (result === 'G') {
						firstVisitYn = 'N';
						//이전에 결제완료된 분할결제 금액
						let existSplitAmount = $('#reservePaymentInsertModal #splitPayment p').eq(1).text()?.replace(/[^\d]/g, '')
						//총 결제된 분할금액
						let resultSplitAmount = (parseInt(existSplitAmount, 0) || 0) + splitAmount;
						//분할결제 후 데이터 업데이트
						fn_setSplitData(resultSplitAmount);
						//모달 표출 데이터 업데이트
						$('#reservePaymentInsertModal #splitPayment').remove();
						$('#reservePaymentInsertModal .amount_detail_list').append(
							`<li id="splitPayment">
								<p>분할결제 금액</p>
								<p>-${resultSplitAmount.toLocaleString()}원</p>
							 </li>`)
						//분할결제 진행중에는 모달 닫거나 이동할 수 없음.
						fn_nonTouchModal();
					} else {
						//결제 완료 시 남은 항목이 있는지, 계속 수납진행할지 여부 체크.
						fn_checkRemainPaymentList();
					}
				});
			} else {
				modalEvent.danger("등록 오류", data.msgDesc);
			}
		},
		error: function (xhr, status, error) {
			modalEvent.danger("등록 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend: function () {
			$(".loading-image-layer").show();
		},
		complete: function () {
			$(".loading-image-layer").hide();
		}
	});
}

/****************************************************************************
 * 카드번호 렌더링
 ****************************************************************************/
function formatCardNumber(cardInfo) {
	// 1. =를 기준으로 문자열을 나누기
	const parts = cardInfo.split('=');
	const firstPart = parts[0];

	// 2. 4자리마다 - 삽입
	return firstPart.replace(/(.{4})(?!$)/g, '$1-');
}

/****************************************************************************
 * 현금영수증 정보 렌더링
 ****************************************************************************/
function formatCashReceiptInfo(cashReceiptInfo){
	const firstPart = cashReceiptInfo.substring(0, 3);
	const middlePart = '****';
	const lastPart = cashReceiptInfo.substring(7);

	return `${firstPart}-${middlePart}-${lastPart}`;
}

/****************************************************************************
 * 남은 마납 항목이 있는지, 계속 수납진행할지 여부 체크.
 ****************************************************************************/
function fn_checkRemainPaymentList(){
	if(reservePaymentInsertModal.dataList.length!==rowData.length){
		firstVisitYn='N';
		modalEvent.info("성공", "미납 내역이 있습니다. 이어서 진행하시겠습니까?", function(){
			reservePaymentInsertModal.search();
			// 닫기버튼 시 새로고침
			$('#reservePaymentInsertModal .btnCancle').off("click");
			$('#reservePaymentInsertModal .btnCancle').on("click", function () {
				reservePaymentInsertModal.close('R');
			});
		},function (){
			reservePaymentInsertModal.close('R');
		});
	}else{
		reservePaymentInsertModal.close('R');
	}
}

/****************************************************************************
 * 중복 단어 제거 및 렌더링
 ****************************************************************************/
function fn_removeDuplicateWord(param){
	if(param){
		let array = param.split(',');
		let uniqueArray = [...new Set(array)];

		return uniqueArray.join(', ');
	}
	return ''
}
