/* 페이징 관련 변수 */
let procedureReviewTotalCount = 0;
let procedureReviewTotalPages = 0;

/*aggird*/
let procedureReviewAgGridData = [];

let procedureReviewSelectId = "";
let procedureReviewSelectCategoryNo = "";

/****************************************************************************
 * 시술후기 정보 리스트 조회
 ****************************************************************************/
function fn_selectListProcedureReviewJson() {
    let paramData = {
        "menuClass": menuClass,
        "categoryDivCd": categoryDivCd,
        "title": title,
        "writeName": writeName,
        "sort": sort,
        "dir": dir,
        "start": start,
        "limit": limit,
        "startDate": startDate,
        "endDate": endDate,
        "dateType": dateType
    };

    $.ajax({
        url: encodeURI('/procedureReview/getProcedureReviewList.do'),
        data: JSON.stringify(paramData),
        dataType: "json",
        contentType: "application/json",
        type: 'POST',
        async: true,
        success: function (data) {
            if ('0' == data.msgCode) {
                // 페이징 처리
                procedureReviewTotalCount = data.totalCount;

                procedureReviewTotalPages = Math.ceil(procedureReviewTotalCount / limit);

                // 리스트 조회
                procedureReviewAgGridData = data.rows;
                procedureReviewGridOptions.api.setRowData(procedureReviewAgGridData);

                if (0 < data.rows.length) {
                    //페이징 처리
                    window.pagObj = $('#procedureReviewPagination').twbsPagination({
                        startPage: ((start / limit) + 1),
                        totalPages: (procedureReviewTotalPages == 0) ? 1 : procedureReviewTotalPages,
                        visiblePages: 10,
                        initiateStartPageClick: false,
                        prev: '<img src="/image/web/page_navigation_arrow.svg" alt="prev"/>',
                        next: '<img src="/image/web/page_navigation_arrow.svg" alt="next"/>',
                        first: '',
                        last: '',
                        onPageClick: function (event, page) {
                            fn_procedureReviewPagination(page);
                        }
                    }).on('page', function (event, page) {
                    });
                }
            }
            else {
                modalEvent.danger("조회 오류", data.msgDesc);
            }
        },
        error: function (xhr, status, error) {
            modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
        },
        beforeSend: function () {
            // 로딩열기
            procedureReviewGridOptions.api.showLoadingOverlay();
        },
        complete: function () {

        }
    });
}

/****************************************************************************
 * 검색하기
 ****************************************************************************/
function fn_procedureReviewSearch(param) {
    if ("A" != param && "Y" != selectUseYn) {
        modalEvent.warning("", "조회 권한이 없습니다.");
        return false;
    }

    fn_procedureReviewPaginReset();

    categoryDivCd = $("#procedureReviewSearchCategory").val();
    title = $("#titleSearch").val();
    writeName = ""; // 작성자 검색 제거

    dateType = $("#dateType").val();
    startDate = $("#startDate").val();
    endDate = $("#endDate").val();

    fn_selectListProcedureReviewJson();
}


/****************************************************************************
 * 초기화하기
 ****************************************************************************/
function fn_procedureReviewReset() {
    $("#procedureReviewSearchCategory").val("");
    $("#titleSearch").val("");

    fn_procedureReviewSearch();
}

/****************************************************************************
 * 페이징 처리
 ****************************************************************************/
function fn_procedureReviewPagination(param) {
    start = (parseInt(param) - 1) * limit;

    fn_selectListProcedureReviewJson();
}

/****************************************************************************
 * 페이징 리셋
 ****************************************************************************/
function fn_procedureReviewPaginReset() {
    title = '';
    writeName = '';

    start = 0;
    limit = 100;
    procedureReviewTotalCount = 0;
    procedureReviewTotalPages = 0;

    //페이징 초기화
    if ($("#procedureReviewPagination").data("twbs-pagination")) {
        $("#procedureReviewPagination").twbsPagination("destroy");
    }
}

/****************************************************************************
 * 시술후기 삭제
 ****************************************************************************/
function fn_deleteProcedureReview() {
    if ("Y" != deleteUseYn) {
        modalEvent.warning("", "삭제 권한이 없습니다.");
        return false;
    }

    if (!procedureReviewSelectId) {
        modalEvent.warning("", "삭제할 대상을 선택하세요.");
        return false;
    }

    modalEvent.info("삭제", "선택한 시술후기 정보를 삭제하시겠습니까?", function () {
        let paramData = {
            "menuClass": menuClass,
            "muProcedureReviewId": procedureReviewSelectId
        };

        $.ajax({
            url: encodeURI('/procedureReview/delProcedureReview.do'),
            data: JSON.stringify(paramData),
            dataType: "json",
            contentType: "application/json",
            type: 'POST',
            async: true,
            success: function (data) {
                if ('0' == data.msgCode) {
                    modalEvent.success("삭제 성공", data.msgDesc, function () {
                        fn_procedureReviewOk();
                    });
                }
                else {
                    modalEvent.danger("삭제 오류", data.msgDesc);
                }
            },
            error: function (xhr, status, error) {
                modalEvent.danger("삭제 오류", "삭제 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            },
            beforeSend: function () {

            },
            complete: function () {

            }
        });
    });
}

/****************************************************************************
 * 검색 엔터 시술후기
 ****************************************************************************/
function fn_procedureReviewEnter(e) {
    if (e.which) {
        if (13 == e.which) {
            fn_procedureReviewSearch();
        }
    }
    else {
        if (13 == e.keyCode) {
            fn_procedureReviewSearch();
        }
    }
}

/****************************************************************************
 * 완료
 ****************************************************************************/
function fn_procedureReviewOk() {
    fn_procedureReviewReset();
}

/****************************************************************************
 * 등록 화면으로 이동.
 ****************************************************************************/
function fn_insertProcedureReviewIntro() {
    if ("Y" == insertUseYn) {
        let pagingParam = "?menuClass=" + menuClass;
        pagingParam += "&categoryDivCd=" + categoryDivCd;
        pagingParam += "&title=" + title;
        fn_leftFormAction("/procedureReview/moveProcedureReviewInsert.do" + pagingParam);
    } else {
        modalEvent.warning("", "등록 권한이 없습니다.");
        return false;
    }

}

/****************************************************************************
 * 수정 화면으로 이동.
 ****************************************************************************/
function fn_updateProcedureReviewIntro(muProcedureReviewId) {
    if ("Y" == updateUseYn) {
        let pagingParam = "?menuClass=" + menuClass;
        pagingParam += "&categoryDivCd=" + categoryDivCd;
        pagingParam += "&title=" + title;
        pagingParam += "&muProcedureReviewId=" + muProcedureReviewId;
        fn_leftFormAction("/procedureReview/moveProcedureReviewUpdate.do" + pagingParam);
    } else {
        modalEvent.warning("", "수정 권한이 없습니다.");
        return false;
    }
}


let procedureReviewColumnDefs = [
    { field: "checkbox", headerName: "", minWidth: 55, maxWidth: 55, headerCheckboxSelection: true, checkboxSelection: true },
    { field: "rowNum", headerName: "번호", minWidth: 60, maxWidth: 60, sortable: false, cellStyle: { textAlign: 'center' } },
    {
        field: "categoryDivCd", headerName: "구분", minWidth: 100, maxWidth: 120, cellStyle: { textAlign: 'center' }, valueFormatter: function (params) {
            if (params.value == '07') return '다이어트 센터';
            if (params.value == '08') return '쁘띠 센터';
            return params.value;
        }
    },
    { field: "title", headerName: "제목", minWidth: 150, cellStyle: { cursor: 'pointer', color: '#3985EA' } },
    {
        field: "content",
        headerName: "내용요약",
        minWidth: 150,
        valueFormatter: function (params) {
            let val = params.value;
            if (!val) return "";

            try {
                let delta = JSON.parse(val);
                if (typeof delta === 'string') {
                    delta = JSON.parse(delta);
                }

                if (delta && delta.ops) {
                    let text = "";
                    delta.ops.forEach(function (op) {
                        if (op.insert) {
                            if (typeof op.insert === 'string') text += op.insert;
                            else if (op.insert.image) text += "[이미지] ";
                        }
                    });
                    return text.replace(/\n/g, ' ').trim();
                }
            } catch (e) {
                // Fallback to strip HTML
            }
            return String(val).replace(/<[^>]*>?/gm, '').replace(/\n/g, ' ').trim();
        }
    },
    { field: "hashtag", headerName: "해시태그", minWidth: 150 },
    { field: "writeDate", headerName: "등록일", minWidth: 100, maxWidth: 150 },
    { field: "writeName", headerName: "작성자", minWidth: 100, maxWidth: 150 },
];

let procedureReviewGridOptions = {
    suppressRowTransform: true,
    columnDefs: procedureReviewColumnDefs,
    defaultColDef: {
        flex: 1,
        sortable: true,
        resizable: true,
        editable: true,
        cellStyle: { textAlign: 'left', fontSize: '14px', padding: '0' },
        enablePivot: true,
        enableValue: true
    },
    headerHeight: 41,
    rowHeight: 41,
    rowData: procedureReviewAgGridData,
    suppressRowClickSelection: true,
    localeText: {
        noRowsToShow: '조회 결과가 없습니다.'
    },
    rowSelection: 'multiple',
    debug: false,
    onCellClicked: function (event) {
        if ('title' == event.column.colId) {
            fn_updateProcedureReviewIntro(event.data.muProcedureReviewId);
        }
    },
    onSelectionChanged: function (event) {
        let selectRows = [];
        selectRows = event.api.getSelectedRows();

        procedureReviewSelectId = '';
        for (let i = 0; i < selectRows.length; i++) {
            procedureReviewSelectId += selectRows[i].muProcedureReviewId + ",";
        }
        procedureReviewSelectId = procedureReviewSelectId.substring(0, procedureReviewSelectId.lastIndexOf(','));
    },
    onSortChanged: function (event) {
        sort = '';
        let columnArr = event.columnApi.getColumnState();
        if (0 < columnArr.length) {
            columnArr.sort(function (a, b) {
                return a.sortIndex - b.sortIndex;
            });

            let nullCnt = 0;
            for (let i = 0; i < columnArr.length; i++) {
                let gridSortModel = columnArr[i].colId;
                let gridSort = columnArr[i].sort;

                if (gridSort != null) {
                    start = 0;
                    sort += gridSortModel + ' ' + gridSort + ',';
                }
                else {
                    nullCnt++;
                    if (nullCnt == columnArr.length) {
                        sort = '';
                        dir = '';
                        start = 0;
                    }
                }
            }
        }
        sort = sort.substring(0, sort.lastIndexOf(","));

        fn_procedureReviewSearch();
    }
};

let procedureReviewGridDiv = document.querySelector('#procedureReviewGrid');
new agGrid.Grid(procedureReviewGridDiv, procedureReviewGridOptions);


/****************************************************************************
 * 페이지 init
 ****************************************************************************/
function fn_pageInit() {
    if (!startDate && !endDate) {
    } else {
        $("#startDate").val(startDate).trigger("change");
        $("#endDate").val(endDate).trigger("change");
    }

    $("#procedureReviewSearchCategory").val(categoryDivCd);
    $("#titleSearch").val(title);

    fn_procedureReviewSearch("A");
}



/****************************************************************************
 * 페이지 event
 ****************************************************************************/
function fn_pageProcedureReview() {

    $(document).on('keypress', '#titleSearch', function (e) {
        fn_procedureReviewEnter(e);
    });

    $(document).on('keypress', '#procedureReviewSearchKeyword3', function (e) {
        fn_procedureReviewEnter(e);
    });

    $("#btnSearchProcedureReview").click(function () {
        fn_procedureReviewSearch();
    });

    $("#btnInsertProcedureReview").click(function () {
        fn_insertProcedureReviewIntro();
    });

    $("#btnDeleteProcedureReview").click(function () {
        fn_deleteProcedureReview();
    });


}

$(function () {
    fn_pageInit();
    fn_pageProcedureReview();
});
