/* ##############################################################
	설  명 : [Modal]고객 검색 팝업
	작성일 : 2025. 06. 24.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2024. 03. 14.	NTsoft 	 최초 생성
*/
let treatmentSelectModal = {
    callback: null,
    reqParam: null,
    dataList: null,
    /* 모달 초기화 작업 */
    init: function () {
        $('#treatmentSelectModal').remove();
        $('body').append(this.HtmlTemplate);
        //그리드 이벤트
        this.setEvent();
		treatmentSelectModal.searchIntroUserList('Y');
    },
    /* 그리드 이벤트 설정 */
    setEvent: function () {
        $('#treatmentSelectModal .btnCancle').on("click", function () {
            treatmentSelectModal.close();
        });
        $('#treatmentSelectModal .btnSave').on("click", function () {
            treatmentSelectModal.save();
        });
        document.getElementById("searchIntroUserBtn").addEventListener('click',()=>{
            treatmentSelectModal.searchIntroUserList('N');
        });
        document.getElementById("introUserSearchKeyword").addEventListener('keypress',(e)=>{
            fn_IntroUserEnter(e)
        });
    },

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

    },
    searchIntroUserList:function (initflag){
        let searchKeyword = document.querySelector("#introUserSearchKeyword").value;
        let formData = new FormData();

        if(2 > searchKeyword.length && initflag == 'N'){
            modalEvent.warning("", "검색어는 2자 이상으로 입력해 주시기 바랍니다.");

            return;
        }

        formData.append("menuClass", menuClass);
        formData.append("userSearchKeywordParam", searchKeyword??'');

        $.ajax({
            url: encodeURI('/webtreatmentdiet/selectListTreatmentOption.do'),
            data: formData,
            dataType: "json",
            processData: false,
            contentType: false,
            type: 'POST',
            async: true,
            success: function (data) {
                if ('0' == data.msgCode) {
                    let tbody = document.querySelector('.list1_modal_table tbody');
                    while (tbody.firstChild) {
                        tbody.removeChild(tbody.firstChild);
                    }
                    dataList = data.rows;
                    data.rows.forEach(function(treatment, index) {
                        let tr = document.createElement('tr');
                        tr.innerHTML = '<td id="' + treatment.treatmentId + '">' + treatment.treatmentNm + '</td>';
						tr.innerHTML += '<td id="' + treatment.price + '">' + treatment.price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '</td>';
						tr.innerHTML += '<td id="' + treatment.discountPrice + '">' + treatment.discountPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '</td>';
                        tr.onclick = function() {
                            treatmentSelectModal.setSelect(index);
                        };
						
                        tbody.appendChild(tr);
                        
                    });
                }
            },
            error: function (xhr, status, error) {
                modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            },
            beforeSend: function () {
            },
            complete: function () {
            },
        })
    },
    /*
     * 팝업
     * callback : 콜백함수, reqParam: 팝업파라미터
     */
    popup: function (callback, reqParam) {
        // 초기화 후 열기
        treatmentSelectModal.init();

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

        // treatmentSelectModal.searchIntroUserList();

        setTimeout(function () {
            $('#treatmentSelectModal').modal('show')
        }, 200);

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

		setTimeout(function(){
			$('#treatmentSelectModal').remove();
		},500);
    },
    HtmlTemplate : `
        <div id="treatmentSelectModal" class="modal list1_diagnosis fade" tabIndex="-1"
             aria-labelledby="exampleModalLabel"
             aria-hidden="">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="list1_modal_header">
                        <label>시술조회</label>
                    </div>
                    <div class="list1_modal_body">
                        <div class="input_box">
                            <div class="search_box">
                                <img src="/image/web/search_B.svg"/>
                                <input id="introUserSearchKeyword" type="text" placeholder="시술명"/>
                            </div>
                            <button id="searchIntroUserBtn">검색</button>
                        </div>
                        <div class="list1_modal_table">
                            <table>
                                <thead>
                                <tr>
                                    <th>시술명</th>
									<th>가격</th>
									<th>할인가격</th>
                                </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td style="text-align: center;">조회결과가 없습니다.</td>
                                    </tr>                         
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="list1_modal_footer">
                        <div class="btn_box">
                            <button type="button" class="cancel_btn btnCancle">취소</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>`
};
/****************************************************************************
 * 검색 엔터 이벤트
 ****************************************************************************/
function fn_IntroUserEnter(e){
    if(e.which){
        // 파이어폭스
        if(13 == e.which) {
            //로그인 액션 스크립트
            treatmentSelectModal.searchIntroUserList();
        }
    }else{
        // 윈도우, 사파리, 크롬
        if(13 == event.keyCode) {
            //로그인 액션 스크립트
            treatmentSelectModal.searchIntroUserList();
        }
    }
}
function convertDateFormat(input) {
	if(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 '';
}









