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

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

    },
    setRowData:function(state) {
        let tableHtml=''
        tableHtml += '<tbody>';
        paymentMembershipModal.reqParam.rowData.forEach(row => {
            let total = parseInt((row["8"]==='-'?row[7]:row[8]).replace(/,/g, ''), 10);
            let amount = row[6]==="0"?total:Math.round(total/1.1);
            let vat = total-amount;
            tableHtml += '<tr>';
            // 필요한 열만 표에 추가 (5, 6, 7번째 열)
            tableHtml += '<td data-id="'+row["0"]+'"><p>' + row["3"].toLocaleString() + '</p></td>'; // 3번째 열
            tableHtml += '<td><p>' + (row["10"]||amount).toLocaleString() + '</p></td>'; // 5번째 열
            tableHtml += '<td><p>' + (row["11"]||vat).toLocaleString()+ '</p></td>'; // 6번째 열
            tableHtml += '<td><p>' + (row["12"]||total).toLocaleString() + '</p></td>'; // 7번째 열
            tableHtml +=`<td>
                            <div class="input_box">
                                <input name="discountAmount" type="text" onchange="fn_calculateMembership()" placeholder="멤버십 사용 금액 입력"/>
                            </div>
                        </td>`
            tableHtml += '<td></td>'; // 7번째 열
            tableHtml += '</tr>';
        });

        tableHtml += '</tbody>';
        $('#paymentMembershipModal .table_box table').append(tableHtml);
    },
    // 미 수납건 조회
    search:function(state) {
        let muUserId               = paymentMembershipModal.reqParam.muUserId;

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

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

        $.ajax({
            url: encodeURI('/webmembership/selectMembershipBalance.do'),
            data: formData,
            dataType: "json",
            processData: false,
            contentType: false,
            type: 'POST',
            async: true,
            success: function(data){
                if('0'==data.msgCode){
                    let membershipBalance = data.rows[0].membershipBalance;
                    $('#paymentMembershipModal .modal-header span').text(membershipBalance.toLocaleString()+'원')
                }
                else{
                    modalEvent.danger("조회 오류", data.msgDesc);
                }
            },
            error : function(xhr, status, error) {
                modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            },
            beforeSend:function(){

            },
            complete:function(){

            }
        });
    },
    save:function(){
        let tableData = [];
        let isMembershipZero = false;
        $('#paymentMembershipModal tbody tr').each(function() {
            let $row = $(this);

            const id = $row.find('td:nth-child(1)').data('id');
            const isVat = parseFloat($row.find('td:nth-child(3)').text().replace(/,/g, ''));
            const itemText = $row.find('td:nth-child(1)').text().trim();
            const amountText = $row.find('td:nth-child(6)').text().replace(/,/g, '');
            const totalAmountText = $row.find('td:nth-child(4)').text().replace(/,/g, '');
            const discountAmountText = $row.find('input[name="discountAmount"]').val().replace(/,/g, '') || '0';

            const rawAmount = isVat!==0?parseFloat(amountText) / 1.1:parseFloat(amountText) || 0;
            const amount = Math.round(rawAmount);
            const vat = isVat!==0?Math.round(parseFloat(amountText) - rawAmount):0 || 0;
            const totalAmount = parseFloat(totalAmountText) || 0;
            const discountAmount = parseFloat(discountAmountText) || 0;
            if (discountAmount === 0) {
                isMembershipZero=true;
                return;
            }
            const finalAmount = parseFloat(amountText) || 0;

            let rowData = {
                id:id,
                item: itemText,
                amount: amount,
                vat: vat,
                totalAmount: totalAmount,
                discountAmount: discountAmount,
                finalAmount: finalAmount
            };

            tableData.push(rowData);
        });
        tableData.membershipBalance=parseFloat($('#paymentMembershipModal .modal-header span').text().replace(/,/g, '')) || 0;
        let totalDiscountAmount = tableData.reduce((sum, item) => sum + item.discountAmount, 0);
        tableData.finalMembershipBalance = tableData.membershipBalance-totalDiscountAmount;
        if(0>tableData.finalMembershipBalance){
            modalEvent.warning("등록", "멤버십 잔여금액이 부족합니다.");
            return;
        }
        // if(isMembershipZero){
        //     modalEvent.warning("등록", "멤버십 사용금액이 없습니다.");
        //     return;
        // }else{
            membershipPayCheckModal.popup(function (obj) {
                if( paymentMembershipModal.callback )  {
                    paymentMembershipModal.callback(tableData);
                }
                paymentMembershipModal.close();
            }, tableData);
        // }

    },
    /*
     * 팝업
     * callback : 콜백함수, reqParam: 팝업파라미터
     */
    popup:function(callback, reqParam) {
        //콜백함수 지정.
        paymentMembershipModal.callback = callback;
        paymentMembershipModal.reqParam = reqParam;
        paymentMembershipModal.dataList = null;

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

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

        // paymentMembershipModal.search();

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

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

		setTimeout(function(){
			$('#paymentMembershipModal').remove();
		},500);
    },
    HtmlTemplate : `
	<div id="paymentMembershipModal" class="modal membership_modal fade tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
		<div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <div>
                        <p>멤버십 차감 진료/시술 선택</p>
                        <p>멤버십 잔여금액 <span>500,000원</span></p>
                    </div>
                </div>
                <div class="modal-body">
                    <div class="table_box">
                        <table>
                            <thead>
                                <tr>
                                    <th>진료내용</th>
                                    <th>공급가</th>
                                    <th>VAT</th>
                                    <th>결제총액</th>
                                    <th>멤버십 사용 금액</th>
                                    <th>멤버십 차감 후 결제금액</th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <div class="button_box">
                        <button class="cancel_btn btnCancle">취소</button>
                        <button class="application_btn btnSave" data-toggle="modal" data-target=".membership_pay_modal" style="transition: all 0.2s ease-in-out 0s;">적용</button>
                    </div>
                </div>							
            </div>
        </div>
    </div>
    `
};

function fn_calculateMembership() {
    $('#paymentMembershipModal tr').each(function() {
        let $row = $(this);
        let discountAmount = parseFloat($row.find('input[name="discountAmount"]').val()?.replace(/[^\d]/g, '')) || 0;
        let totalAmount = parseFloat($row.find('td:nth-child(4)').text().replace(/,/g, '')) || 0;

        if (discountAmount > totalAmount) {
            discountAmount = totalAmount; // 할인금액이 결제총액보다 크면 결제총액으로 설정
        }
        $row.find('input[name="discountAmount"]').val(discountAmount.toLocaleString());

        let discountedTotal = totalAmount - discountAmount;

        if (discountedTotal < 0) {
            discountedTotal = 0; // 할인 후 금액이 0보다 작으면 0으로 설정
        }

        // 결과를 '할인 후 결제금액' 열에 표시
        $row.find('td:last-child').text(discountedTotal.toLocaleString());
    });
}