/* ##############################################################
	설  명 : [Modal]멤버십 양수인 검색 팝업
	작성일 : 2024. 05. 10.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2024. 03. 14.	NTsoft 	 최초 생성
*/
let searchTransferModal = {
    callback: null,
    reqParam: null,
    dataList: null,
    /* 모달 초기화 작업 */
    init: function () {
        $('#searchTransferModal').remove();
        $('body').append(searchTransferModal.HtmlTemplate);

        //그리드 이벤트
        this.setEvent();
    },
    /* 그리드 이벤트 설정 */
    setEvent: function () {
        $('#searchTransferModal .btnCancle').on("click", function () {
            searchTransferModal.close();
        });
        $('#searchTransferModal #searchTransferUserBtn').on("click", function () {
            searchTransferModal.search();
        });
        $('#searchTransferModal #transferUserSearchKeyword').on('keypress',function(e){
            fn_insertModalSearchEnter(e);
        });
    },
    /* 데이터 선택 */
    setSelect: function (target) {
        let rowData = {}
        $(target).parent().each(function() {
            let $row = $(this);

            const id = $row.find('td:nth-child(1)').attr('id');
            const membershipYn = $row.find('td:nth-child(1)').data('membershipyn');
            const membershipBalance = $row.find('td:nth-child(1)').data('membershipbalance');
            const userName = $row.find('td:nth-child(1)').text().trim();
            const birth = $row.find('td:nth-child(3)').text().trim();
            const age = calculateAge($row.find('td:nth-child(3)').text().trim());
            const gender = $row.find('td:nth-child(4)').text().trim()
            const nationality = $row.find('td:nth-child(2)').text().trim()
            const phoneNumber = $row.find('td:nth-child(5)').text().trim()

            rowData = {
                muUserId:id,
                membershipYn:membershipYn,
                userName: userName,
                birth: birth,
                membershipBalance: membershipBalance,
                age: age,
                gender: gender,
                nationality: nationality,
                phoneNumber: phoneNumber,
            };

        });
        if (searchTransferModal.callback) {
            searchTransferModal.callback(rowData);
        }
        searchTransferModal.close();
    },
    search: function() {
        let searchKeyword = $("#transferUserSearchKeyword").val();

        let formData = new FormData();
        formData.append("menuClass", menuClass);
        formData.append("membershipSearchKeywordParam", searchKeyword);
        $.ajax({
            url: encodeURI('/webmembership/selectToTransferUser.do'),
            data: formData,
            dataType: "json",
            processData: false,
            contentType: false,
            type: 'POST',
            async: false,
            success: function (data) {
                if ('0' == data.msgCode) {
                    if(0<data.rows.length){
                        let tbody = document.querySelector('#searchTransferModal .modal_table tbody');
                        tbody.innerHTML='';
                        data.rows.forEach(function(data) {
                            let tr = document.createElement('tr');
                            tr.innerHTML = '<td id="' + data.muUserId + '" data-membershipyn="'+data.membershipYn+'" data-membershipbalance="'+data.membershipBalance+'">' + data.userName + '</td>' +
                                '<td>' + data.nationality + '</td>' +
                                '<td>' + convertDateFormat(data.birth) + '</td>' +
                                '<td>' + data.gender + '</td>' +
                                '<td>' + data.phoneNumber + '</td>' ;
                            tbody.appendChild(tr);
                        });
                        tbody.addEventListener('click', function(event) {
                            if (event.target.tagName === 'TD' && event.target.id) {
                                searchTransferModal.setSelect(event.target);
                            }
                        });
                    }else{
                        modalEvent.warning("조회", "조회결과가 없습니다.");
                    }
                }
            },
            error: function (xhr, status, error) {
                modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            },
            beforeSend: function () {
            },
            complete: function () {
            },
        })
    },

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

        //콜백함수 지정.
        searchTransferModal.callback = callback;

        searchTransferModal.dataList = null;

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

		setTimeout(function(){
			$('#searchTransferModal').remove();
		},500);
    },
    HtmlTemplate :`
        <div id="searchTransferModal" class="modal search_modal fade" tabIndex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <label class="title">양수인조회</label>
                    </div>
                    <div class="modal-body">
                        <div class="input_box">
                            <div class="search_box">
                                <img src="../../../../image/web/search_B.svg">
                                <input id="transferUserSearchKeyword" type="text" placeholder="성함, 연락처">
                            </div>
                            <button id="searchTransferUserBtn">검색</button>
                        </div>
                        <div class="modal_table">
                            <table>
                                <thead>
                                <tr>
                                    <th>성함</th>
                                    <th>국적</th>
                                    <th>생년월일</th>
                                    <th>성별</th>
                                    <th>연락처</th>
                                </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td colspan="5" style="text-align: center; color: black; cursor: default" >조회결과가 없습니다.</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <div class="btn_box">
                            <button type="button" class="cancel_btn btnCancle">취소</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>`
};
/****************************************************************************
 * 검색 엔터 이벤트
 ****************************************************************************/
function fn_insertModalSearchEnter(e, type){
    if(e.which){
        // 파이어폭스
        if(13 == e.which) {
            //로그인 액션 스크립트
            searchTransferModal.search();
        }
    }
    else{
        // 윈도우, 사파리, 크롬
        if(13 == event.keyCode) {
            //로그인 액션 스크립트
            searchTransferModal.search();
        }
    }
}
function convertDateFormat(input) {

    if(input && "-" != input){
		// 날짜 추출 정규식
		const datePart = input.match(/\d{4}-\d{2}-\d{2}/)[0];
		const date = new Date(datePart);

		const year = date.getFullYear();
		const month = ('0' + (date.getMonth() + 1)).slice(-2);
		const day = ('0' + date.getDate()).slice(-2);

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

function calculateAge(date) {
    if(date && "-" != date){
        let birthDate = new Date(date);
        let today = new Date();
        let age = today.getFullYear() - birthDate.getFullYear();
        let month = today.getMonth() - birthDate.getMonth();

        if (0 > month || (0 === month  && today.getDate() < birthDate.getDate())) {
            age--;
        }

        return age+"세";
    }else{
        return "-";
    }
}