function getDataAsync(url, method, param, args, successFunc, errorFunc ) {
    $.ajax({
        url    : url,
        method : method,
        dataType : 'JSON',
        data : param,
        success : function (req) {
            if (successFunc) {
                successFunc(req, args);
            }
        },
        error : function (request, status, error) {
            if (errorFunc) {
                errorFunc(request, status, error);
            }
            else {
                if (error.responseJSON) {
                    // 400: Bad Request
                    // 404: Not Found
                    // 417, Expectation Failed
                    let errorObj = error.responseJSON;
                    if (errorObj.status !== 404) {
                        sendErrorMsg(error);
                    }
                }
            }
        }
    });
}

function sendErrorMsg(error) {
    const jsonError = error.responseJSON;
    const timestamp = jsonError.timestamp.replace(/T/g, " ").substring(0, 19);
    const message = `<div class="error-message">
                          <div class="top">
                              <div>발생시각 : </div>
                              <div>${timestamp}</div>
                              <div>상태 : ${jsonError.status}</div>
                          </div>
                          <div>
                              <div>에러명 : </div>
                              <div>${jsonError.title}</div>
                          </div>
                          <div>
                              <div>내용 : </div>
                              <div>${jsonError.message}</div>
                          </div>
                          <div>
                              <div>경로 : </div>
                              <div>${jsonError.path}</div>
                          </div>
                          <div>
                              <div>에러 : </div>
                              <div>${jsonError.errors}</div>
                          </div>
                   </div>`
    alertError(message, "작업 실행 중 오류가 발생하였습니다.");
}


function alertError(AMessage, ATitle, id) {
    return alertMessage("red", AMessage, ATitle, id);
}

function alertWarning(AMessage, ATitle, id) {
    //return alertMessage("fa fa-asterisk", "blue", "btn-blue", AMessage, ATitle, id);
    return alertMessage("fa fa-warning", "red", "red", "btn-red", AMessage, ATitle, id);
}

function alertConfirm(AMessage, ATitle, id) {
    return alertMessage(
        "fa fa-info-circle dx-theme-accent-as-text-color",
        "blue dx-theme-accent-as-border-color",
        "dx-theme-accent-as-text-color",
        "btn-blue dx-theme-accent-as-background-color",
        AMessage,
        ATitle,
        id
    );
}

function alertMessage(type, AMessage, ATitle, id, confirmMethod) {

    const alertModal = $('.modal.alert');
    if (alertModal[0]) {
        alertModal.remove();
    }

    let str = `<div class="modal alert">
                    <div class="alert-modal ${type}">
                        <div class="title">
                            <div></div>
                            <div>${ATitle}</div>
                            <div onclick="closeModal('.modal.alert')"></div>
                        </div>
                        <div class="content">
                            ${AMessage}
                        </div>
                        <div class="button-box">
                            <input type="button" id="confirm-button" value="확인" class="button ${type}">`;
                 if(confirmMethod) {
                     str+= `<input type="button" id="cancel-button" class="button" value="취소" onclick="closeModal('.modal.alert')">`;
                 }
                 str +=`</div>
                    </div>
               </div>`;
    const modal = $(str);
    $('body').append(modal);
    modal.css('display', 'flex');
    const confirmBtn = $('#confirm-button');
    confirmBtn.focus();
    confirmBtn.on('click', ()=>{
        closeModal('.modal.alert')
        if (confirmMethod) {
            confirmMethod();
        }
        if (id) {
            id.focus();
        }
    });
}
function confirmMessage(AMessage, ATitle) {
    const title = ATitle ?? document.title;
    const message = AMessage;
    const ok = new $.Deferred();
    $.alert({
        useBootstrap: false,
        title: title,
        titleClass: "dx-theme-accent-as-text-color",
        content: message, //theme: "dark",
        type: "blue dx-theme-accent-as-border-color",
        typeAnimated: true,
        columnClass: "small",
        icon: "fa fa-check dx-theme-accent-as-text-color",
        // closeIcon: true,
        closeIcon: "cancel",
        closeIconClass: "fa fa-close dx-theme-accent-as-text-color",
        draggable: true,
        escapeKey: false,
        backgroundDismiss: false,
        backgroundDismissAnimation: "glow",
        buttons: {
            close: {
                text: " 확 인 ",
                btnClass: "btn-blue dx-theme-accent-as-background-color",
                action: function () {
                    ok.resolve(true);
                },
            },
            cancel: {
                text: " 취 소 ", //btnClass: "btn-blue",
                action: function () {
                    ok.resolve(false);
                },
            },
        },
    });
    return ok.promise();
}


function textFormat(text) {
    return isNull(text) ? '-' : text;
}

function isNull(value) {
    if (value === null || value === "" || value === undefined) {
        return true;
    }

    if (value.toString().trim() === "") {
        return true;
    }
    return false;
}

function moveNoticeView(boarNo, isAdmin) {
    getDataAsync("/api/notice/update-read-count/" +boarNo, "POST", null, null, (jsonData)=>{
        if (jsonData) {
            let page = '/notice/view/';
            if (isAdmin) page = '/phits/notice-view/';
            window.location.href = page + boarNo;
        }
        else {
            moveNoticeView(boarNo);
        }
    }, null);
}

function dateFormatter(date) {
    let year  = date.getFullYear().toString();
    let month = date.getMonth() + 1;
    let day   = date.getDate();
    month = month < 10 ? "0" + month : month;
    day   = day < 10 ? "0" + day : day;
    return year + month + day;
}

function getCookie(name) {
    let matches = document.cookie.match(new RegExp(
        "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
    ));
    return matches ? decodeURIComponent(matches[1]) : undefined;
}

function setCookie(name, value, options = {}) {

    options = {
        path: '/', // 경로 지정
        ...options // 아규먼트로 옵션을 넘겨줬을경우 전개연산자로 추가 갱신
    };

    if (options.expires instanceof Date) {
        options.expires = options.expires.toUTCString(); // 생 Date 객체라면 형식에 맞게 인코딩
    }

    let updatedCookie = encodeURIComponent(name) + "=" + encodeURIComponent(value);

    for (let optionKey in options) {
        updatedCookie += "; " + optionKey;
        let optionValue = options[optionKey];
        if (optionValue !== true) { // 밸류가 없다면
            updatedCookie += "=" + optionValue;
        }
    }
    document.cookie = updatedCookie; // 새로 갱신
}

function closePopup(popupId) {
    const isChecked = $('#popup_check_' + popupId).is(':checked');
    if (isChecked) {
        let expire = new Date();
        expire.setDate(expire.getDate() + 1);
        setCookie('p_'+ popupId , 'N', {expires : expire});
    }
    $('#popup_' + popupId).css('display', 'none');
}

function menuOpen() {
    let isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    let display = 'flex';
    if (isMobile) {
        if ($(window).width() <= 450) {
            display = 'block';
        }
    }
    $('header #menu-modal').css('display', display);
}

window.addEventListener(`resize`, function () {
    const display = $('header #menu-modal').css('display');
    if (display === 'flex' || display === 'block') {
        if ($(window).width() <= 450) {
            $('header #menu-modal').css('display', 'block');
        } else {
            $('header #menu-modal').css('display', 'flex');
        }
    }

});

function closeModal(target) {
    $(target).css('display', 'none');
}

function openBusSite(ord) {
    const urlArr = [
        'https://www.pohang.go.kr/bis/busRoute.do',
        'https://www.pohang.go.kr/bis/busStation.do',
        'https://www.pohang.go.kr/dept/contents.do?mid=0505020100',
    ];
    window.open(urlArr[ord], '_blank', "noopener noreferrer")
}

function movePath(uri) {
    window.location.href = uri;
}

function openModal(target) {
    $(target).css('display', 'flex');
    $(target + " .content").scrollTop(0);
}