/* 페이징 관련 변수 */
let userTotalCount   = 0;
let userTotalPages   = 0;


let userAgGridData = [];
let muUserData=[];

/****************************************************************************
 * 페이징 리셋
 ****************************************************************************/
function fn_userPaginReset(){
    userSearchKeywordParam      = '';
    search_nationality          ='';
    search_userType             ='';
    search_membershipYn         ='';
    userStart                   = 0;
    userLimit                   = 500;
    userTotalCount              = 0;
    userTotalPages              = 0;
    userSort                    = '';

    //페이징 초기화
    if($("#userPagination").data("twbs-pagination")){
        $("#userPagination").twbsPagination("destroy");
    }
}
/****************************************************************************
 * 관심진료 조회
 ****************************************************************************/
function fn_selectListTreatmentOption(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';
                        $("#treatment").parent().find('button').text(treatmentName);
                    }

                    listHTML += `<li class="option_list_item ${selectedYn}" id="${treatmentId}">${treatmentName}</li>`;
                }
                $("#treatment").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(){
        }
    });
}
/****************************************************************************
 * 검색필터 조회
 ****************************************************************************/
function fn_selectCategoryList(){
    let result = []
    let formData = new FormData();
    formData.append("menuClass", menuClass);
    $.ajax({
        url: encodeURI('/webcategory/selectCategoryList.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){
                    result = data.rows;
                }
            }
            else{
                modalEvent.danger("조회 오류", data.msgDesc);
            }
        },
        error : function(xhr, status, error) {
            modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
        },
        beforeSend:function(){

        },
        complete:function(){

        }
    });
    return result;
}
function fn_selectListOtherOption(categoryCode){
    let formData = new FormData();
    formData.append('categoryCode',categoryCode);
    $.ajax({
        url: encodeURI('/webcategory/selectCategoryItem.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async: false,
        success: function(data){
            if('0'==data.msgCode){
                let listHTML = '';
                if (0 < Object.keys(data.rows).length) {
                    let categoryName = '';
                    $('.select_box button').each(function() {
                        categoryName = $(this).text();
                        if (Object.values(data.rows).some(item => item.categoryName === categoryName)) {
                            let ulElement = $(this).parent().find('ul');
						    ulElement.html('');

                            Object.values(data.rows).forEach(categoryItem => {
                                if (categoryItem.categoryName === categoryName) {
                                    let categoryItemCode = categoryItem.categoryItemCode;
                                    let categoryItemName = categoryItem.categoryItemName;
                                    let nationality = '';

                                    if (categoryItem.categoryName === '국적') {
									    nationality = categoryItemName.toLowerCase().includes('한국'.toLowerCase()) ? 'local' : 'foreigner';
                                    } else if (categoryItem.categoryName === '고객구분') {
									    let url = categoryItem.filePath.replace("C:", "");
                                        categoryItemName = `<img src="${url}">`;
										ulElement.html('<li class="option_list_item" data-code="" id="li_">선택안함</li>');
                                    }

                                    let listHTML = `<li class="option_list_item ${nationality}" data-code="${categoryCode}" id="li_${categoryItemCode}">${categoryItemName}</li>`;
                                    ulElement.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(){
        }
    });
}
/****************************************************************************
 * 모달 검색필터 조회
 ****************************************************************************/
function fn_selectModalOtherOption(categoryCode){
    let formData = new FormData();
    formData.append('categoryCode',categoryCode);
    $.ajax({
        url: encodeURI('/webcategory/selectCategoryItem.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async: false,
        success: function(data){
            if('0'==data.msgCode){
                let listHTML = '';
                if (0 < Object.keys(data.rows).length) {
                    Object.keys(data.rows).forEach(category => {
                        // for(let i = 0; i < data.rows[key].length; i++){
                        let categoryItem = data.rows[category];
                        let categoryItemCode = categoryItem.categoryItemCode;
                        let categoryItemName = categoryItem.categoryItemName;

                        let selectedYn = '';
                        let nationality = '';

                        if(categoryItem.categoryName === '국적') {
                             nationality = categoryItemName.toLowerCase().includes('한국'.toLowerCase()) ? 'local' : 'foreigner';
                        }
                        if(categoryItem.filePath){
                            let url = categoryItem.filePath.replace("C:", "");
                            categoryItemName = `<img src="${url}">`
                        }
                        listHTML = `<li class="option_list_item ${nationality}" data-code="${categoryCode}" id="${categoryItemCode}">${categoryItemName}</li>`;
                        let categoryName = categoryItem.categoryName;
                        $('.select_box button').each(function() {
                            if ($(this).text() === categoryName) {
                                $(this).parent().find('ul').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(){
        }
    });
}

function fn_setSelectBox(num){
    let category=fn_selectCategoryList();
    for(let i = 0; i < num; i++){
        let categoryCode     = category[i].categoryCode;
        if(num>2){
            fn_selectModalOtherOption(categoryCode)
        }else{
            fn_selectListOtherOption(categoryCode);
        }
    }
}

/****************************************************************************
 * 옵션선택
 ****************************************************************************/
function fn_OptionSelection(target,e) {
    // 옵션 선택 이벤트 핸들러
    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();

}
/****************************************************************************
 * 주민번호, 외국인 등록번호 및 생년월일, 성별 유효성검사
 ****************************************************************************/
function userRrnCheck(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('input[name="gender"]:checked').value; // 성별 입력값 ('M' 또는 'F')
    let birthDateInput = document.getElementById('birthday').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;
    }
}
/****************************************************************************
 * 캘린더 날짜 변경 시 만나이 계산
 ****************************************************************************/
function calculateAge() {
    let birthday = document.getElementById('birthday').value;
    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--;
    }

    document.getElementById('identity').textContent = `만 ${age}세`;
}
/****************************************************************************
 * select box 선택 이벤트
 ****************************************************************************/
function fn_clickSelectBox(target) {
    $(target).find('.select_option_list').toggle();
}

function fn_clickEvent() {
    // $('.select_box').off('click');
     //$(document).off('click');

    // $('.select_box').on('click', function () {
    //     $('.select_box').not(this).find('.select_option_list').hide();
    //     fn_clickSelectBox($(this));
    // });
    // 옵션 선택 이벤트
    $('.select_box').on('click', 'li', function (e) {
        fn_OptionSelection($(this), e);
    });

   // 다른 곳을 클릭했을 때 옵션 숨기기
   //  $(document).on('click', function (event) {
   //      if (!$(event.target).closest('.select_box').length) {
   //          $('.user .select_option_list').hide();
   //      }
   //  });
}

/****************************************************************************
 * 휴대폰 번호, 주민번호 숫자입력 제한
 ****************************************************************************/
function formatPhoneNumber(inputElement) {
    // 입력된 키가 숫자가 아닌 경우 입력을 막음
    inputElement.value = inputElement.value.replace(/\D/g, '');
    let phoneNumber = inputElement.value;

    if (phoneNumber.length > 11) {
        inputElement.value = phoneNumber.substring(0, 11)
    }
    inputElement.value = fn_setFormatPhone(phoneNumber);
}

function formatRrn1(inputElement) {
    // 입력된 키가 숫자가 아닌 경우 입력을 막음
    inputElement.value = inputElement.value.replace(/\D/g, '');
    let Rrn1 = inputElement.value;

    if (Rrn1.length > 6) {
        inputElement.value=Rrn1.substring(0, 6)
    }
}
function formatRrn2(inputElement) {
    inputElement.value = inputElement.value.replace(/\D/g, '');
    let Rrn1 = inputElement.value;

    if (Rrn1.length > 7) {
        inputElement.value=Rrn1.substring(0, 7)
    }
}

/****************************************************************************
 * 주소 검색
 ****************************************************************************/
function sample4_execDaumPostcode() {
    new daum.Postcode({
        oncomplete: function (data) {
            let roadAddr = data.roadAddress; // 도로명 주소 변수
            // 우편번호와 주소 정보를 해당 필드에 넣는다.
            $("#address").val('(' + data.zonecode + ')' + (roadAddr ? roadAddr : data.jibunAddress));

            // 참고항목 문자열이 있을 경우 해당 필드에 넣는다.
            document.getElementById("addressDetails").value = '';
            document.getElementById("addressDetails").focus();
        }
    }).open();
}
/****************************************************************************
 * 국적선텍에 따른 여권번호/외국인 번호 활성화 event
 ****************************************************************************/
function fn_isForeignerEvent(){

    document.querySelectorAll('.local').forEach(element => {
        element.addEventListener('click', function () {
            document.querySelectorAll('.local_box').forEach(box => box.style.display = 'block');
            document.querySelectorAll('.foreigner_box').forEach(box => box.style.display = 'none');
        });
    });

    document.querySelectorAll('.foreigner').forEach(element => {
        element.addEventListener('click', function () {
            document.querySelectorAll('.local_box').forEach(box => box.style.display = 'none');
            document.querySelectorAll('.foreigner_box').forEach(box => box.style.display = 'block');
        });
    });

    document.querySelectorAll('.passport_number_option').forEach(element => {
        element.addEventListener('click', function () {
            document.querySelectorAll('.foreigner_number_box').forEach(box => {
                box.style.display = 'none';
                box.querySelector('input').value = '';
            });
            document.querySelectorAll('.passport_number_box').forEach(box => box.style.display = 'block');
        });
    });

    document.querySelectorAll('.foreigner_number_option').forEach(element => {
        element.addEventListener('click', function () {
            document.querySelectorAll('.passport_number_box').forEach(box => {
                box.style.display = 'none';
                box.querySelector('input').value = '';
            });
            document.querySelectorAll('.foreigner_number_box').forEach(box => box.style.display = 'block');
        });
    });
}
