
/* ##############################################################
	설  명 : [Modal]수납모달 - 현금결제 팝업
	작성일 : 2024. 06. 17.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2024. 06. 17.	NTsoft 	 최초 생성
*/
let cancellationPayModal = {
    callback : null,
    reqParam : null,
    dataList : null,
    /* 모달 초기화 작업 */
    init : function () {
        $('#cancellationPayModal').remove();
        $('body').append( this.HtmlTemplate);
        //그리드 이벤트
        this.setEvent();
    },
    /* 그리드 이벤트 설정 */
    setEvent:function() {
        $('#cancellationPayModal .btnCancle').on("click", function(){
            cancellationPayModal.close();
        });

        $('#cancellationPayModal .btnSave').on("click", function(){
            cancellationPayModal.save();
        });


    },
    // 미 수납건 조회
    search:function(state) {
        let data = cancellationPayModal.reqParam;

        let totalCancelAmount = 0;
        let paymentInfo = '';

        for(let i=0; i<data.paymentDetailData.length; i++){
            let totalCancelAmount2 = 0;
            let cardInfo = data.paymentDetailData[i].cardInfo;
            if('멤버십' == data.paymentDetailData[i].paymentCategoryItemName){
                totalCancelAmount2 = Math.abs(data.paymentDetailData[i].membershipPrice).toLocaleString();
                totalCancelAmount -= data.paymentDetailData[i].membershipPrice;

                cardInfo = '(멤버십)';
            }else{
                totalCancelAmount2 = Math.abs(data.paymentDetailData[i].totalAmount).toLocaleString();
                totalCancelAmount += data.paymentDetailData[i].totalAmount;
            }

            let id = data.paymentDetailData[i].muPaymentId+"_"+data.paymentDetailData[i].paymentCategoryItemId;
            let paymentData = encodeURIComponent(JSON.stringify(data.paymentDetailData[i]));


            paymentInfo += '<div>';
            paymentInfo += '    <input type="hidden" class="payment-checkbox" data-value="'+paymentData+'" id="'+id+'">';
            paymentInfo += '    <label for="'+id+'">';
            paymentInfo += '        <span class="on"></span>';
            paymentInfo += '        '+cardInfo+' : '+totalCancelAmount2+'원';
            paymentInfo += '    </label>';
            paymentInfo += '</div>';
        }

        $('#cancellationPayModal #totalCancelAmount').text(totalCancelAmount.toLocaleString()+'원');
        $('#cancellationPayModal #userName').text(data.userName || '-');
        $('#cancellationPayModal #reserveDate').text(data.reserveDate|| '-');
        $('#cancellationPayModal #treatmentProcedureName').text(data.procedureName || '-');
        $('#cancellationPayModal #cancelAmount').text(totalCancelAmount.toLocaleString()+'원');
        $('#cancellationPayModal #paymentItem').html(paymentInfo);

         // 카드 결제 관련 안내 추가
        if(data.paymentDetailData.some(item => item.paymentCategoryItemName === "카드")) {
            $('#cancellationPayModal .modal-body .subP').append('<br>결제에 사용된 카드를 준비해주세요.</p>');
        }
        // 라벨 클릭 시 체크박스 상태 변경 이벤트 추가
        $('#cancellationPayModal .chk_box').on('click', function(e) {
            if (e.target.tagName !== 'INPUT') {
                const checkbox = $(this).find('input[type="checkbox"]');
                checkbox.prop('checked', !checkbox.prop('checked'));
            }
        });
    },
    save: async function(){
        let userId;
        let userName;

        //해당 모달이 홈->수납 or 수납내역 -> 상세 인지 체크해서 고객정보 조회
        if (typeof reservePaymentInsertModal !== 'undefined'
            && reservePaymentInsertModal
            && reservePaymentInsertModal.reqParam ) {
            userId = reservePaymentInsertModal.reqParam.muUserId;
            userName = $('#reservePaymentInsertModal .modalUserName').text();
        } else if(typeof muUserId !== 'undefined' && muUserId ){
            userId = muUserId;
            userName = paymentDetailModal.reqParam.userName;
        } else if (typeof paymentDetailModal !== 'undefined'
            && paymentDetailModal.reqParam.muUserId) {
            userId = paymentDetailModal.reqParam.muUserId
            userName = paymentDetailModal.reqParam.userName;
        } else {
            modalEvent.danger("오류", "고객 정보가 없습니다");
            return;
        }

        let paymentDataArray = [];

        const checkboxes = $('#cancellationPayModal .payment-checkbox');
        let cancelTitle = checkboxes.eq(0).siblings("label").text().trim();

        modalEvent.success("", cancelTitle+"\n결제취소를 진행합니다.", function(){
            cancellationPayModal.save2(checkboxes, 0, checkboxes.length-1, paymentDataArray, userId, userName);
        });
    },
    save2:async function(checkboxes, index, maxIndex, paymentDataArray, userId, userName){

        completeFlag = (index === maxIndex);
        let paymentData = JSON.parse(decodeURIComponent(checkboxes.eq(index).data('value')));
        let paymentApprovalId = paymentData.paymentApprovalId;
        let muPaymentId = paymentData.muPaymentId;
        let paymentCategoryId = checkboxes.eq(index).attr('id').split("_")[1];

        let arr_sub = {};

        if (paymentApprovalId) {

            let S01 = paymentCategoryId === 'M' ? 'B2' : 'D4';
            // 단말기로 데이터 전송
            let posRequestParam = {
                S01: S01, 	                                      // 전문 구분코드 2자리
                S04: paymentData.cardInstallmentsCode,            //할부/현금 영수증용도 2자리
                S05: paymentData.paymentApprovalDate.slice(2,8),  // 승인일시
                S06: paymentApprovalId,                           // 승인번호
                S07: String(paymentData.totalAmount),		      // 금액 8자리
                S08: '00000000',		                          // 봉사료 8자리
                S09: String(paymentData.vat),		              // 부가세 8자리
            };
            let userData = {muUserId:userId,userName:userName};
            // 단말기 요청 식별자 저장
            if(terminalLinkage) {
                arr_sub.muPaymentRequestHistoryId = fn_saveRequestParam(posRequestParam, userData);
                try {
                    let paymentResponseData = await sendData(createDataString(posRequestParam));
                    if ('0000' !== paymentResponseData.responseCode) {
                        modalEvent.warning("결제 오류", paymentResponseData.msg);
                        return false;
                    }
                    //단말기 응답 식별자 저장
                    arr_sub.muPaymentResponseHistoryId = fn_saveResponseData(arr_sub.muPaymentRequestHistoryId, paymentResponseData);
                    arr_sub.paymentApprovalId = paymentResponseData.approvalNo;
                } catch (error) {
                    console.error('Error in sendData:', error);
                    return;
                }
            }
        }

        arr_sub.muPaymentId = muPaymentId;
        paymentDataArray.push(arr_sub);


        if(maxIndex == index){

            let formData = new FormData();
            formData.append("menuClass", menuClass);
            formData.append("muUserId", userId);
            formData.append("paymentDataArray",JSON.stringify(paymentDataArray));

            $.ajax({
                url: encodeURI('/webpayment/paymentCancellationPay.do'),
                data: formData,
                dataType: "json",
                processData: false,
                contentType: false,
                type: 'POST',
                async: true,
                success: function(data) {
                    if('0' == data.msgCode) {

                        modalEvent.success("", data.msgDesc, function(){
                            if (cancellationPayModal.callback) {
                                cancellationPayModal.callback(cancellationPayModal.reqParam);
                            }
                            cancellationPayModal.close();
                        });

                    } else {
                        modalEvent.danger("등록 오류", data.msgDesc);
                    }
                },
                error : function(xhr, status, error) {
                    modalEvent.danger("등록 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
                },
                beforeSend:function(){
                    // 로딩열기
                    $(".loading-image-layer").show();
                },
                complete:function(){
                    // 로딩닫기
                    $(".loading-image-layer").hide();
                }
            });
        }else{
            index++;
            let cancelTitle = checkboxes.eq(index).siblings("label").text().trim();
            modalEvent.success("", cancelTitle+"\n결제취소를 진행합니다.", function(){
                cancellationPayModal.save2(checkboxes, index, maxIndex, paymentDataArray, userId, userName);
            });
        }
    },
    complete:function(){
        if( cancellationPayModal.callback )  {
            cancellationPayModal.callback(cancellationPayModal.reqParam);
        }
        cancellationPayModal.close();
    },
    /*
     * 팝업
     * callback : 콜백함수, reqParam: 팝업파라미터
     */
    popup:function(callback, reqParam) {
        let balance = reqParam.paymentDetailData.reduce((sum, item) => sum + item.totalAmount, 0);

        if(0===balance){
            modalEvent.warning('오류','이미 결제 취소된 수납 내역입니다.');
            return;
        }

        if(reqParam.paymentDetailData[0].status==='환불'){
            modalEvent.warning('오류','이미 환불처리 된 수납 내역입니다.');
            return;
        }

        if(reqParam.paymentDetailData[0].status==='미수'){
            modalEvent.warning('오류','미수처리 된 수납 내역입니다.');
            return;
        }

        // 초기화 후 열기
        cancellationPayModal.init();

        //콜백함수 지정.
        cancellationPayModal.callback = callback;
        cancellationPayModal.reqParam = reqParam;
        cancellationPayModal.dataList = null;

        cancellationPayModal.search();


        setTimeout(function(){
            $('#cancellationPayModal').modal({keyboard:false, backdrop:'static'});
        }, 200);
    },
    /*
     * 팝업 닫기
     */
    close:function() {
        $('#cancellationPayModal').modal('hide');

		setTimeout(function(){
			$('#cancellationPayModal').remove();
		},500);
    },
    HtmlTemplate : `
	<div class="modal payment_cancel_modal fade" id="cancellationPayModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
			<div class="modal-dialog">
			    <div class="modal-content">
					<div class="modal-header">
						<p>결제취소 금액</p>
						<p id="totalCancelAmount">-원</p>
					</div>
					<div class="modal-body">
						<ul>
							<li class="first">
								<p class="title">고객명 :</p>
								<p id="userName">-</p>
							</li>
							<li>
								<p class="title">진료일 :</p>
								<p id="reserveDate">-</p>
							</li>
							<li>
								<p class="title">진료/시술항목 :</p>
								<p id="treatmentProcedureName">-</p>
							</li>
							<li>
								<p class="title">취소금액 :</p>
								<p id="cancelAmount">-원</p>
							</li>
							<li>
								<p class="title">결제수단 :</p>
								<p id="paymentItem">-</p>
							</li>
						</ul>
						<p class="subP">위 내용으로 결제취소를 진행하시겠습니까?
					</div>
					<div class="modal-footer">
						<div class="button_box">
							<button class="cancel_btn btnCancle">취소</button>
							<button class="refund_btn btnSave">결제취소</button>
						</div>
					</div>							
				</div>
			</div>
		</div>
    `
};
