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

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

        $('#monetizationModal .btnPayment').on("click", function () {
            monetizationModal.save();
        });

        const buttons = document.querySelectorAll('#monetizationModal .cashReceiptsType button');
        buttons.forEach(button => {
            button.addEventListener('click', function () {
                if (this.classList.contains('active')) {
                    this.classList.remove('active');
                } else {
                    buttons.forEach(btn => btn.classList.remove('active'));
                    this.classList.add('active');
                }
            });
        });

    },
    // 미 수납건 조회
    search:function(state) {
        let data = monetizationModal.reqParam;
        let totalAmount = data.splitAmount||data.reduce((sum, item) => sum + item.totalAmount, 0);

        $('#monetizationModal .modal-header p').eq(1).text(totalAmount.toLocaleString()+'원');
        $('#monetizationModal .afterShow p').eq(0).text(totalAmount.toLocaleString()+'원');
    },
    save:async function () {
        //현금영수증 입력값
        let cashReceiptsType = $('#monetizationModal .cashReceiptsType .active').data('code');
        let muUserId = reservePaymentInsertModal.reqParam.muUserId;
        let muPaymentRequestHistoryId = '';
        let muPaymentResponseHistoryId='';
        let paymentApprovalId='';

        let reverseData = [];
        let detailData = [];
        let paymentData = [];
        let paymentResponseData = {};
        let membershipBalance = monetizationModal.reqParam[0].membershipBalance;
        let totalAmount = monetizationModal.reqParam.reduce((sum, item) => sum + item.totalAmount, 0);
        let itemAmount = monetizationModal.reqParam.reduce((sum, item) => sum + item.amount, 0);
        let splitAmount = monetizationModal.reqParam.splitAmount
        let membershipAmount = monetizationModal.reqParam.reduce((sum, item) => sum + item.membershipAmount, 0);
        let calculatePartialPayment = fn_calculatePartialPayment(totalAmount, itemAmount, splitAmount || totalAmount);
        let amount = calculatePartialPayment.partialSupplyAmount;
        let vat = calculatePartialPayment.partialVatAmount;

        //현금영수증 입력 시 로직
        if (cashReceiptsType) {
            //단말기로 데이터 전송
            let posRequestParam = {
                S01: 'B1', 	                // 전문 구분코드 2자리
                S04: cashReceiptsType,      // 현금영수증 용도
                S07: String(amount+vat),	// 금액 8자리
                S08: '00000000',		    // 봉사료 8자리
                S09: String(vat),		    // 부가세 8자리
                S10: '',		            // POS거래번호 8자리
            }
            let userName = $('#reservePaymentInsertModal .modalUserName').text();
            let userData = {muUserId:muUserId,userName:userName};
            if(terminalLinkage){
                completeFlag = true;
                muPaymentRequestHistoryId = fn_saveRequestParam(posRequestParam,userData);
                try {
                    paymentResponseData = await sendData(createDataString(posRequestParam));
                    if ('0000' !== paymentResponseData.responseCode) {
                        modalEvent.warning("결제 오류", paymentResponseData.msg);
                        return;
                    }
                    // 응답 데이터 저장
                    muPaymentResponseHistoryId = fn_saveResponseData(muPaymentRequestHistoryId, paymentResponseData);
                } catch (error) {
                    console.error('Error in sendData:', error);
                    return;
                }
            }
        }

        let nonPayment = monetizationModal.reqParam.reduce((sum, item) => sum + item.nonPayment, 0);
        //분할결제금액이 있다면 분할 결제중:G 상태
        let status = splitAmount && (totalAmount !== splitAmount) ? 'G' : 'Y'
        let status2 = ''
        //미수금이 있고 결제금이 미수금과 같을때
        let amountStat = nonPayment > 0 ? 'NY' : 'Y'
        if ('G' === status) {
            status2 = 'Y'
        } else {
            status2 = amountStat
        }

        let paymentMoney = splitAmount || totalAmount
        let cardNumber='';
        let cardCompanyName='';
        let cardInstallments='';
        let cardInstallmentsCode='';

        if ('B1' === paymentResponseData.transactionType) {
            cardInstallmentsCode = paymentResponseData.paymentOptionCode;
            cardNumber = formatCashReceiptInfo(paymentResponseData.cardNumber);
            cardCompanyName = '현금(소득공제)'
            if ('00' === cardInstallmentsCode) {
                cardInstallments = '소비자 소득공제용';
            } else {
                cardInstallments = '사업자 지출증빙용';
            }
        }
        paymentApprovalId = paymentResponseData.approvalNo;

        monetizationModal.reqParam.forEach(row => {
            let detailAmount = 0;
            if (paymentMoney > 0) {
                paymentMoney -= row["totalAmount"]
                if (paymentMoney >= 0) {
                    detailAmount = row["totalAmount"]
                } else if (paymentMoney < 0) {
                    detailAmount = row["totalAmount"] + paymentMoney;
                }
            }

            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:row["originAmount"]||row["amount"],
                // vat:row["originVat"]||row["vat"],
                amount: 0,
                vat: 0,
                // totalAmount:row["nonPayment"]||row["originTotalAmount"]||row["totalAmount"],
                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);
        });

        let rowData3 = {
            paymentNumber: monetizationModal.reqParam.paymentNumber,
            muUserId: muUserId,
            paymentApprovalId: paymentApprovalId,
            paymentCategoryItemId: 'M',
            paymentCategoryItemName: '현금',
            paymentCardInfo: cardCompanyName+' '+cardNumber,
            cardInstallments: cardInstallments,
            cardInstallmentsCode: cardInstallmentsCode,
            amount: amount,
            vat: vat,
            paymentAmount: splitAmount || totalAmount,
            etc: $('#reservePaymentInsertModal #payment .textarea_box textarea').val(),
            status: status2,
            muPaymentId: monetizationModal.reqParam.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: monetizationModal.reqParam.paymentNumber,
                muUserId: 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: monetizationModal.reqParam.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) {
                    monetizationModal.reqParam.status = status;
                    $('.monetization_modal').find('.afterHide').hide();
                    $('.monetization_modal').find('.afterShow').show();
                } else {
                    modalEvent.danger("등록 오류", data.msgDesc);
                }
            },
            error: function (xhr, status, error) {
                modalEvent.danger("등록 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            },
            beforeSend: function () {
                // 로딩열기
                $(".loading-image-layer").show();
            },
            complete: function () {
                // 로딩닫기
                $(".loading-image-layer").hide();
            }
        });

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

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

        monetizationModal.search();


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

		setTimeout(function(){
			$('#monetizationModal').remove();
		},500);
    },
    HtmlTemplate : `
	<div class="modal monetization_modal fade" id="monetizationModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header afterHide">
						<div>
							<p>결제금액</p>
							<p>1,000,000원</p>
						</div>
					</div>
					<div class="modal-body">
						<div class="input_box afterHide">
							<label>현금영수증 신청</label>
							<div class="cashReceiptsType">
                                <button data-code="00">
                                    소비자 소득공제용
                                </button>
                                <button data-code="01">
                                    사업자 지출증빙용
                                </button>
                            </div>
						</div>
						<div class="afterShow">
							<img src="/image/web/check.svg" alt="확인"/>
							<p class="first">1,000,000원</p>
							<p class="last">결제완료</p>
						</div>
					</div>
					<div class="modal-footer">
						<div class="button_box">
							<button class="cancel_btn afterHide btnCancle">취소</button>
							<button class="pick_payment_btn monetization_payment_btn afterHide btnPayment">결제</button>
							<button class="check_btn afterShow btnSave">확인</button>
						</div>
					</div>							
				</div>
			</div>
		</div>
    `
};
