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

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

    },
    setRowData:function(state) {
        let tableHtml=''
            tableHtml += '<tbody>';
        discountInsertModal.reqParam.forEach(row => {
            //미수금액이 '-'라면 총액으로 계산.
            let total = parseInt((row["8"]==='-'?row[7]:row[8]).replace(/,/g, ''), 10);
            //vat가 0이라면 공급가 == 총액, 아니라면 /1.1로 계산
            let amount = row[6] === "0"? total:Math.round(total/1.1);
            //총액 - 공급가로 vat 계산
            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_calculate()" placeholder="할인금액 입력"/>
                            </div>
                        </td>`
            tableHtml += '<td></td>'; // 7번째 열
            tableHtml += '</tr>';
        });

        tableHtml += '</tbody>';
        $('#discountInsertModal .table_box table').append(tableHtml);
    },
    save:function(){
        let tableData = [];
        let isDiscountZero = false;
        $('#discountInsertModal 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) {
                isDiscountZero=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);
        });
        // if(isDiscountZero){
        //     modalEvent.warning("등록", "할인금액이 없습니다.");
        // }else{
            discountPayCheckModal.popup(function (obj) {
                if( discountInsertModal.callback )  {
                    discountInsertModal.callback(tableData);
                }
                discountInsertModal.close();
            }, tableData);
        // }

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

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

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

		setTimeout(function(){
			$('#discountInsertModal').remove();
		},500);
    },
    HtmlTemplate : `
	<div id="discountInsertModal" class="modal discount_modal fade tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
				    <p>할인적용 진료/시술 선택</p>
                </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>
                        </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=".discount_pay_modal" style="transition: all 0.2s ease-in-out 0s;">적용</button>
                    </div>
                </div>							
            </div>
        </div>
    </div>
    `
};

function fn_calculate() {
    $('#discountInsertModal 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());
    });
}