
/* ##############################################################
	설  명 : [Modal]고객 등록 팝업
	작성일 : 2024. 03. 14.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2024. 03. 14.	NTsoft 	 최초 생성
*/
let	userInsertModal = {
    callback : null,
    reqParam : null,
    dataList : null,
    /* 모달 초기화 작업 */
    init : function () {
        $('#userInsertModal').remove();
        $('body').append(this.HtmlTemplate);
        //그리드 이벤트
        this.setEvent();
    },
    /* 그리드 이벤트 설정 */
    setEvent:function() {
        $('#userInsertModal .btnCancle').on("click", function(){
            userInsertModal.close();
        });

        $('#userInsertModal .btnSave').on("click", function(){
            userInsertModal.save();
        });
        
        userInsertModal.setTreatmentOption();
        userInsertModal.setSelectBox(3);

        $('#userInsertModal #birthday').datetimepicker({
            allowInputToggle: true,
            format: 'YYYY-MM-DD',
			useCurrent: false // 현재 날짜 자동 선택
        }).on("dp.change", function(e){
			// 날짜가 변경될 때 실행
			// console.log(e.oldDate.format("YYYY-MM-DD"));
			// console.log(e.date.format("YYYY-MM-DD"));
            let selectDate = e.date.format("YYYY-MM-DD");

            let ageText = userInsertModal.calculateAge(selectDate);
            $("#userInsertModal .txtAge").text(ageText);


            selectDate = selectDate.replaceAll("-", "");
            $("#userRrn1").val(selectDate.substring(2, selectDate.length));
		});

        // 국적선택에 따른 여권번호/외국인 번호 활성화 이벤트
        userInsertModal.isForeignerEvent();
        
        userInsertModal.clickEvent();
        /*$('#userInsertModal .essential .select_box ul').each(function() {
            this.querySelector('li:first-child')?.click();
        });*/
        
        // 생년월일 변경 시 나이표시 이벤트
        /*document.querySelector('#userInsertModal #birthday').addEventListener('change',(e)=>{
             let ageText = userInsertModal.calculateAge(e.target.value);
             
             document.querySelector('#userInsertModal .txtAge').textContent = ageText;
        });*/
        
        // 주소 찾기 버튼 이벤트
        // document.querySelector('#userInsertModal .address_btn').addEventListener('click',()=>{
        //      new daum.Postcode({
		//         oncomplete: function (data) {
		//             let roadAddr = data.roadAddress; // 도로명 주소 변수
		//             // 우편번호와 주소 정보를 해당 필드에 넣는다.
		//             $('#userInsertModal input[name="modalAddress"]').val('(' + data.zonecode + ')' + (roadAddr ? roadAddr : data.jibunAddress));
		//
		//             // 참고항목 문자열이 있을 경우 해당 필드에 넣는다.
		//             document.querySelector('#userInsertModal #addressDetails').value = '';
		//             document.querySelector('#userInsertModal #addressDetails').focus();
		//         }
		//     }).open();
        // });
        
        // 연락처 형식 이벤트
        document.querySelector('#userInsertModal #phoneNumber').addEventListener("input", function(event) {
            userInsertModal.formatPhoneNumber(this);
        });
        
        // 보조 연락처 형식 이벤트
        document.querySelector('#userInsertModal #phoneNumber2').addEventListener("input", function(event) {
            userInsertModal.formatPhoneNumber(this);
        });
        
        // 외국인 등록번호 앞자리 이벤트
        document.querySelector('#userInsertModal #userArc1').addEventListener("input", function(event) {
            userInsertModal.formatRrn1(this);
        });
        
        // 외국인 등록번호 뒷자리 이벤트
        document.querySelector('#userInsertModal #userArc2').addEventListener("input", function(event) {
            userInsertModal.formatRrn2(this);
        });
        
        // 주민등록번호 앞자리 이벤트
        document.querySelector('#userInsertModal #userRrn1').addEventListener("input", function(event) {
            userInsertModal.formatRrn1(this);
        });
        
        // 주민등록번호 뒷자리 이벤트
        document.querySelector('#userInsertModal #userRrn2').addEventListener("input", function(event) {
        	userInsertModal.formatRrn2(this);
        });
        
        // 추천인 이벤트
        document.querySelector('#userInsertModal #searchIntroUser').addEventListener("click", function(){
			userInsertModal.listOpen();
		});
        
    },
    /* 데이터 선택 */
    setSelect:function(selectNumber) {
        var checkedData = dataList[selectNumber];
        if(dataList==null||checkedData==undefined){
            return ;
        }

        if( userInsertModal.callback )  {
            userInsertModal.callback(checkedData);
        }
        userInsertModal.close();
    },
    /* 콤보 셋팅 */
    setSelectBox:function(num){
		let category=fn_selectCategoryList2();
	    for(let i = 0; i < num; i++){
	        let categoryCode     = category[i].categoryCode;
	        fn_selectModalOtherOption3(categoryCode, "userInsertModal");
	    }
	},
    /* selectBox 이벤트 */
	clickEvent:function() {
	    // $('#userInsertModal .select_box').off('click');
	    //$(document).off('click');
	
	    // $('#userInsertModal .select_box').on('click', function () {
	    //     $(this).find('.select_option_list').toggle();
	    //     $('#userInsertModal .select_box').not(this).find('.select_option_list').hide();
	    // });
	    // 옵션 선택 이벤트
	    $('#userInsertModal .select_box').on('click', 'li', function (e) {
	        let target = $(this);
	        
	        // 옵션 선택 이벤트 핸들러
		    let selectedOption = target.text();
		    if ('' !== selectedOption) {
		        // 선택된 옵션의 텍스트를 .label 요소에 설정
		        target.closest('.select_box').find('.label').text(selectedOption);
		    } else {
		        // 선택된 옵션이 텍스트가 아닌 경우(예: 이미지), .html()을 사용
		        selectedOption = target.html();
		        target.closest('.select_box').find('.label').html(selectedOption);
		    }
		    target.closest('.select_box').find('input')?.val(target.attr('id')??selectedOption);
		    target.closest('.select_box').find('.option_list_item').removeClass('selected');
		    target.addClass('selected');
		    // target.closest('.select_option_list').hide();
		    // e.stopPropagation();
	    });
	
		// 다른 곳을 클릭했을 때 옵션 숨기기
	    // $(document).on('click', function (event) {
	    //     if (!$(event.target).closest('.select_box').length) {
	    //         $('#userInsertModal .select_option_list').hide();
	    //     }
	    // });
	},
    /* 휴대폰 번호 숫자입력 제한 */
    formatPhoneNumber:function(inputElement){
		// 입력된 키가 숫자가 아닌 경우 입력을 막음
	    inputElement.value = inputElement.value.replace(/\D/g, '');
	    let phoneNumber = inputElement.value;
	
	    // Prevent further input if length exceeds 11
	    if (phoneNumber.length > 11) {
	        inputElement.value = phoneNumber.substring(0, 11)
	    }
	    inputElement.value = fn_setFormatPhone(phoneNumber);
	},
    /* 주민번호 숫자입력 제한 */
    formatRrn1:function(inputElement){
		// 입력된 키가 숫자가 아닌 경우 입력을 막음
	    inputElement.value = inputElement.value.replace(/\D/g, '');
	    let Rrn1 = inputElement.value;
	
	    if (Rrn1.length > 6) {
	        inputElement.value=Rrn1.substring(0, 6)
	    }
	},
    /* 주민번호 숫자입력 제한 2 */
    formatRrn2:function(inputElement){
		inputElement.value = inputElement.value.replace(/\D/g, '');
	    let Rrn1 = inputElement.value;
	
	    if (Rrn1.length > 7) {
	        inputElement.value=Rrn1.substring(0, 7)
	    }
	},
    /* 캘린더 날짜 변경 시 만나이 계산 */
    calculateAge:function(param){
		let birthday = param;
	    let birthDate = new Date(birthday);
	    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}세`;
	},
    /* 국적선텍에 따른 여권번호/외국인 번호 활성화 event */
    isForeignerEvent:function(){
		document.querySelectorAll('#userInsertModal .local').forEach(element => {
	        element.addEventListener('click', function () {
	            document.querySelectorAll('#userInsertModal .local_box').forEach(box => box.style.display = 'block');
	            document.querySelectorAll('#userInsertModal .foreigner_box').forEach(box => box.style.display = 'none');
	        });
	    });
	
	    document.querySelectorAll('#userInsertModal .foreigner').forEach(element => {
	        element.addEventListener('click', function () {
	           document.querySelectorAll('#userInsertModal .local_box').forEach(box => box.style.display = 'none');
	           document.querySelectorAll('#userInsertModal .foreigner_box').forEach(box => box.style.display = 'block');
	        });
	    });
	
	    document.querySelectorAll('#userInsertModal .passport_number_option').forEach(element => {
	        element.addEventListener('click', function () {
	            document.querySelectorAll('#userInsertModal .foreigner_number_box').forEach(box => {
	                box.style.display = 'none';
	                box.querySelector('input').value = '';
	            });
	            document.querySelectorAll('#userInsertModal .passport_number_box').forEach(box => box.style.display = 'block');
	        });
	    });
	
	    document.querySelectorAll('#userInsertModal .foreigner_number_option').forEach(element => {
	        element.addEventListener('click', function () {
	            document.querySelectorAll('#userInsertModal .passport_number_box').forEach(box => {
	                box.style.display = 'none';
	                box.querySelector('input').value = '';
	            });
	            document.querySelectorAll('#userInsertModal .foreigner_number_box').forEach(box => box.style.display = 'block');
	        });
	    });
	},
    /* 추천인 검색 팝업 open */
    listOpen:function(selectNumber) {
        let reqParam = {};
        userIntroSelectModal.popup(function (obj, reqParam) {
            document.querySelector("#userInsertModal input[name='modalRecommendId']").dataset.userId=obj.muUserId;
            document.querySelector("#userInsertModal input[name='modalRecommendId']").value = obj.userName;
        }, reqParam);
    },
    /* 관심진료 옵션 셋팅*/
    setTreatmentOption:function(selectedGroupId){
        let formData = new FormData();
        $.ajax({
            url: encodeURI('/webtreatment/selectListTreatmentOption.do'),
            data: formData,
            dataType: "json",
            processData: false,
            contentType: false,
            type: 'POST',
            async: false,
            success: function(data){
                if('0'==data.msgCode){
                    let listHTML = '';
    
                    for(let i = 0; i < data.rows.length; i++){
                        let treatmentName = data.rows[i].treatmentName;
                        let treatmentId = data.rows[i].muTreatmentId;
                        let selectedYn = '';
                        if(treatmentId === selectedGroupId) {
                            selectedYn = 'selected';
                            $("#userInsertModal .modalTreatment").parent().find('button').text(treatmentName);
                        }
    
                        listHTML += `<li class="option_list_item ${selectedYn}" id="${treatmentId}">${treatmentName}</li>`;
                    }
                    $("#userInsertModal .modalTreatment").empty().append(listHTML);
    
                }else if(data.msgCode=='-1'){
                    modalEvent.warning("조회 오류", data.msgDesc);
                }else{
                    modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
                }
            },
            error : function(xhr, status, error) {
                modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            },
            beforeSend:function(){
            },
            complete:function(){
            }
        });
    },
	/* 주민번호, 외국인 등록번호 및 생년월일, 성별 유효성검사 */
	userRrnCheck:function(idNumber){
		let year = idNumber.substring(0, 2);
	    let month = idNumber.substring(2, 4);
	    let day = idNumber.substring(4, 6);
	    let yearPrefix;
	    let genderCode = idNumber.charAt(6);
	
	    switch (genderCode) {
	        case '1':
	        case '2':
	        case '5':
	        case '6':
	            yearPrefix = '19'
	            break;
	        case '3':
	        case '4':
	        case '7':
	        case '8':
	            yearPrefix = '20';
	            break;
	        default:
	            console.log("잘못된 주민등록번호입니다.");
	            return;
	    }
	    let genderInput = document.querySelector('#userInsertModal input[name="modalGender"]:checked').value; // 성별 입력값 ('M' 또는 'F')
	    let birthDateInput = document.querySelector('#userInsertModal input[name="modalBirthday"]').value; // 'yyyy-mm-dd' 형식
	
	    // 성별 검증
	    let genderMatch = ((genderCode === '1' || genderCode === '3' || genderCode === '5' || genderCode === '7') && genderInput === 'M') ||
	        ((genderCode === '2' || genderCode === '4' || genderCode === '6' || genderCode === '8') && genderInput === 'F');
	
	    let fullYear = yearPrefix + year;
	    let birth = `${fullYear}-${month}-${day}`;
	
	    // 생년월일 및 성별 일치 검증
	    if (birth === birthDateInput && genderMatch) {
	        return true;
	    } else {
	        return false;
	    }
	},
    /****************************************************************************
     * 고객 정보 등록
     ****************************************************************************/
    //저장
    save:function() {
        let nationalitySelectYn         = $("#nationality_pop .option_list_item.selected").length==0?"N":"Y";
        let nationalityCode             = "";
        let nationality                 = "";
        let localYn                     = "";
        if("Y" == nationalitySelectYn){
            nationalityCode             = $("#nationality_pop .option_list_item.selected").data('code');
            nationality                 = $("#nationality_pop .option_list_item.selected").attr('id').split('_')[1];
            localYn                     = $("#nationality_pop .option_list_item.selected").hasClass('local');
        }
        let userName                    = $("#userName").val().trim();
        let userRrn1                    = $("#userRrn1").val().trim();
        let userRrn2                    = $("#userRrn2").val().trim();
        let userPno                     = $("#userPno").val().trim();
        let userArc1                    = $("#userArc1").val().trim();
        let userArc2                    = $("#userArc2").val().trim();
        let phoneNumber                 = $("#phoneNumber").val().replace(/-/g, "");
        let phoneNumber2                = $("#phoneNumber2").val().replace(/-/g, "");
        // let email                       = $("#email").val().trim();
        // let emailYn                     = email ? 'Y' : "N";
        let refusePhotoYn               = $("#userInsertModal input[name='modalRefusePhotoYn']:checked").val();
        let smsYn                       = $("#userInsertModal input[name='modalSmsYn']:checked").val();
        let gender                      = $("input[name='gender']:checked").val()==null?"":$("input[name='gender']:checked").val();
        let channelSelectYn             = $("#channel .option_list_item.selected").length==0?"N":"Y";
        let channel                     = "";
        let channelCode                 = "";
        if("Y" == channelSelectYn){
            channel                     = ($("#channel .option_list_item.selected").attr("id")||'').split('_')[1]||'';
            channelCode                 = $("#channel .option_list_item.selected").data('code');
        }
        let muGroupIdSelectYn           = $("#treatment .option_list_item.selected").length==0?"N":"Y";
        let muGroupId                   = "";
        if("Y" == muGroupIdSelectYn){
            muGroupId                   = $("#treatment .option_list_item.selected").attr("id");
        }
        let userTypeCodeSelectYn        = $("#userType_pop .option_list_item.selected").length==0?"N":"Y";
        let userTypeCode                = "";
        let userType                    = "";
        if("Y" == userTypeCodeSelectYn){
            userTypeCode                = $("#userType_pop .option_list_item.selected").data('code');
            userType                    = $("#userType_pop .option_list_item.selected").attr('id').split('_')[1];
        }
        let memo                        = $("#memo").val();
        let etc                         = $("#etc").val();
        let birthday                    = $("#birthday").val();
        //우편번호
        // let address                     = $("#address").val();
        // let addressDetails              = $("#addressDetails").val().trim();
        // let zipCode      = '';
        // let streetAddress= '';
        // let regex       = /\((\d+)\)(.+)/;
        // let matches = address.match(regex);
        // if (matches) {
        //     zipCode                     = matches[1]; // 괄호 안의 숫자 (우편번호)
        //     streetAddress               = matches[2].trim(); // 괄호 바깥의 텍스트 (주소)
        // }

        let regRrn = /^[0-9]{6}-[1-4][0-9]{6}$/; // 주민등록번호 형식
        // let regPassport = /^[A-PR-WYa-pr-wy][1-9]\d\s?\d{4}[1-9]$/; // 대략적인 여권번호 형식
        let regForeigner = /^[0-9]{6}-[5-8][0-9]{6}$/; // 외국인 등록번호 형식
        let regPhone = /^[0-9]{8,11}$/; // 전화번호 형식
        // let regEmail = /^([0-9a-zA-Z_\.-]+)@([0-9a-zA-Z_-]+)(\.[0-9a-zA-Z_-]+){1,2}$/; // 이메일 형식
        let identification = $("#identification .selected").attr("id");
        let introUserId = document.getElementById('recommendId').dataset.userId;

        if ("Y" != insertUseYn) {
            modalEvent.warning("등록", "등록 권한이 없습니다.");
            return false;
        }
        if(!fn_emptyCheck(nationality)){
            modalEvent.warning("등록", "국적을 선택하세요.");
            return;
        }
        if(!fn_emptyCheck(userName)){
            modalEvent.warning("등록", "고객명을 입력하세요.",()=>{$("#userName").focus()});
            return;
        }
        else{
            if(!fn_lengthCheck(userName, 35)) {
                modalEvent.warning("등록", "이름 정보는 35자를 넘을 수 없습니다.",()=>{$("#userName").focus()});
                return;
            }
        }

        /*if(!fn_emptyCheck(birthday)){
            modalEvent.warning("등록", "생년월일을 입력하세요.",()=>{$("#birthday").focus()});
            return;
        }*/

        /*if(!fn_emptyCheck(gender)){
            modalEvent.warning("등록", "성별을 입력하세요.");
            return;
        }*/
        
        if(!fn_emptyCheck(channel)){
            channel = '';
        }
        
        if(!fn_emptyCheck(channelCode)){
            channelCode = '';
        }
        
        if(!fn_emptyCheck(muGroupId)){
            muGroupId = '';
        }
        
        if(!fn_emptyCheck(introUserId)){
            introUserId = '';
        }
        
        /*if(!fn_emptyCheck(userType)){
            modalEvent.warning("등록", "고객구분을 선택하세요.");
            return;
        }*/
        if(!fn_emptyCheck(phoneNumber)){
            modalEvent.warning("등록", "연락처 정보를 입력하세요.",()=>{$("#phoneNumber").focus()});
            return;
        }
        else if(!regPhone.test(phoneNumber)){
            modalEvent.warning("등록", "연락처 정보는 숫자 8~11자리여야 합니다",()=>{$("#phoneNumber").focus()});
            return;
        }
        if (phoneNumber2 && !regPhone.test(phoneNumber2)) {
            modalEvent.warning("등록", "유효하지 않은 보조 연락처 형식입니다.",()=>{$("#phoneNumber2").focus()});
            return;
        }
        // 국적이 KR일 때 주민등록번호 검사
        if (localYn) {
            /*if (!fn_emptyCheck(userRrn1)) {
                modalEvent.warning("등록", "주민등록번호 앞자리가 없습니다.",()=>{$("#userRrn1").focus()});
                $("#userRrn1").focus();
                return;
            }
            if (!fn_emptyCheck(userRrn2)) {
                modalEvent.warning("등록", "주민등록번호 뒷자리가 없습니다.",()=>{$("#userRrn2").focus()});
                $("#userRrn2").focus();
                return;
            }
            if (!regRrn.test(userRrn1 + "-" + userRrn2)) {
                modalEvent.warning("등록", "유효하지 않은 주민등록번호입니다.",()=>{$("#userRrn1").focus()});
                return;
            }
            if (!userRrnCheck(userRrn1 + "" + userRrn2)) {
                modalEvent.warning("등록", "입력된 개인정보가 일치하지 않습니다",()=>{$("#userRrn1").focus()});
                return;
            }*/
        } else {
            userRrn1 = "";
            userRrn2 = "";

            /*if ("pno" === identification  ) {
                if (!fn_emptyCheck(userPno)) {
                    modalEvent.warning("등록", "여권번호가 없습니다.",()=>{$("#userPno").focus()});
                    $("#userPno").focus();
                    return;
                }
                // if (!regPassport.test(userPno)) {
                //     modalEvent.warning("등록", "유효하지 않은 여권번호입니다.",()=>{$("#userPno").focus()});
                //     return;
                // }
            } else {
                if (!fn_emptyCheck(userArc1)) {
                    modalEvent.warning("등록", "외국인 등록번호 앞자리가 없습니다.",()=>{$("#userArc1").focus()});
                    $("#userRrn1").focus();
                    return;
                }
                if (!fn_emptyCheck(userArc2)) {
                    modalEvent.warning("등록", "외국인 등록번호 뒷자리가 없습니다.",()=>{$("#userArc2").focus()});
                    $("#userRrn2").focus();
                    return;
                }
                if (!regForeigner.test(userArc1 + "-" + userArc2)) {
                    modalEvent.warning("등록", "유효하지 않은 외국인 등록번호입니다.",()=>{$("#userArc1").focus()});
                    return;
                }
                if (!userRrnCheck(userArc1 + "" + userArc2)) {
                    modalEvent.warning("등록", "입력된 개인정보가 일치하지 않습니다",()=>{$("#userArc1").focus()});
                    return;
                }
            }*/
        }

        // 이메일 형식 검사
        // if (email && !regEmail.test(email)) {
        //     modalEvent.warning("등록", "유효하지 않은 이메일 형식입니다.",()=>{$("#email").focus()});
        //     return;
        // }

        modalEvent.info("등록", "고객 정보를 등록하시겠습니까?", function(){
            let formData = new FormData();
            formData.append("muUserId", muUserId);
            formData.append("menuClass", menuClass);
            formData.append("nationality", nationality);
            formData.append("nationalityCode", nationalityCode);
            formData.append("localYn", localYn);
            formData.append("userName", userName);
            formData.append("userRrn1", userRrn1);
            formData.append("userRrn2", userRrn2);
            formData.append("userPno", userPno);
            formData.append("userArc1", userArc1);
            formData.append("userArc2", userArc2);
            formData.append("phoneNumber", phoneNumber.replace(/-/g, ""));
            formData.append("phoneNumber2", phoneNumber2.replace(/-/g, ""));
            // formData.append("email", email);
            // formData.append("address", streetAddress);
            // formData.append("addressDetails", addressDetails);
            // formData.append("zipCode", zipCode);
            formData.append("gender", gender);
            formData.append("channel", channel);
            formData.append("channelCode", channelCode);
            formData.append("muGroupId", muGroupId);
            formData.append("memo", memo);
            formData.append("etc", etc);
            formData.append("birthday", birthday);
            formData.append("userTypeCode", userTypeCode);
            formData.append("userType", userType);
            formData.append("refusePhotoYn", refusePhotoYn);
            formData.append("smsYn", smsYn);
            // formData.append("emailYn", emailYn);
            formData.append("identification", identification);
            formData.append("introUserId", introUserId);

            $.ajax({
                url: encodeURI('/webuser/insertUser.do'),
                data: formData,
                dataType: "json",
                processData: false,
                contentType: false,
                type: 'POST',
                async:true,
                success: function(data){
                    if(data.msgCode=='0'){
                        modalEvent.success("성공", data.msgDesc, function(){
                            fn_leftFormAction2('020101','/webuser/selectListUserIntro.do');
                        });

                    }else{
                        modalEvent.danger("오류", data.msgDesc);
                    }
                },
                error : function(xhr, status, error) {
                    modalEvent.danger("등록 오류", "고객 등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
                },
                beforeSend: function () {
                },
                complete: function () {
                }
            });
        });
    },
    /*
     * 팝업
     * callback : 콜백함수, reqParam: 팝업파라미터
     */
    popup:function(callback, reqParam) {
        // 초기화 후 열기
        userInsertModal.init();

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

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

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

		setTimeout(function(){
			$('#userInsertModal').remove();
		},500);
    },
    HtmlTemplate :`
        <div id="userInsertModal" class="modal new_patient_modal fade" tabindex="-1" aria-labelledby="exampleModalLabel"
             aria-hidden="">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <p class="title">고객 등록</p>
                    </div>

                    <div class="modal-body">
                        <div class="form_box">
                            <div class="input_box essential">
                                <label>국적</label>
                                <div class="select_box dropdown">
                                    <button class="label" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">국적</button>
                                    <ul class="select_option_list dropdown-menu" id="nationality_pop">
                                    </ul>
                                </div>
                            </div>
                            <div class="input_box essential">
                                <label>고객명</label>
                                <input type="text" id="userName" placeholder="이름"/>
                            </div>
                            <div class="input_box">
                                <label>생년월일</label>
                                <input id="birthday" placeholder="연도-월-일"/>
                                <img class="userBirthday" src="/image/web/calendar.svg" alt="calendar">
                                <p class="identity txtAge" id="identity"></p>
                            </div>
                            <div class="input_box foreigner_box">
                                <label>식별정보</label>
                                <div class="select_box dropdown">
                                    <button class="label" type="button" data-toggle="dropdown" aria-haspopup="true"
                                            aria-expanded="false">여권번호
                                    </button>
                                    <ul class="select_option_list dropdown-menu" id="identification">
                                        <li class="option_list_item passport_number_option selected" id="pno">여권번호</li>
                                        <li class="option_list_item foreigner_number_option" id="arc">외국인등록번호</li>
                                    </ul>
                                </div>
                                <div class="passport_number_box">
                                    <div class="passport_number">
                                        <input id="userPno" type="text" placeholder="여권번호"/>
                                    </div>
                                </div>
                                <div class="foreigner_number_box">
                                    <input id="userArc1" type="text" placeholder="000000"/>
                                    <span class="slash">-</span>
                                    <input type="text" id="userArc2" placeholder="000000"/>
                                </div>
                            </div>
                            <div class="input_box local_box" id="rrn">
                                <label>주민등록번호</label>
                                <input id="userRrn1" type="text" placeholder="000000"/>
                                <span class="slash">-</span>
                                <input id="userRrn2" type="text" placeholder="000000"/>
                            </div>
                            <div class="input_box">
                                <label>성별</label>
                                <div class="gender">
                                    <input type="radio" name="gender" id="female" value="F"/>
                                    <label for="female" >여자</label>
                                </div>
                                <div class="gender">
                                    <input type="radio" name="gender" id="male" value="M"/>
                                    <label for="male">남자</label>
                                </div>
                            </div>
                            <div class="input_box">
                                <label>고객구분</label>
                                <div class="select_box dropdown">
                                    <button class="label" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">고객구분</button>
                                    <ul class="select_option_list dropdown-menu" id="userType_pop">
                                    </ul>
                                </div>
                            </div>
                            <div class="input_box two essential">
                                <div class="first essential">
                                    <label>연락처</label>
                                    <input id="phoneNumber" type="tel" placeholder="010-0000-0000"/>
                                </div>
                                <div>
                                    <label>보조연락처</label>
                                    <input id="phoneNumber2" type="tel" placeholder="010-0000-0000"/>
                                </div>
                            </div>
                            <!--<div class="input_box">
                                <label>이메일</label>
                                <input id="email" type="text" placeholder="이메일"/>
                            </div>
                            <div class="input_box">
                                <label>주소</label>
                                <input class="address" id="address" type="text" readonly="readonly"/>
                                <button class="address_btn" id="searchAddr" type="button">주소 찾기</button>
                                <input class="address_detail" id="addressDetails" type="text" placeholder=""/>
                            </div>-->
                            <div class="input_box">
                                <label>사진 거부</label>
                                <div class="gender">
                                    <input type="radio" name="modalRefusePhotoYn" id="modalRefusePhotoY" value="Y" checked/>
                                    <label for="modalRefusePhotoY">예</label>
                                </div>
                                <div class="gender">
                                    <input type="radio" name="modalRefusePhotoYn" id="modalRefusePhotoN" value="N"/>
                                    <label for="modalRefusePhotoN">아니오</label>
                                </div>
                            </div>
                            
                            <div class="input_box">
                                <label>SMS 수신여부</label>
                                <div class="gender">
                                    <input type="radio" name="modalSmsYn" id="modalSmsY" value="Y" checked/>
                                    <label for="modalSmsY">예</label>
                                </div>
                                <div class="gender">
                                    <input type="radio" name="modalSmsYn" id="modalSmsN" value="N"/>
                                    <label for="modalSmsN">아니오</label>
                                </div>
                            </div>

                            <p class="title">기타 정보</p>
                            <div class="input_box">
                                <label>관심진료</label>
                                <div class="select_box dropdown">
                                    <button class="label" type="button" data-toggle="dropdown" aria-haspopup="true"
                                            aria-expanded="false">관심진료 선택
                                    </button>
                                    <ul class="select_option_list dropdown-menu" id="treatment">
                                    </ul>
                                </div>
                            </div>
                            <div class="input_box two">
                                <div class="first">
                                    <label>방문경로</label>
                                    <div class="select_box dropdown">
                                        <button class="label" type="button" data-toggle="dropdown" aria-haspopup="true"
                                                aria-expanded="false">방문경로</button>
                                        <ul class="select_option_list dropdown-menu" id="channel">
                                        </ul>
                                    </div>
                                </div>
                                <div>
                                    <label>추천인</label>
                                    <div class="search_box" id="searchIntroUser">
                                        <button class="search_btn"><img src="../../../../image/web/search_B.svg" alt="search"/></button>
                                        <input type="text" id="recommendId" placeholder="추천인 검색" readonly>
                                    </div>
                                </div>
                            </div>
                            <div class="textarea_box">
                                <label>특이 사항</label>
                                <p class="explanation">*시술 및 약물 관련 특이사항 기록</p>
                                <textarea id="etc" placeholder="내용을 입력해주세요."></textarea>
                            </div>
                            <div class="textarea_box">
                                <label>고객 메모</label>
                                <textarea id="memo" placeholder="내용을 입력해주세요."></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <div class="btn_box">
                            <button type="button" class="cancel_btn btnCancle">취소</button>
                            <button type="button" class="registration_bth btnSave">등록</button>
                        </div>
                    </div>
                </div>
            </div>
            <script>
                $(document).ready(function() {
                    fn_selectListTreatmentOption();
                    fn_isForeignerEvent();
                    fn_clickEvent();
                    /*$('#userInsertModal .essential .select_box ul').each(function() {
                        this.querySelector('li:first-child')?.click();
                    });*/
                });
                document.getElementById('birthday').addEventListener('change',()=>{
                     calculateAge();
                });
                // document.getElementById('searchAddr').addEventListener('click',()=>{
                //      sample4_execDaumPostcode();
                // });
                
                document.getElementById("phoneNumber2").addEventListener("input", function(event) {
                    formatPhoneNumber(this);
                });
                
                document.getElementById("phoneNumber").addEventListener("input", function(event) {
                    formatPhoneNumber(this);
                });
                
                document.getElementById("userArc1").addEventListener("input", function(event) {
                    formatRrn1(this);
                });
                
                document.getElementById("userRrn1").addEventListener("input", function(event) {
                    formatRrn1(this);
                });
                document.getElementById("userRrn2").addEventListener("input", function(event) {formatRrn2(this)});
                
                document.getElementById("userArc2").addEventListener("input", function(event){formatRrn2(this)});
                
                document.getElementById("searchIntroUser").addEventListener("click", function(){listOpen();});
            </script>
        </div>`
};






