
/* ##############################################################
	설  명 : [Modal]수납모달 - 환불 팝업
	작성일 : 2024. 06. 17.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2024. 06. 17.	NTsoft 	 최초 생성
*/

let refundModal = {
    callback : null,
    reqParam : null,
    dataList : null,
    /* 모달 초기화 작업 */
    init : function () {
        $('#refundModal').remove();
        $('body').append( this.HtmlTemplate);
        //그리드 이벤트
        this.setEvent();
    },
    /* 그리드 이벤트 설정 */
    setEvent:function() {
        $('#refundModal .btnCancle').on("click", function(){
            refundModal.close();
        });

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

        });
        $('#refundModal .monetization_btn').on("click", function () {
            let isActive = $('#refundModal .monetization_btn').hasClass('active');
            $('#refundModal .account_btn').removeClass('active').css('background','white');
            $('#refundModal .modal-body .input_box').css('display','none');
            if (!isActive) {
                $('#refundModal .monetization_btn').toggleClass('active', !isActive).css('background', isActive ? 'white' : 'orange');
            }
        });

        $('#refundModal .account_btn').on("click", function () {
            let isActive = $('#refundModal .account_btn').hasClass('active');
            $('#refundModal .monetization_btn').removeClass('active').css('background','white');
            if (!isActive) {
                $('#refundModal .account_btn').toggleClass('active', !isActive).css('background', isActive ? 'white' : 'red');
                $('#refundModal .modal-body .input_box').css('display','block');
            }else{
                $('#refundModal .modal-body .input_box').css('display','none');
            }
        });
    },
    save:function(){
        //환불금액
        let refundAmount = parseInt('-'+$('#refundModal .modal-header input').val());
        //환불수단
        let refundItem = $('#refundModal .button_box button.active').text();
        let refundEtc = $('#refundModal .modal-body .textarea_box textarea').val();
        let refundAccount = $('#refundModal .modal-body .input_box input').val();

        let paymentCategoryItemId = refundItem==='현금'?'M':'A';
        let reverseData = [];
        let detailData = [];
        let paymentData = [];
        let paymentNumber=''
        let paymentMoney = Math.abs(refundAmount);

        if($('#refundModal .button_box button.active').length===0){
            modalEvent.warning('오류','환불수단을 선택하세요.')
            return;
        }
        if(!parseInt('-'+$('#refundModal .modal-header input').val())){
            modalEvent.warning('오류','환불금액을 입력하세요.')
            return;
        }

        //결제상태(N:미결제, Y:결제완료, C:결제취소, G:결제중) (*추가)
        refundModal.reqParam.procedureData.forEach(row => {
            let detailAmount = 0;
            if(paymentMoney>0){
                //환불금액이 0보다 클때
                paymentMoney-=row["totalAmount"]
                if(paymentMoney>=0){
                    //첫번째 결제금액을 뺀 값이 0보다 크거나 같다면
                    detailAmount = row["totalAmount"]
                }else if(paymentMoney<0){
                    detailAmount= row["totalAmount"]+paymentMoney;
                }
            }
            paymentNumber = row['paymentNumber'];
            let rowData={
                muReserveId:row['muReserveId'],
                status2:'R',
            }
            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,
            }
            rowData2.amount = row['vat']>0? -(Math.round(detailAmount/1.1)):-detailAmount
            rowData2.vat = -detailAmount-rowData2.amount;
            reverseData.push(rowData);
            detailData.push(rowData2);
        });
        let userId;
        if (typeof reservePaymentInsertModal !== 'undefined' && reservePaymentInsertModal && reservePaymentInsertModal.reqParam) {
            userId = reservePaymentInsertModal.reqParam.muUserId;
        } else if(typeof muUserId !== 'undefined'&& muUserId){
            userId = muUserId;
        } else if(typeof paymentDetailModal !== 'undefined'&&paymentDetailModal.reqParam.muUserId){
            userId=paymentDetailModal.reqParam.muUserId
        } else {
           modalEvent.danger("오류", "고객 정보가 없습니다");
            return;
        }
        let rowData3 = {
            paymentNumber:paymentNumber,
            muUserId:userId,
            paymentCategoryItemId: paymentCategoryItemId,
            paymentCategoryItemName:refundItem,
            refundAmount:refundAmount,
            refundEtc:refundEtc,
            refundAccount:refundAccount,
            status:'R'
        }
        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));

        $.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){
                    if( refundModal.callback )  {
                        refundModal.callback(refundModal.reqParam);
                    }
                    refundModal.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) {
        // 초기화 후 열기
        refundModal.init();

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

        // refundModal.search();


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

		setTimeout(function(){
			$('#refundModal').remove();
		},500);
    },
    HtmlTemplate : `
	<div class="modal refund_modal fade" id="refundModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<div class="input_box">
							<label>환불금액</label>
							<input type="text" placeholder="환불금액을 입력해주세요.">
							<p>원</p>
						</div>
					</div>
					<div class="modal-body">
						<div class="button_box">
							<p>환불수단 선택</p>
							<button class="monetization_btn"><img class="b" src="/image/web/monetization.svg" alt="현금"><img class="w" src="/image/web/monetizationW.svg" alt="현금">현금</button>
							<button class="account_btn"><img class="b" src="/image/web/account.svg" alt="계좌이체"><img class="w" src="/image/web/accountW.svg" alt="계좌이체">계좌이체</button>
						</div>
						<div class="input_box">
							<input type="text" placeholder="홍길동, 신한은행, 110-222-15751547"/>
						</div>
						<div class="textarea_box">
							<p>환불 사유메모</p>
							<textarea></textarea>
						</div>
					</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>
    `
};
