/****************************************************************************
 * 고객 정보 상세 조회
 ****************************************************************************/
//조회한 회원의 주민번호 뒷자리
let userArc2 = "";
let userRrn2 = "";
function fn_selectUser() {

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

    $.ajax({
        url: encodeURI('/webuser/selectUser.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async: true,
        success: function (data) {
            if (data.msgCode === '0') {
                // if('Y'===data.userDetail[0].userType2&&data.userDetail[0].userType){
                    //국적
                    let nationality = data.userDetail[0].nationality;
                    let nationalityName = data.userDetail[0].nationalityName;
                    let nationalityYn;
                    let localYn = true;

                    $('#nationality .option_list_item').each(function () {
                        if ($(this).attr('id') === "li_"+nationality) {
                            // 클래스 'selected' 추가 및 버튼 텍스트 업데이트
                            $(this).click();
                            nationalityYn=true;
                        }
                    });
                    if(!nationalityYn){
                        $("#nationality").parent().find('button').text(nationalityName);
                        $("#nationalityCd").val(nationality);
                    }
                    if(nationalityName){
                        localYn = nationalityName.toLowerCase().includes('한국'.toLowerCase())||
                                                nationalityName.toLowerCase().includes('KR'.toLowerCase())
                    }

                    if (localYn) {
                        // KR인 경우
                        $('.local_box').show();
                        $('.foreigner_box').hide();
                        if(data.userDetail[0].userRrn1){
                            document.getElementById('userRrn1').value = data.userDetail[0].userRrn1;
                        }
                        if(data.userDetail[0].userRrn2){
                            userRrn2 = data.userDetail[0].userRrn2;
                            document.getElementById('userRrn2').value = data.userDetail[0].userRrn2.charAt(0) + '*'.repeat(data.userDetail[0].userRrn2.length - 1);
                        }
                    } else {
                        $('.local_box').hide();
                        $('.foreigner_box').show();
                        if (data.userDetail[0].userPno) {
                            $('.passport_number_box').show();
                            $('.foreigner_number_box').hide();
                            document.getElementById('pno').classList.add('selected');
                            document.getElementById('arc').classList.remove('selected');
                            document.getElementById('userPno').value = data.userDetail[0].userPno;
                        } else {
                            $('.passport_number_box').hide();
                            $('.foreigner_number_box').show();
                            document.getElementById('pno').classList.remove('selected');
                            document.getElementById('arc').classList.add('selected');
                            if(data.userDetail[0].userArc1){
                                document.getElementById('userArc1').value = data.userDetail[0].userArc1;
                            }
                            if(data.userDetail[0].userArc2){
                                userArc2 = data.userDetail[0].userArc2;
                                document.getElementById('userArc2').value = data.userDetail[0].userArc2.charAt(0) + '*'.repeat(data.userDetail[0].userArc2.length - 1);
                            }
                        }
                        $("#identification").parent().find('button').text($("#identification .selected").text());
                    }
                // }
                // 방문경로
                let channel = data.userDetail[0].channel;
                    let channelYn;
                $('#channel .option_list_item').each(function () {
                    if ($(this).attr('id') === "li_"+channel) {
                        $(this).click();
                        channelYn=true;
                    }
                });
                if(!channelYn){
                    $("#channel").parent().find('button').text(data.userDetail[0].channelName);
                    $("#channelCd").val(channel);
                }
                $("#email").val(data.userDetail[0].email);
                $("#userNumber").text(data.userDetail[0].userNumber);
                $("#birthday").val(data.userDetail[0].birthday);
                $("#nationality").val(nationality);
                $("#userName").val(data.userDetail[0].userName);
                $("#address").val(
                     (data.userDetail && data.userDetail[0]
                        ? (data.userDetail[0].zipCode ? '(' + data.userDetail[0].zipCode + ') ' : '') + (data.userDetail[0].address || '')
                         : '')
                );
                $("#addressDetails").val(data.userDetail[0].addressDetails);
                $("#identity").text(data.userDetail[0].identity);
                $("#phoneNumber").val(fn_setFormatPhone(data.userDetail[0].phoneNumber??''));
                $("#phoneNumber2").val(fn_setFormatPhone(data.userDetail[0].phoneNumber2??''));
                if(data.userDetail[1]){
                   let recommendUserId = data.userDetail[1].userName+`(${fn_setFormatPhone(data.userDetail[1].phoneNumber)})`
                    $("#recommendUserId").val(recommendUserId);
                }
                $("#etc").val(data.userDetail[0].etc);
                $("#memo").val(data.userDetail[0].memo);

                $("#appUseYn").val(data.userDetail[0].appUseYn);
                $("#membershipAccount").val(data.userDetail[0].membershipAccount);
                $("#leaveDate").val(data.userDetail[0].leaveDate);
                $("#appIntroDate").val(data.userDetail[0].appIntroDate);

                //관심진료
                let muGroupId = data.userDetail[0].muGroupId;
                fn_selectListTreatmentOption(muGroupId);

                //고객 구분
                let type = data.userDetail[0].userType;
                $('#userType li').removeClass('selected');
                let typeYn;
                // 해당 userType에 맞는 li 요소를 찾아 selected 클래스 추가 및 버튼에 이미지 표시
                $('#userType li').each(function () {
                    if ($(this).attr('id') === "li_"+type) {
                        $(this).click();
                        typeYn=true;
                    }
                });
                if(!typeYn && data.userDetail[0].filePath){
                    let url = data.userDetail[0].filePath.replace("C:", "");
                    $("#userType").parent().find('button').html(`<img src="${url}">`);
                    $("#userTypeCd").val(type);
                }

                let gender = data.userDetail[0].gender;
                if("F" == gender){
                    $('#female').prop('checked', true);
                }else if("M" == gender){
                    $('#male').prop('checked', true);
                }
                let refusePhotoYn = data.userDetail[0].refusePhotoYn;
                refusePhotoYn == 'Y' ? $('#refusePhotoY').prop('checked', true) : $('#refusePhotoN').prop('checked', true);
                let smsYn = data.userDetail[0].smsYn;
                smsYn == 'Y' ? $('#smsY').prop('checked', true) : $('#smsN').prop('checked', true);
                let userPhysical = data.userPhysical;
                if (userPhysical.writeDate) {
                    // 신체 정보를 가져와서 HTML에 삽입
                    document.getElementById("regDt").innerText = userPhysical.writeDate +' 기준';
                    document.getElementById("height").innerText = (userPhysical.height || '-') + ' cm';
                    document.getElementById("weight").innerText = (userPhysical.weight || '-') + ' kg';
                    document.getElementById("muscle").innerText = (userPhysical.muscle || '-') + ' kg';
                    document.getElementById("fatMass").innerText = (userPhysical.fatMass || '-') + ' kg';
                    document.getElementById("fatPercent").innerText = (userPhysical.fatPercent || '-') + '%';
                    document.getElementById("bmi").innerText = (userPhysical.bmi || '-') + ' kg/m2';
                }
				console.log(data);
				$("#introName").val(data.userDetail[0].introName);
				$("#introName").val(data.userDetail[0].introName);
            } else {
                modalEvent.danger("조회 오류", data.msgDesc);
            }

        },
        error: function (xhr, status, error) {
            modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
        },
        beforeSend: function () {
        },
        complete: function () {
        }
    });
}/****************************************************************************
 * 추천인 팝업
 ****************************************************************************/
function listOpen(){
    let reqParam = {};
    userIntroSelectModal.popup(function (obj, reqParam) {
        document.getElementById('recommendUserId').dataset.userId=obj.muUserId;
        document.getElementById('recommendUserId').value = obj.userName+`(${obj.phoneNumber})`;
    }, reqParam);
}
/****************************************************************************
 * 고객 정보 수정
 ****************************************************************************/
function fn_updateUser() {
    let nationalitySelectYn         = $("#nationalityCd").length==0?"N":"Y";
    let nationalityCode             = "";
    let nationality                 = "";
    let nationalityName             = "";
    let localYn                     = "";
    if("Y" == nationalitySelectYn){
        nationalityCode             = $("#nationality").find("li.selected").data('code');
        nationality                 = $("#nationalityCd").val().split("_")[1];
        nationalityName             = $("#nationalityCd").parent().find('button').text();
        localYn                     = nationalityName.toLowerCase().includes('한국'.toLowerCase()) ||
                                      nationalityName.toLowerCase().includes('KR'.toLowerCase());
    }
    let userName                    = $("#userName").val().trim();
    let userRrn1                    = $("#userRrn1").val().trim();
    userRrn2                        =userRrn2?.trim();
    let userPno                     = $("#userPno").val().trim();
    let userArc1                    = $("#userArc1").val().trim();
    userArc2                        =userArc2?.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               = $("input[name='refusePhotoYn']:checked").val();
    let smsYn                       = $("input[name='smsYn']:checked").val();
    let gender                      = $("input[name='gender']:checked").val()==null?"":$("input[name='gender']:checked").val();
    let channelSelectYn             = $("#channelCd").length==0?"N":"Y";
    let channel                     = "";
    let channelCode                 = "";
    if("Y" == channelSelectYn){
        channelCode                 = $("#channel").find("li.selected").data('code');
        channel                     = $("#channelCd").val().split("_")[1];
    }
    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").length==0?"N":"Y";
    let userTypeCode                = "";
    let userType                    = "";
    if("Y" == userTypeCodeSelectYn){
        userTypeCode                = $("#userType").find("li.selected").data('code');
        userType                    = $("#userTypeCd").val().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('recommendUserId').dataset.userId??'';

    if ("Y" != updateUseYn) {
        modalEvent.warning("수정", "수정 권한이 없습니다.");
        return false;
    }

    console.log("nationalityCode : "+nationalityCode)
    console.log("nationality     : "+nationality)

    console.log("userTypeCode : "+userTypeCode)
    console.log("userType     : "+userType)

    console.log("channelCode : "+channelCode)
    console.log("channel     : "+channel)
    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(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("menuClass", menuClass);
        formData.append("muUserId", muUserId);
        formData.append("nationalityCode", nationalityCode);
        formData.append("nationality", nationality);
        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/updateUser.do'),
            data: formData,
            dataType: "json",
            processData: false,
            contentType: false,
            type: 'POST',
            async:true,
            success: function (data) {
                if ('0' == data.msgCode) {
                    modalEvent.success("성공", data.msgDesc,()=> {
                        fn_leftFormAction2(menuClass, '/webuser/selectListUserIntro.do');
                    });
                } else {
                    modalEvent.danger("오류", data.msgDesc);
                }
            },
            error: function (xhr, status, error) {
                modalEvent.danger("비활성화 오류", "비활성화 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            },
            beforeSend: function () {
            },
            complete: function () {
            },
        });
    });
}

document.getElementById("userRrn2").addEventListener("input", function (e) {
    const inputChar =  e.data?.replace(/\D/g, '');
    const backspace = e.inputType === "deleteContentBackward"; // 백스페이스 키 입력 여부


    if (backspace) {
        userRrn2 = userRrn2.slice(0, -1); // 마지막 문자 제거
    } else {
        userRrn2 += inputChar; // 입력된 문자 추가
    }
    if (userRrn2.length > 7) {
        userRrn2 = userRrn2.substring(0, 7);
    }
    // 입력값을 제외한 나머지를 *로 표시
    if(0<userRrn2.length)
        this.value = userRrn2.charAt(0) + '*'.repeat(userRrn2.length - 1);

    // 실제 값이 변경될 때마다 보이는 input의 커서 위치 조정
    this.setSelectionRange(this.value.length, this.value.length);

});

document.getElementById("userArc2").addEventListener("input", function (e) {
    const inputChar = e.data?.replace(/\D/g, '');
    const backspace = e.inputType === "deleteContentBackward";

    if (backspace) {
        userArc2 = userArc2.slice(0, -1);
    } else {
        userArc2 += inputChar;
    }
    if (userArc2.length > 7) {
        userArc2 = userArc2.substring(0, 7);
    }
    // 입력값을 제외한 나머지를 *로 표시
    if(0<userArc2.length)
        this.value = userArc2.charAt(0) + '*'.repeat(userArc2.length - 1);

    this.setSelectionRange(this.value.length, this.value.length);
});
function fn_setSelectBox(){
    let category=fn_selectCategoryList();
    for(let i = 0; i < 3; i++){
        let categoryCode     = category[i].categoryCode;
        fn_selectListOtherOption(categoryCode);
    }
}
function fn_pageInit(){
    fn_setSelectBox();
    fn_clickEvent();
    fn_selectUser();
    fn_isForeignerEvent();
}
document.getElementById('physicalInfoPage').addEventListener('click', () => {
    fn_leftFormAction2('0201010102', '/webuser/selectListUserPhysicalIntro.do?muUserId=' + muUserId);
});

document.getElementById('birthday').addEventListener('change',()=>{
    calculateAge();
});
document.getElementById('updateBtn').addEventListener('click',()=>{
    fn_updateUser();
});
// document.getElementById('searchAddr').addEventListener('click',()=>{
//     sample4_execDaumPostcode();
// });

document.getElementById("userArc1").addEventListener("input", function(event) {
    formatRrn1(this);
});

document.getElementById("userRrn1").addEventListener("input", function(event) {
    formatRrn1(this);
});

document.getElementById("phoneNumber2").addEventListener("input", function(event) {
    formatPhoneNumber(this);
});

document.getElementById("phoneNumber").addEventListener("input", function(event) {
    formatPhoneNumber(this);
});
document.getElementById("recommendUserId").addEventListener("click", function(){listOpen();});

$('#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);
    calculateAge();


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

$(function(){
    // 페이지 init
    fn_pageInit();
});