
/* ##############################################################
	설  명 : [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 membershipTransferInsertModal = {
    callback : null,
    reqParam : null,
    dataList : null,
    /* 모달 초기화 작업 */
    init : function () {
        $('#membershipTransferInsertModal').remove();
        userData.phoneNumber=fn_setFormatPhone(userData.phoneNumber);
        $('body').append(this.HtmlTemplate());
        //그리드 이벤트
        this.setEvent();
    },
    /* 그리드 이벤트 설정 */
    setEvent:function() {
        //연락처 양식 변경
        $('#membershipTransferInsertModal .cancel_btn').on("click", function(){
            membershipTransferInsertModal.close();
        });

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

        $('#membershipTransferInsertModal #transferAmount').on('input', function() {
            // 입력된 키가 숫자가 아닌 경우 입력을 막음
            this.value = this.value.replace(/\D/g, '');
        });

        $('#membershipTransferInsertModal #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( membershipTransferInsertModal.callback )  {
            membershipTransferInsertModal.callback(checkedData);
        }
        membershipTransferInsertModal.close();
    },
    //저장
    save:function() {
        console.log(this.dataList);
        let transferToUser = this.dataList;
        let transferFromUser = userData;
        let transferInfo  = $('#membershipTransferInsertModal #transferInfo').val();

        if(true != fn_emptyCheck(transferInfo)||true != fn_emptyCheck(transferToUser.muUserId)){
            modalEvent.warning("등록", "양수인 정보가 없습니다.");
            return;
        }

        if(true != fn_emptyCheck(transferAmount)||transferAmount==0){
            modalEvent.warning("등록", "양도 멤버십 금액이 없습니다.");
            return;
        }

        if(transferToUser.muUserId===transferFromUser.muUserId){
            modalEvent.warning("등록", "본인에게 멤버십을 양도할 수 없습니다.");
            return;
        }
        let msg = `${transferToUser.userName}님께 ${$('#membershipTransferInsertModal #transferAmount').val()}원을 양도하시겠습니까?`;
        modalEvent.info("등록", msg, function(){
                let formData = new FormData();
                formData.append("menuClass", menuClass);
                formData.append("transferFromUserId",transferFromUser.muUserId );
                formData.append("transferToUserId",transferToUser.muUserId );
                formData.append("transferAmount", transferAmount);
                formData.append("availableBalance", availableBalance);
                formData.append("holdAmount", holdAmount);
                formData.append("finalAmount", finalAmount);
                formData.append("remainingBalance", remainingBalance);
                formData.append("memo", $("#membershipTransferInsertModal #memo").val());
                formData.append("membershipYn", transferToUser.membershipYn);

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

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

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

		setTimeout(function(){
			$('#membershipTransferInsertModal').remove();
		},500);
    },
    HtmlTemplate :function (){
        return`
    <div class="modal transfer_modal fade" id="membershipTransferInsertModal" 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>${getFormattedDate()}</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><!-- 검색내역 나오는곳 -->
                                    </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="금액 입력"/>원
                                    </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"></textarea>
                        </div>
                    </div>
                </div>

                <div class="modal-footer">
                    <div class="btn_box">
                        <button type="button" class="cancel_btn">취소</button>
                        <button type="button" class="seve_bth">저장</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    `}
};


/****************************************************************************
 * 오늘 날짜
 ****************************************************************************/
function getFormattedDate() {
    const date = new Date();

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // getMonth()는 0부터 시작하므로 1을 더해줌
    const day = String(date.getDate()).padStart(2, '0');

    return `${year}-${month}-${day}`;
}

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

    let membershipBalance = String(transferUser.membershipBalance);

    holdAmount = parseInt(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());
}

