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

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

    },
    // 미 수납건 조회
    search:function(state) {
        let data = membershipPartialModal.reqParam;
        let membershipAmount = data.reduce((sum, item) => sum + item.membershipAmount, 0);
        let discountAmount = data.reduce((sum, item) => sum + item.discountAmount, 0);
        let totalAmount = data.reduce((sum, item) => sum + (item.nonPayment||item.originTotalAmount), 0);
        let paymentBalance = data.reduce((sum, item) => sum + item.totalAmount, 0);
        let membershipBalance = data[0].membershipBalance;

        $('#membershipPartialModal #membershipAmount').text(membershipAmount.toLocaleString()+'원');
        $('#membershipPartialModal #totalPayment').text((totalAmount-discountAmount).toLocaleString()+'원');
        $('#membershipPartialModal #membershipAmount_detail').text('-'+membershipAmount.toLocaleString()+'원');
        $('#membershipPartialModal #membershipBalance').text(membershipBalance.toLocaleString()+'원');
        $('#membershipPartialModal #paymentBalance').text(paymentBalance.toLocaleString()+'원');
        $('#membershipPartialModal .modal-body .subP span').text(paymentBalance.toLocaleString()+'원');
    },
    save:function(){
        let reverseData = [];
        let detailData = [];
        let paymentData = [];

        let paymentNumber = membershipPartialModal.reqParam.paymentNumber;

        if(true != fn_emptyCheck(paymentNumber)){
            modalEvent.warning("등록", "결제번호가 없습니다.");
            return;
        }

        let membershipBalance = membershipPartialModal.reqParam[0].membershipBalance;
        let totalAmount = membershipPartialModal.reqParam.reduce((sum, item) => sum + ((item.nonPayment||item.originTotalAmount)-item.discountAmount), 0);
        let membershipAmount = membershipPartialModal.reqParam.reduce((sum, item) => sum + item.membershipAmount, 0);
        let calculatePartialPayment = fn_calculatePartialPayment2(totalAmount,membershipAmount);
        let amount = calculatePartialPayment.partialSupplyAmount;
        let vat = calculatePartialPayment.partialVatAmount;
        let nonPayment = membershipPartialModal.reqParam.reduce((sum, item) => sum + item.nonPayment, 0);
        //분할결제금액이 있다면 분할 결제중:G 상태
        let status2=''
        //미수금이 있고 결제금이 미수금과 같을때
        let amountStat = nonPayment>0?'NY':'Y'
        status2= totalAmount===membershipAmount?amountStat:'P'
        membershipPartialModal.reqParam.forEach(row => {
            let rowData={
                muReserveId:row["muReserveId"],
                status2:status2,
            }
            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:0,
                discountPrice:row["discountAmount"]||0,
                membershipPrice:parseInt('-'+(row["membershipAmount"]||0)),
            }
            reverseData.push(rowData);
            detailData.push(rowData2);
        });
        let rowData3 = {
            paymentNumber:paymentNumber,
            muUserId:reservePaymentInsertModal.reqParam.muUserId,
            paymentCategoryItemId: 'MM',
            paymentCategoryItemName:'멤버십',
            amount:parseInt('-'+amount,0),
            vat:parseInt('-'+vat,0),
            paymentAmount:parseInt('-'+membershipAmount,0),
            status:status2,
            etc:$('#reservePaymentInsertModal #payment .textarea_box textarea').val(),
            muPaymentId:membershipPartialModal.reqParam.muPaymentId,
            firstVisitYn:firstVisitYn
        }
        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(){
                        if( membershipPartialModal.callback )  {
                            membershipPartialModal.callback();
                        }
                        membershipPartialModal.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();
            }
        });
    },
    /*
     * 팝업
     * callback : 콜백함수, reqParam: 팝업파라미터
     */
    popup:function(callback, reqParam) {
        // 초기화 후 열기
        membershipPartialModal.init();

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

        // 진료 콤보데이타 설정
        // membershipPartialModal.setTreatmentCombo();

        membershipPartialModal.search();

        // fn_searchDatePicker("#membershipPartialModal #payment_detail input[name='modalStartDate']", "#membershipPartialModal #payment_detail input[name='modalEndDate']");

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

		setTimeout(function(){
			$('#membershipPartialModal').remove();
		},500);
    },
    HtmlTemplate : `
	<div class="modal membership_partial_modal fade" id="membershipPartialModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<div>
							<p>멤버십 결제금액</p>
							<p id="membershipAmount">500,000원</p>
						</div>
					</div>
					<div class="modal-body">
						<ul>
							<li>
								<p class="title">진료/시술 금액</p>
								<p class="last" id="totalPayment">1,000,000원</p>
							</li>
							<li>
								<p class="title">멤버십 결제금액</p>
								<p class="last red" id="membershipAmount_detail">-500,000원</p>
							</li>
							<li class="sub">
								<p class="title">└ 결제 후 멤버십 잔액</p>
								<p class="last" id="membershipBalance">0원</p>
							</li>
							<li class="remaining">
								<p class="title">결제잔여금액</p>
								<p class="last" id="paymentBalance">500,000원</p>
							</li>
						</ul>
						<p class="subP">결제 진행시<br/>잔여금액 <span>500,000원</span>은 미수 처리됩니다.</p>
					</div>
					<div class="modal-footer">
						<div class="button_box">
							<button class="cancel_btn btnCancle">취소</button>
							<button class="pick_payment_btn btnSave">결제</button>
						</div>
					</div>							
				</div>
			</div>
		</div>
    `
};
