
/* ##############################################################
	설  명 : [Modal]수납상세 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/

//데이터 갱신 필요여부
let reloadYn=false;

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

        $('#paymentDetailModal .payment_cancel_btn').on("click", function () {
            cancellationModal.popup(function (obj) {
                paymentDetailModal.search();
                reloadYn=true;
            }, paymentInsertData);
        });
        $('#paymentDetailModal .refund_btn').on("click", function () {
            refundModal.popup(function (obj) {
                paymentDetailModal.search();
                reloadYn=true;
            }, paymentInsertData);
        });
    },
    /* 데이터 선택 */
    setSelect:function(param) {
        let checkedData = param;
        if(dataList==null||checkedData==undefined){
            return ;
        }

        if( paymentDetailModal.callback )  {
            paymentDetailModal.callback(checkedData);
        }
        paymentDetailModal.close();
    },
    // 상세 조회
    search:function() {

        let paymentNumber  = paymentDetailModal.reqParam.paymentNumber;
        let muUserId  = paymentDetailModal.reqParam.muUserId;

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

        $.ajax({
            url: encodeURI('/webpayment/selectListPaymentUser.do'),
            data: formData,
            dataType: "json",
            processData: false,
            contentType: false,
            type: 'POST',
            async: true,
            success: function(data){
                if('0'==data.msgCode) {
                    if (data.rows.length > 0) {
                        let paymentDetailData = data.paymentDetail.map(row => ({
                            amount: row['amount'],
                            vat: row['vat'],
                            totalAmount: row['totalAmount'],
                            paymentCategoryItemId: row['paymentCategoryItemId'],
                            paymentCategoryItemName: row['paymentCategoryItemNm'],
                            paymentCardInfo: row['paymentCardInfo'],
                            cardInstallments: row['cardInstallments'],
                            cardInstallmentsCode: row['cardInstallmentsCode'],
                            paymentNumber: row['paymentNumber'],
                            paymentApprovalId: row['paymentApprovalId'],
							paymentApprovalDate: row['paymentApprovalDate'],
							muPaymentId: row['muPaymentId'],
                            status: row['status'],
                            membershipPrice: row['membershipPrice'],
							cardInfo: row['cardInfo']
                        }));
                        let procedureData = data.procedureList.map(row => ({
                            muReserveId: row['muReserveId'],
                            treatmentProcedureName: row['treatmentProcedureName'],
                            treatmentName: row['treatmentName'],
                            muTreatmentId: row['muTreatmentId'],
                            muTreatmentProcedureId: row['muTreatmentProcedureId'],
                            reserveMemberId: row['reserveMemberId'],
                            totalAmount: row['totalAmount'],
                            amount: row['amount'],
                            vat: row['vat'],
                            paymentNumber: row['paymentNumber']
                        }));
                        let paymentAmount = data.rows.reduce((sum, item) => sum + item.paymentAmount, 0);
                        let userName = paymentDetailModal.reqParam.userName
                        let procedureName = data.procedureList[0].treatmentName + '-' + data.procedureList[0].treatmentProcedureName + (data.procedureList.length - 1 > 0 ? (' 외 ' + (data.procedureList.length - 1) + '건') : '');
                        paymentInsertData.reserveDate = paymentDetailModal.reqParam.reserveDate;
                        paymentInsertData.paymentAmount = paymentAmount;
                        paymentInsertData.userName = userName;
                        paymentInsertData.procedureName = procedureName;
                        paymentInsertData.paymentDetailData = paymentDetailData;
                        paymentInsertData.procedureData = procedureData;
                        let totalPayment = 0;
                        const tbody = document.querySelector('#paymentDetailModal tbody');
                        tbody.innerHTML = '';

                        if (0 < data.procedureList.length) {
                            data.procedureList.forEach(item => {
                                // 새로운 행 생성
                                const row = document.createElement('tr');

                                // 각 데이터를 행에 추가
                                const writeDateCell = document.createElement('td');
                                writeDateCell.textContent = item.writeDate;
                                row.appendChild(writeDateCell);

                                const treatmentProcedureNmCell = document.createElement('td');
                                treatmentProcedureNmCell.textContent = item.treatmentName + '-' + item.treatmentProcedureName;
                                row.appendChild(treatmentProcedureNmCell);

                                const amountCell = document.createElement('td');
                                const vatCell = document.createElement('td');
                                let amount = item.totalAmount
                                let vat = 0;
                                if (item.vat && 0 < item.vat) {
                                    amount = Math.round(item.totalAmount / 1.1)
                                    vat = item.totalAmount - amount
                                }

                                amountCell.textContent = amount.toLocaleString()
                                vatCell.textContent = vat.toLocaleString(); // 숫자 포맷팅
                                row.appendChild(amountCell);

                                row.appendChild(vatCell);
                                // tbody에 행 추가
                                tbody.appendChild(row);
                                totalPayment += amount + vat;
                            });
                        }
                        let listHTML2 = '';
                        if (data.paymentDetail.length > 0) {
                            for (let i = 0; i < data.paymentDetail.length; i++) {
                                let detail = data.paymentDetail[i];
                                let {
                                    writeTime,
                                    paymentApprovalId = '-',
                                    amount,
                                    vat,
                                    discountPrice,
                                    membershipPrice,
                                    totalAmount,
                                    paymentCardInfo,
                                    paymentCategoryItemNm,
                                    cardInstallments = '-',
                                    status,
                                    refundAccount,
                                    refundEtc: rowRefundEtc
                                } = detail;
                                // refundEtc += rowRefundEtc||'';
                                // if (i < data.rows.length - 1 && rowRefundEtc) {
                                //     refundEtc += '\n';
                                // }
                                listHTML2 += `
                                <div class="detail_box">
                                    <ul>
                                        <li class="first">
                                            <label>결제총액</label>
                                            <p>${paymentCategoryItemNm=='멤버십'?0:totalAmount.toLocaleString()}원</p>
                                        </li>
                                        <li>
                                            <label>공급가</label>
                                            <p>${amount && paymentCategoryItemNm!='멤버십'? (amount.toLocaleString()) : 0}원</p>
                                        </li>
                                        <li>
                                            <label>부가세</label>
                                            <p>${vat && paymentCategoryItemNm!='멤버십'? (vat.toLocaleString()) : 0}원</p>
                                        </li>
                                        <li>
                                            <label>멤버십</label>
                                            <p>${membershipPrice ? (membershipPrice.toLocaleString() + '원') : '-'}</p>
                                        </li>
                                        <li>
                                            <label>할인</label>
                                            <p>${discountPrice ? (discountPrice.toLocaleString() + '원') : '-'}</p>
                                        </li>
                                        <li>
                                            <label>결제시간</label>
                                            <p>${writeTime}</p>
                                        </li>
                                        <li>
                                            <label>결제수단</label>
                                            <p>${status === '환불' ? refundAccount || paymentCategoryItemNm : paymentCardInfo || paymentCategoryItemNm}</p>
                                        </li>
                                        <li>
                                            <label>결제구분</label>
                                            <p>${cardInstallments}</p>
                                        </li>
                                        <li>
                                            <label>승인번호</label>
                                            <p>${paymentApprovalId}</p>
                                        </li>
                                        <li>
                                            <label>승인상태</label>
                                            <p>${status}</p>
                                        </li>
                                    </ul>
                                </div>`;
                            }
                        }
                        $('#paymentDetailModal .detail_box').remove();
                        $('#paymentDetailModal .modal-body').prepend(listHTML2);
                        $('#paymentDetailModal #totalPayment').text(totalPayment.toLocaleString());
                        $('#paymentDetailModal .textarea_box textarea').val(data.rows[0].etc);
                        let status = data.rows[0].status1
                        if(status==='부분결제'||status==='미수'){
                            let membership = Math.abs(data.rows[0].membershipPrice)*2;
                            let paymentAmount =data.rows[0].paymentAmount;
                            let totalAmount =data.rows[0].totalAmount;
                            $('#paymentDetailModal #nonPayment_detail').text((totalAmount-membership-paymentAmount).toLocaleString());
                        }
                    }
                }
                else{
                    modalEvent.danger("조회 오류", data.msgDesc);
                }
            },
            error : function(xhr, status, error) {
                modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            },
            beforeSend:function(){
                // 로딩열기
            },
            complete:function(){

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

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

        paymentDetailModal.search();

        setTimeout(function(){
            $('#paymentDetailModal').modal('show')
        }, 200);
    },
    /*
     * 팝업 닫기
     */
    close:function() {
        $('#paymentDetailModal').modal('hide');
        if(reloadYn){
            if( paymentDetailModal.callback )  {
                paymentDetailModal.callback();
            }
        }

        setTimeout(function(){
            $('#paymentDetailModal').remove();
        },500);
    },
    HtmlTemplate : `
    <div class="modal payment_detail_modal fade" id="paymentDetailModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <p class="title">결제</p>
                    <div class="button_box">
                        <button class="payment_cancel_btn" style="transition: all 0.2s ease-in-out 0s;">결제취소</button>
                        <button class="refund_btn" style="transition: all 0.2s ease-in-out 0s;">환불</button>
                    </div>
                </div>
    
                <div class="modal-body">
                    <div class="detail_box">
                        <ul>
                            <li>
                                <label>수납방법</label>
                                <p class="pbold">신용카드</p>
                            </li>
                            <li>
                                <label>결제 총액</label>
                                <p class="pbold"><span>3,330,000</span>원</p>
                            </li>
                            <li>
                                <label>기본수납 금액</label>
                                <p>3,000,000</p>
                            </li>
                            <li>
                                <label>수납 추가 금액</label>
                                <p>330,000</p>
                            </li>
                            <li>
                                <label>할부기간</label>
                                <p>일시불</p>
                            </li>
                            <li>
                                <label>카드번호</label>
                                <p>000-0000-000</p>
                            </li>
                            <li>
                                <label>승인번호</label>
                                <p>00000000</p>
                            </li>
                            <li>
                                <label>단말기번호</label>
                                <p>00000000</p>
                            </li>
                            <li>
                                <label>카드종류</label>
                                <p>BC카드</p>
                            </li>
                        </ul>
                    </div>
    
                    <div class="table_box">
                        <p class="title">수납 내용</p>
                        <table>
                            <thead>
                            <tr>
                                <th>진료일시</th>
                                <th>진료유형</th>
                                <th>금액</th>
                                <th>vat</th>
                            </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
    
                    <ul>
                        <li class="textarea_box">
                            <label>수납메모</label>
                            <textarea readonly></textarea>
                        </li>
                        <li>
                            <label>총 수납금액</label>
                            <p class="pbold" id="totalPayment"></p>
                        </li>
                        <li>
                            <label>미수금</label>
                            <p id="nonPayment_detail">0</p>
                        </li>
                    </ul>
                </div>
                
                
                <div class="modal-footer">
                    <div class="btn_box">
                        <button type="button" class="cancel_btn btnCancle">확인</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    `
};
