
/* ##############################################################
	설  명 : [Modal]진료 시술 등록 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/
// //양도 멤버십금액
// let transferAmount=0;
// //양도 가능 멤버십금액
// let availableBalance=0;
// //양도 후 멤버십 잔액
// let remainingBalance=0;
// //양수 후 멤버십금액
// let finalAmount=0;
// //멤버십 보유금액
// let holdAmount=0;
let membershipTransferSelectModal = {
    callback : null,
    reqParam : null,
    dataList : null,
    /* 모달 초기화 작업 */
    init : function () {
        $('#membershipTransferSelectModal').remove();
        userData.phoneNumber=fn_setFormatPhone(userData.phoneNumber);
        $('body').append(this.HtmlTemplate());
        //그리드 이벤트
        this.setEvent();
    },
    /* 그리드 이벤트 설정 */
    setEvent:function() {
        //연락처 양식 변경
        $('#membershipTransferSelectModal .cancel_btn').on("click", function(){
            membershipTransferSelectModal.close();
        });

        $('#membershipTransferSelectModal .seve_bth').on("click", function(){
            membershipTransferSelectModal.save();
        });
        // $('#membershipTransferSelectModal #searchKeyword').on("click", function(){
        //     let reqParam = {};
        //     searchTransferModal.popup(function (obj, reqParam) {
        //         membershipTransferSelectModal.dataList=obj;
        //         fn_setTransferMemberData2(obj);
        //     }, reqParam);
        // });
        // $('#membershipTransferSelectModal #searchKeyword').on('keypress',function(){
        //     fn_insertModalSearchEnter();
        // });

        // $('#membershipTransferSelectModal #transferAmount').on('input', function() {
        //     // 입력된 키가 숫자가 아닌 경우 입력을 막음
        //     this.value = this.value.replace(/\D/g, '');
        // });
        //
        // $('#membershipTransferSelectModal #transferAmount').on('change', function() {
        //     transferAmount = parseInt(this.value.replace(/,/g, ''), 10);
        //     availableBalance = parseInt(userData.membershipBalance.replace(/,/g, ''), 10);
        //
        //     if (isNaN(transferAmount)) {
        //         transferAmount = 0;
        //     }
        //
        //     if (transferAmount > availableBalance) {
        //         modalEvent.warning("", "양도 가능 멤버십 잔액이 부족합니다.");
        //         this.value='';
        //         transferAmount = 0;
        //         document.getElementById('remainingBalance').innerText = `${availableBalance.toLocaleString()}원`;
        //     } else {
        //         remainingBalance = availableBalance - transferAmount;
        //         document.getElementById('remainingBalance').innerText = `${remainingBalance.toLocaleString()}원`;
        //     }
        //     if($('#transferInfo').val()){
        //         holdAmount = parseInt($('#holdAmount').text().replace(/,/g, ''), 10);
        //         finalAmount = holdAmount+transferAmount;
        //         $('#finalAmount').text(`${finalAmount.toLocaleString()}`);
        //     }
        // });

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

        if( membershipTransferSelectModal.callback )  {
            membershipTransferSelectModal.callback(checkedData);
        }
        membershipTransferSelectModal.close();
    },
    //저장
    search:function() {
        let muMembershipHistoryId = membershipTransferSelectModal.reqParam.muMembershipHistoryId;

        if(true != fn_emptyCheck(muMembershipHistoryId)){
            modalEvent.warning("조회", "양도/양수 정보가 없습니다.");
            return;
        }

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

        $.ajax({
            url: encodeURI('/webmembership/selectMembershipTransfer.do'),
            data: formData,
            dataType: "json",
            processData: false,
            contentType: false,
            type: 'POST',
            async: true,
            success: function(data){
                if('0'==data.msgCode){
                    let transferData = data.rows[0];
                    let listHTML=`<li>
                                            <label>${transferData.senderName}</label>
                                            <p>
                                                <span>${transferData.senderBirthday}</span>
                                                <span>${transferData.senderAge}</span>
                                                <span>${transferData.senderGender}</span>
                                                <span>${transferData.senderNationality}</span>
                                                <span>`+fn_setFormatPhone(`${transferData.senderPhoneNumber}`)+`</span>
                                            </p>
                                        </li>
                                        <li>
                                            <label>양도가능 멤버십 잔액</label>
                                            <p id="availableBalance">${transferData.senderBeforeAmount}원</p>
                                        </li>
                                        <li>
                                            <label>양도 후 멤버십 잔액</label>
                                            <p id="remainingBalance">${transferData.senderAfterAmount}원</p>
                                        </li>`
                    $('#membershipTransferSelectModal .left_box ul').append(listHTML);
                    $('#membershipTransferSelectModal .modal-header span').append(transferData.writeDate);
                    $('#membershipTransferSelectModal #transferInfo').val(`${transferData.receiverName}\n${transferData.receiverBirthday} | ${transferData.receiverAge} | ${transferData.receiverGender} | ${transferData.receiverNationality} | ${fn_setFormatPhone(transferData.receiverPhoneNumber)}`.trim());
                    $('#membershipTransferSelectModal #transferAmount').val(transferData.transferAmount.toLocaleString());
                    $('#membershipTransferSelectModal #holdAmount').text(transferData.receiverBeforeAmount.toLocaleString());

                    $('#membershipTransferSelectModal #finalAmount').text(transferData.receiverAfterAmount.toLocaleString());
                    $('#membershipTransferSelectModal #memo').val(transferData.memo);
                }
                else{
                    modalEvent.danger("조회 오류", data.msgDesc);
                }
            },
            error : function(xhr, status, error) {
                modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            },
            beforeSend:function(){
            },
            complete:function(){

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

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

		setTimeout(function(){
			$('#membershipTransferSelectModal').remove();
		},500);
    },
    HtmlTemplate :function (){
        return`
    <div class="modal transfer_modal fade" id="membershipTransferSelectModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <p class="title">멤버십 양도</p>
                    <p>양도일자 <span></span></p>
                </div>
    
                <div class="modal-body">
                    <div class="transfer_top">
                        <div class="left_box">
                            <p class="box_title">양도인</p>
                            <ul>
<!--                                <li>-->
<!--                                    <label>${userData.userName}</label>-->
<!--                                    <p>-->
<!--                                        <span>${userData.birth}</span>-->
<!--                                           <span>${userData.age}</span>-->
<!--                                           <span>${userData.gender}</span>-->
<!--                                        <span>${userData.nationality}</span>-->
<!--                                         <span>${userData.phoneNumber}</span>-->
<!--                                    </p>-->
<!--                                </li>-->
<!--                                <li>-->
<!--                                    <label>양도가능 멤버십 잔액</label>-->
<!--                                    <p id="availableBalance">${userData.membershipBalance}원</p>-->
<!--                                </li>-->
<!--                                <li>-->
<!--                                    <label>양도 후 멤버십 잔액</label>-->
<!--                                    <p id="remainingBalance">${userData.membershipBalance}원</p>-->
<!--                                </li>-->
                            </ul>
                        </div>
                        <div class="img_box">
                            <img src="/image/web/arrow2.svg" alt="화살표"/>
                        </div>
                        <div class="right_box">
                            <p class="box_title">양수인</p>

                            <ul>
                                <li class="search_list first">
<!--                                    <div class="search_box">-->
<!--                                        <img src="/image/web/search_G.svg" alt="search"/>-->
<!--                                        <input type="text" id="searchKeyword" placeholder="성함, 연락처" readonly>-->

<!--                                        <div class="search_list"></div>&lt;!&ndash; 검색내역 나오는곳 &ndash;&gt;-->
<!--                                    </div>-->
<!--                                    <button class="search_btn" id="search">조회</button>-->

                                    <div class="textarea_box">
                                        <textarea id="transferInfo" readonly></textarea>
                                    </div>
                                </li>

                                <li>
                                    <label>양도 멤버십 금액</label>
                                    <div class="input_box">
                                        <input type="text" id="transferAmount" placeholder="금액 입력" readonly/>원
                                    </div>
                                </li>
                                <li>
                                    <div class="balance">
                                        <label>멤버십 보유금액</label>
                                        <span id="holdAmount">-</span> 원
                                    </div>
                                    <div class="img_box">
                                        <img src="/image/web/arrow2.svg" alt="화살표"/>
                                    </div>
                                    <div class="balance">
                                        <label>양수 후 멤버십 잔액</label>
                                        <span id="finalAmount">-</span> 원
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <div class="transfer_bottom">
                        <div class="textarea_box">
                            <label>멤버십 양도사유</label>
                            <textarea id="memo" readonly></textarea>
                        </div>
                    </div>
                </div>

                <div class="modal-footer">
                    <div class="btn_box">
                        <button type="button" class="cancel_btn">확인</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    `}
};

/****************************************************************************
 * 양수인 데이터 format 및 삽입
 ****************************************************************************/
function fn_setTransferMemberData2(transferUser){
    $('#transferInfo').val(`${transferUser.userName}\n${transferUser.birth}  ${transferUser.age} | ${transferUser.gender} | ${transferUser.nationality} | ${fn_setFormatPhone(transferUser.phoneNumber)}`.trim());

    holdAmount = parseInt(transferUser.membershipBalance?.replace(/,/g, ''), 10);
    if(isNaN(holdAmount)){
        holdAmount=0;
    }
    finalAmount = holdAmount+transferAmount;
    $('#holdAmount').text(holdAmount.toLocaleString());

    // transferAmount = parseInt(document.getElementById('transferAmount').value.replace(/,/g, ''), 10);
    // if(isNaN(transferAmount)){
    //     transferAmount = 0;
    // }
    $('#finalAmount').text(finalAmount.toLocaleString());
}

