// Custom Table Logic
let treatmentList = [];

function renderTreatmentTable() {
    let tbody = document.getElementById("treatmentListBody");
    tbody.innerHTML = "";

    treatmentList.forEach((item, index) => {
        let row = document.createElement("tr");
        row.innerHTML = `
            <td><input type="checkbox" name="treatmentCheck" value="${index}"></td>
            <td style="text-align:left; padding-left:10px;">${item.treatmentProcedureName}</td>
            <td style="text-align:right;">${num2won(item.price)}</td>
            <td style="text-align:right;">${num2won(item.discountPrice)}</td>
        `;
        tbody.appendChild(row);
    });
}

function fn_checkAll(source) {
    let checkboxes = document.getElementsByName('treatmentCheck');
    for (var i = 0, n = checkboxes.length; i < n; i++) {
        checkboxes[i].checked = source.checked;
    }
}

/****************************************************************************
 * 이벤트 조회
 ****************************************************************************/
function fn_selectWebTreatmentPetit() {
    if (true != fn_emptyCheck(postNo)) {
        modalEvent.warning("수정", "이벤트 정보가 없습니다.");
        return;
    }
    let formData = new FormData();
    formData.append("menuClass", menuClass);
    formData.append("categoryDivCd", categoryDivCd);
    formData.append("categoryNo", categoryNo);
    formData.append("postNo", postNo);

    $.ajax({
        url: encodeURI('/contentsBbs/getContentsBbs.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async: true,
        success: function (rst) {
            if ('0' == rst.msgCode) {
                let data = rst.detail;
                $("select[name=category]").val(data.categoryNo).prop("selected", true);
                $("#categoryNo").val(data.categoryNo);
                $("#title").val(data.title);
                $("#content").val(data.content);
                $("#hashtag").val(data.hashtag);
                $("#thumbnailBottomTxt").val(data.thumbnailBottomTxt);
                $("#thumbnailImg").attr("src", CDN_URL + data.thumbnailImgPath);
                $("#contentsImg").attr("src", CDN_URL + data.contentImgPath);
                $("#oldCrmItemId").val(data.oldCrmItemId);
                $("#ordNo").val(data.ordNo);

                if (data.startDt) $("#eventStartDt").val(data.startDt);
                if (data.endDt) $("#eventEndDt").val(data.endDt);

                treatmentList = [];
                rst.treatmentList.forEach((item, i) => {
                    treatmentList.push({
                        treatmentProcedureName: item.treatmentProcedureName,
                        price: item.price,
                        discountPrice: item.discountPrice,
                        muTreatmentId: item.muTreatmentId,
                        muTreatmentProcedureId: item.muTreatmentProcedureId
                    });
                });
                renderTreatmentTable();
            }
            else {
                modalEvent.danger("수정 오류", eventData.msgDesc);
            }
        },
        error: function (xhr, status, error) {
            modalEvent.danger("수정 오류", "수정 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
        },
        beforeSend: function () {

        },
        complete: function () {

        }
    });
}

function num2won(x) {
    if (typeof x === 'undefined' || x === null) return '';
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}


/****************************************************************************
 * 이벤트 수정
 ****************************************************************************/
function fn_updateWebTreatmentPetit() {
    if ("Y" != insertUseYn) {
        modalEvent.warning("", "등록 권한이 없습니다.");
        return false;
    }

    let title = $("#title").val();
    let content = $("#content").val();
    let hashtag = $("#hashtag").val();
    let thumbnailBottomTxt = $("#thumbnailBottomTxt").val();
    let categoryNo = $("#categoryNo").val();

    var treatmentIdList = []; // muTreatmentId
    var treatmentProcedureIdList = []; // muTreatmentProcedureId

    treatmentList.forEach(item => {
        treatmentIdList.push(item.muTreatmentId);
        treatmentProcedureIdList.push(item.muTreatmentProcedureId);
    });

    let eventStartDt = $("#eventStartDt").val();
    let eventEndDt = $("#eventEndDt").val();
    let file = $("#file")[0].files[0];
    let content_file = $("#content_file")[0].files[0];

    if (true != fn_emptyCheck(categoryNo)) {
        modalEvent.warning("등록", "카테고리를 입력하세요.");
        return;
    }
    if (true != fn_emptyCheck(title)) {
        modalEvent.warning("등록", "제목을 입력하세요.");
        return;
    }

    modalEvent.info("수정", categorytitle + " 정보를 수정하시겠습니까?", function () {
        let formData = new FormData();
        formData.append("menuClass", menuClass);
        formData.append("categoryDivCd", categoryDivCd);
        formData.append("categoryNo", categoryNo);
        formData.append("postNo", postNo);
        formData.append("title", title);
        formData.append("content", content);
        formData.append("hashtag", hashtag);
        formData.append("thumbnailBottomTxt", thumbnailBottomTxt);
        formData.append("treatmentlist", treatmentIdList);
        formData.append("treatmentprocedurelist", treatmentProcedureIdList);
        formData.append("eventStartDt", eventStartDt);
        formData.append("eventEndDt", eventEndDt);
        formData.append("file", file);
        formData.append("content_file", content_file);
        formData.append("oldCrmItemId", $("#oldCrmItemId").val());
        formData.append("ordNo", $("#ordNo").val());

        $.ajax({
            url: encodeURI('/contentsBbs/modContentsBbs.do'),
            data: formData,
            dataType: "json",
            processData: false,
            contentType: false,
            type: 'POST',
            async: true,
            success: function (data) {
                if ('0' == data.msgCode) {
                    modalEvent.success("등록 성공", data.msgDesc, function () {
                        fn_selectListWebTreatmentPetitIntro();
                    });
                }
                else {
                    modalEvent.danger("등록 오류", data.msgDesc);
                }
            },
            error: function (xhr, status, error) {
                modalEvent.danger("등록 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            },
            beforeSend: function () {

            },
            complete: function () {

            }
        });
    });
}



/****************************************************************************
 * 썸네일 이미지 미리보기
 ****************************************************************************/
function fn_filePreview(width, height, obj) {
    let file = "";
    if (obj == '.img_box') {
        file = $("#file")[0].files[0];
    } else {
        file = $("#content_file")[0].files[0];
    }

    if (file) {
        $(obj).html('');
        const reader = new FileReader();

        reader.onload = function (e) {
            // 이미지 요소를 생성하고 미리보기 추가
            const img = document.createElement('img');
            img.src = e.target.result;
            img.style.width = width; // 원하는 크기로 조정
            img.style.height = height;
            $(obj).append(img);
        };

        // 파일을 읽기 시작
        reader.readAsDataURL(file);
    }
}
/****************************************************************************
 * 배너 이미지 삭제
 ****************************************************************************/
function fn_removePreview() {
    $("#file").val('');
    $('.img_box').html('');
}


/****************************************************************************
 * 배너 이미지 미리보기
 ****************************************************************************/
function fn_fileContentPreview() {
    const file = $("#content_file")[0].files[0];
    if (file) {
        $('.file_box').html(file.name);
    }
}
/****************************************************************************
 * 배너 이미지 삭제
 ****************************************************************************/
function fn_removeContentPreview() {
    $("#content_file").val('');
    $('.file_box').html('');
}

/****************************************************************************
 * 리스트 화면으로 이동.
 ****************************************************************************/
function fn_selectListWebTreatmentPetitIntro() {
    if ("Y" == selectUseYn) {
        let pagingParam = "?menuClass=" + menuClass;
        pagingParam += "&categoryDivCd=" + categoryDivCd;
        fn_leftFormAction("/contentsBbs/moveContentsBbsList.do" + pagingParam);
    } else {
        modalEvent.warning("", "조회 권한이 없습니다.");
        return false;
    }
}

/****************************************************************************
 * 페이지 init
 ****************************************************************************/
function fn_pageInit() {
    // 날짜 datepicker (jQuery UI)
    $("#eventStartDt, #eventEndDt").datepicker({
        dateFormat: 'yy-mm-dd',
        prevText: '이전 달',
        nextText: '다음 달',
        monthNames: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
        monthNamesShort: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
        dayNames: ['일', '월', '화', '수', '목', '금', '토'],
        dayNamesShort: ['일', '월', '화', '수', '목', '금', '토'],
        dayNamesMin: ['일', '월', '화', '수', '목', '금', '토'],
        showMonthAfterYear: true,
        yearSuffix: '년',
        changeMonth: true,
        changeYear: true
    });

    if (categoryDivCd === '02' || categoryDivCd === '04') {
        $("#dateSelectionRow").show();
    }

    fn_selectWebTreatmentPetit();
}

/****************************************************************************
 * 페이지 event
 ****************************************************************************/
function fn_pageEvent() {
    // 검색 input
    $('.btnCancle').on("click", function () {
        fn_selectListWebTreatmentPetitIntro();
    });

    $('.btnSave').on("click", function () {
        fn_updateWebTreatmentPetit();
    });
    $('#delete_btn').on("click", function () {
        fn_removePreview();
    });

    $('#file').on('change', function (e) {
        fn_filePreview('800px', '450px', '.img_box');
    })
    $('#content_delete_btn').on("click", function () {
        fn_removeContentPreview();
    });
    $('#content_file').on('change', function (e) {
        fn_filePreview('100%', '100%', '.file_box');
    })

}

/****************************************************************************
 * 시술 목록 팝업
 ****************************************************************************/
function listOpen() {
    let reqParam = {};
    treatmentSelectModal.popup(function (obj, reqParam) {

        let isDuplicate = false;
        treatmentList.forEach((item) => {
            if (item.muTreatmentProcedureId == obj.treatmentProcedureId) {
                isDuplicate = true;
            }
        });

        if (isDuplicate) {
            modalEvent.warning("", "이미 시술정보가 있습니다.");
            return;
        }

        let newItem = {
            treatmentProcedureName: obj.treatmentNm,
            price: obj.price,
            discountPrice: obj.discountPrice,
            muTreatmentId: obj.treatmentId,
            muTreatmentProcedureId: obj.treatmentProcedureId
        };
        treatmentList.push(newItem);
        renderTreatmentTable();

    }, reqParam);
}
function fn_removeRow() {
    let checkboxes = document.getElementsByName('treatmentCheck');
    let indicesToRemove = [];

    // Collect indices checking from end to start to maintain index validity
    for (let i = checkboxes.length - 1; i >= 0; i--) {
        if (checkboxes[i].checked) {
            indicesToRemove.push(parseInt(checkboxes[i].value));
        }
    }

    if (indicesToRemove.length === 0) {
        modalEvent.warning("", "삭제할 항목을 선택해주세요.");
        return;
    }

    // Remove items
    indicesToRemove.forEach(index => {
        treatmentList.splice(index, 1);
    });

    // Uncheck "all" checkbox if checked
    document.getElementById("checkAll").checked = false;

    renderTreatmentTable();
}


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

    // 페이지 event
    fn_pageEvent();
});

/* =========================================
   PREVIEW LOGIC
   ========================================= */
function fn_openPreview() {
    let url = "/contentsBbs/contentsBbsPreview.do";
    window.open(url, "preview", "width=1280,height=900,scrollbars=yes");
}

function getTreatmentListForPreview() {
    return treatmentList;
}