
/* ##############################################################
	설  명 : [Modal]멤버십 충전 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/

let membershipItemList = [];
let membershipChargeInsertModal = {
    callback : null,
    reqParam : null,
    dataList : null,
    /* 모달 초기화 작업 */
    init : function () {
        membershipItemList = [];
        $('#membershipChargeInsertModal').remove();
        userData.phoneNumber=fn_setFormatPhone(userData.phoneNumber);
        $('body').append(this.HtmlTemplate());
        //그리드 이벤트
        this.setEvent();
    },
    /* 그리드 이벤트 설정 */
    setEvent:function() {
        // $('.select_box').off('click');
        //$(document).off('click');

        $('#membershipChargeInsertModal .select_box').on('click', function () {
            $(this).find('.select_option_list').toggle();
            $('.select_box').not(this).find('.select_option_list').hide();
        });

        // 옵션 선택 이벤트
        $('#membershipChargeInsertModal .select_box').on('click', 'li', function (e) {
            fn_OptionSelection($(this), e);
            membershipChargeInsertModal.dataList = membershipItemList.filter(item => item.muTreatmentProcedureId === $(this).attr('id'));
            let selectItem =membershipChargeInsertModal.dataList;
            let amount = parseInt(selectItem[0].procedurePrice.replace(/,/g, ''), 10);
            let vat = parseInt(selectItem[0].procedurePriceVat.replace(/,/g, ''), 10);
            let totalPrice = amount + vat;
            $('#membershipChargeInsertModal .modal-header p').eq(1).text(totalPrice.toLocaleString()+'원')
            $('#membershipChargeInsertModal .afterShow .first').text(totalPrice.toLocaleString()+'원')
            $(this).closest('.select_box').find('.label').text( $(this).text());
            $(this).closest('.select_box').find('input').val($(this).attr('id')??$(this).text());
            $(this).closest('.select_box').find('.option_list_item').removeClass('selected');
            $(this).addClass('selected');
            $(this).closest('.select_option_list').hide();

            e.stopPropagation();
        });

        $('#membershipChargeInsertModal .cancel_btn').on("click", function(){
            membershipChargeInsertModal.close();
        });

        $('#membershipChargeInsertModal .pick_payment_btn').on("click", function(){
            membershipChargeInsertModal.save();
        });
        $('#membershipChargeInsertModal .check_btn').on("click", function(){
            membershipChargeInsertModal.complete();
        });


        $('#membershipChargeInsertModal .button_box button').not('.afterHide').on("click", function () {
            fn_handleButtonClick($(this));
        });

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

    },
    /* 데이터 선택 */
    setSelect:function(selectNumber) {
        let checkedData = dataList[selectNumber];
        if(dataList==null||checkedData==undefined){
            return ;
        }

        if( membershipChargeInsertModal.callback )  {
            membershipChargeInsertModal.callback(checkedData);
        }
        membershipChargeInsertModal.close();
    },
    //저장
    save:async function () {
        let selectItemData = membershipChargeInsertModal.dataList;
        let detailData = [];
        let paymentData = [];
        let paymentCategoryItemName = $('#membershipChargeInsertModal .button_box button.on').text();
        let paymentCategoryItemId = $('#membershipChargeInsertModal .button_box button.on').attr('id');
        let cashReceiptsType = $('#membershipChargeInsertModal .cashReceiptsType .active').data('code');
        //단말기 요청 식별자
        let muPaymentRequestHistoryId = '';
        //단말기 응답 식별자
        let muPaymentResponseHistoryId='';
        //카드번호
        let cardNumber='';
        //카드사명
        let cardCompanyName='';
        //할부정보 or 현금영수증 정보
        let cardInstallments='';
        //할부코드 or 현금영수증 코드
        let cardInstallmentsCode='';
        //단말기 결제 승인코드
        let muApprovalId = '';

        if (!selectItemData || selectItemData.length === 0) {
            modalEvent.warning("등록", "멤버십 충전을 선택하세요.");
            return;
        }
        if (!fn_emptyCheck(paymentCategoryItemName)) {
            modalEvent.warning("등록", "결제수단을 선택하세요.");
            return;
        }

        //결제번호
        let paymentNumber = fn_getMembershipPaymentNumber();
        //멤버십 상품 공급가
        let itemAmount = parseInt(selectItemData[0].procedurePrice.replace(/,/g, ''), 10);
        //멤버십 상품 vat
        let itemVat = parseInt(selectItemData[0].procedurePriceVat.replace(/,/g, ''), 10);
        //멤버십 추가지급액
        let itemAdditionalAmount = parseInt(selectItemData[0].additionalAmount.replace(/,/g, ''), 10);
        //기존 멤버십 잔액
        let existingBalance = parseInt(userData.membershipBalance.replace(/,/g, ''), 10);
        //멤버십 상품 총액 (공급가 + vat)
        let totalAmount = itemAmount + itemVat;
        // 멤버십 충전금액
        let rechargeAmount = itemAmount + itemVat + itemAdditionalAmount;

        if(cashReceiptsType || 'C'===paymentCategoryItemId){
        //전문 타입
            let requestType = 'C'===paymentCategoryItemId?'D1':'B1';

            let posRequestParam = {
                S01: requestType, 	// 전문 구분코드 2자리
                S03: '',
                S04: cashReceiptsType,
                S07: String(totalAmount),		// 금액 8자리
                S08: '00000000',		// 봉사료 8자리
                S09: String(itemVat),		// 부가세 8자리
                S10: '',		// POS거래번호 8자리
            }
            // 단말기 요청 식별자 저장
            if(terminalLinkage){
                completeFlag = true;

                muPaymentRequestHistoryId = fn_saveRequestParam(posRequestParam,userData);

                try {
                    //단말기로 데이터 전송
                    const paymentResponseData = await sendData(createDataString(posRequestParam));
                    if ('0000' !== paymentResponseData.responseCode) {
                        modalEvent.warning("결제 오류", paymentResponseData.msg);
                        return false;
                    }
                    // 응답 데이터 저장
                    muPaymentResponseHistoryId = fn_saveResponseData(muPaymentRequestHistoryId, paymentResponseData);

                    if ('I1' === paymentResponseData.transactionType) {
                        cardNumber = formatCardNumber(paymentResponseData.cardNumber);
                        cardCompanyName = paymentResponseData.issuerName;
                        if (paymentResponseData.paymentOptionCode) {
                            cardInstallments = paymentResponseData.paymentOptionCode + '개월';
                            cardInstallmentsCode = paymentResponseData.paymentOptionCode;
                        } else {
                            cardInstallments = '일시불';
                        }
                    }else if ('B1' === paymentResponseData.transactionType) {
                        cardInstallmentsCode = paymentResponseData.paymentOptionCode;
                        cardNumber = formatCashReceiptInfo(paymentResponseData.cardNumber);
                        cardCompanyName = '현금(소득공제)'
                        if ('00' === paymentResponseData.paymentOptionCode) {
                            cardInstallments = '소비자 소득공제용';
                        } else {
                            cardInstallments = '사업자 지출증빙용';
                        }
                    }
                    muApprovalId = paymentResponseData.approvalNo;
                } catch (error) {
                    console.error('Error in sendData:', error);
                    return;
                }
            }
        }

        selectItemData.forEach(row => {
            let rowData2 = {
                muTreatmentId: row["muTreatmentId"],
                muTreatmentProcedureId: row["muTreatmentProcedureId"],
                treatmentName: '멤버십',
                treatmentProcedureName: row["procedureName"],
                reserveMemberId: loginMemberId,
                amount: itemAmount,
                vat: itemVat,
                totalAmount: totalAmount,
            }
            detailData.push(rowData2);
        })
        let rowData3 = {
            paymentNumber: paymentNumber,
            muUserId: muUserId,
            paymentApprovalId: muApprovalId,
            paymentCategoryItemId: paymentCategoryItemId,
            paymentCategoryItemName: paymentCategoryItemName,
            paymentCardInfo: cardCompanyName+' '+cardNumber,
		    cardInstallments: cardInstallments,
		    cardInstallmentsCode: cardInstallmentsCode,
            amount: itemAmount,
            vat: itemVat,
            paymentAmount: totalAmount,
            status: 'Y',
            muPaymentRequestHistoryId: muPaymentRequestHistoryId,
		    muPaymentResponseHistoryId: muPaymentResponseHistoryId
        }
        paymentData.push(rowData3);

        let membershipBalance = existingBalance + rechargeAmount;

        let formData = new FormData();
        formData.append("menuClass", menuClass);
        formData.append("detailData", JSON.stringify(detailData));
        formData.append("paymentData", JSON.stringify(paymentData));
        formData.append("membershipYn", userData.membershipYn);
        formData.append("muUserId", userData.muUserId);
        formData.append("membershipBalance", membershipBalance);
        formData.append("rechargeAmount", rechargeAmount);

        $.ajax({
            url: encodeURI('/webmembership/insertMembership.do'),
            data: formData,
            dataType: "json",
            processData: false,
            contentType: false,
            type: 'POST',
            async: true,
            success: function (data) {
                if ('0' == data.msgCode) {
                    $('.charge_modal .afterHide').hide();
                    $('.charge_modal .afterShow').show();
                } else {
                    modalEvent.danger("등록 오류", data.msgDesc);
                }
            },
            error: function (xhr, status, error) {
                modalEvent.danger("등록 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            },
            beforeSend: function () {
            },
            complete: function () {
            }
        });

    },
    complete:function (){
        if( membershipChargeInsertModal.callback )  {
            membershipChargeInsertModal.callback();
        }
        membershipChargeInsertModal.close();
    },
    search:function(){
        let formData = new FormData();
        formData.append("menuClass", menuClass);
        $.ajax({
            url: encodeURI('/webtreatment/selectMembershipOption.do'),
            data: formData,
            dataType: "json",
            processData: false,
            contentType: false,
            type: 'POST',
            async: true,
            success: function(data){
                if('0'==data.msgCode){
                    if(0<data.rows.length){
                        let membershipIds = data.rows[0].muTreatmentId;
                        fn_searchMembershipItem(membershipIds);
                    }
                }
                else{
                    modalEvent.danger("등록 오류", data.msgDesc);
                }
            },
            error : function(xhr, status, error) {
                modalEvent.danger("등록 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            },
            beforeSend:function(){

            },
            complete:function(){

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

        membershipChargeInsertModal.search();

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

		setTimeout(function(){
			$('#membershipChargeInsertModal').remove();
		},500);
    },
    HtmlTemplate :function (){
        return`
    <div class="modal charge_modal fade" id="membershipChargeInsertModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header afterHide">
                    <div>
                        <p>멤버십 충전금액</p>
                        <p>0원</p>
                    </div>
                </div>
                <div class="modal-body">
                    <div class="select_box_box afterHide">
                        <p>멤버십 충전선택</p>
                        <div class="select_box dropdown">
                            <button class="label" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">멤버십 상품을 선택하세요</button>
                            <input type="hidden" id="membershipItem">
                            <ul class="select_option_list dropdown-menu">
                                
                            </ul>
                        </div>
                    </div>
                    <div class="button_box afterHide">
                        <p>결제수단 선택</p>
                        <button class="card_btn" id="C"><img src="/image/web/card.svg" alt="카드"/>카드</button>
                        <button class="monetization_btn" id="M"><img src="/image/web/monetization.svg" alt="현금">현금</button>
                        <button class="account_btn" id="A"><img src="/image/web/account.svg" alt="계좌이체">계좌이체</button>
                    </div>
                    <div class="input_box afterHide">
                        <p>현금영수증 신청</p>
<!--                        <input type="text" placeholder="홍길동, 신한은행, 110-222-15751547"/>-->
                        <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 bottom">
                        <button class="cancel_btn afterHide">취소</button>
                        <button class="pick_payment_btn afterHide">결제</button>
                        <button class="check_btn afterShow">확인</button>
                    </div>
                </div>							
            </div>
        </div>
        <script>

			// 옵션 선택 이벤트
			$('.option_list_item').on('click', function() {
				var selectedOption = $(this).text();
				$(this).closest('.select_box').find('.label').text(selectedOption);
			});

        </script>
    </div>
    `}
};
function fn_searchMembershipItem(id){
    let formData = new FormData();
    formData.append("menuClass", menuClass);
    formData.append("muTreatmentId", id);
    $.ajax({
        url: encodeURI('/webtreatmentprocedure/selectListTreatmentProcedure.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async: true,
        success: function(data){
            if('0'==data.msgCode){
                let listHTML = '';
                if(0<data.rows.length) {
                    membershipItemList = data.rows;
                    data.rows.forEach(row=>{
                        listHTML += `<li class="option_list_item" id="${row.muTreatmentProcedureId}">${row.procedureName}</li>`
                    })

                    $('#membershipChargeInsertModal .dropdown-menu').append(listHTML);
                    // let membershipTreatments = data.rows.filter(item => item.treatmentName === '멤버십');
                    // let membershipCount = membershipTreatments.length;
                    // let membershipIds = membershipTreatments.map(item => item.muTreatmentId);
                    // console.log(membershipCount)
                    // console.log(membershipIds)
                    // fn_searchMembershipItem(membershipIds);
                }
            } else {
                modalEvent.danger("등록 오류", data.msgDesc);
            }
        },
        error : function(xhr, status, error) {
            modalEvent.danger("등록 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
        },
        beforeSend:function(){

        },
        complete:function(){

        }
    });
}

function fn_getMembershipPaymentNumber() {
    let now = new Date();
    let year = now.getFullYear().toString();
    let month = (now.getMonth() + 1).toString().padStart(2, '0');
    let day = now.getDate().toString().padStart(2, '0');
    let hours = now.getHours().toString().padStart(2, '0');
    let minutes = now.getMinutes().toString().padStart(2, '0');
    let seconds = now.getSeconds().toString().padStart(2, '0');
    let milliseconds = now.getMilliseconds().toString().padStart(3, '0');
    let currentTimeString = year + month + day + hours + minutes + seconds + milliseconds;
    return 'PM' + currentTimeString;
}
function fn_handleButtonClick(clickedButton) {

    let clickedButtonClass = clickedButton.attr('class').split(' ')[0];

    // 모든 버튼의 활성화를 해제하고 기본 스타일로 초기화
    const buttons = ['.card_btn', '.monetization_btn', '.account_btn'];
    const defaultImages = {
        card_btn: '/image/web/card.svg',
        monetization_btn: '/image/web/monetization.svg',
        account_btn: '/image/web/account.svg'
    };

    buttons.forEach(button => {
        $('#membershipChargeInsertModal ' + button).removeClass('on').css({
            'background': 'white',
            'color': 'black'
        }).find('img').attr('src', defaultImages[button.replace('.', '')]);
    });

    // 클릭된 버튼의 활성화 상태를 토글
    let isActive = clickedButton.hasClass('on');
    clickedButton.toggleClass('on', !isActive).css({
        'background': isActive ? 'white' : '#3985EA',
        'color': isActive ? 'black' : 'white'
    });

    const activeImages = {
        card_btn: '/image/web/cardW.svg',
        monetization_btn: '/image/web/monetizationW.svg',
        account_btn: '/image/web/accountW.svg'
    };

    if (!isActive) {
        clickedButton.find('img').attr('src', activeImages[clickedButtonClass]);
        if (clickedButtonClass !== 'card_btn') {
            clickedButton.closest('.button_box').nextAll('.input_box').addClass('openBox');
        }else{
            $('#membershipChargeInsertModal .cashReceiptsType button.active').removeClass('active');
            clickedButton.closest('.button_box').nextAll('.input_box').removeClass('openBox');
        }
    }
}