/* 페이징 관련 변수 */
let webPopupTotalCount   = 0;
let webPopupTotalPages   = 0;

/*aggird*/
let webPopupAgGridData = [];

let webPopupSelectId = "";

/****************************************************************************
 * 콘텐츠 정보 리스트 조회
 ****************************************************************************/
function fn_selectListWebPopupJson(){
    let formData = new FormData();
    formData.append("menuClass", menuClass);
    formData.append("webPopupSearchKeywordParam", webPopupSearchKeywordParam);
    formData.append("webPopupCategoryName", webPopupCategoryName);
    formData.append("webPopupSort", webPopupSort);
    formData.append("webPopupDir", webPopupDir);
    formData.append("webPopupStart", webPopupStart);
    formData.append("webPopupLimit", webPopupLimit);
	formData.append("homepageDivCd", $("#homepageDivCd").val());
    //formData.append("webPopupSearchStartDate", webPopupSearchStartDate);
    //formData.append("webPopupSearchEndDate", webPopupSearchEndDate);
    //formData.append("webPopupSearchDateType", webPopupSearchDateType);

    $.ajax({
        url: encodeURI('/webpopup/selectListWebPopup.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async: true,
        success: function(data){
            if('0'==data.msgCode){
                // 페이징 처리
                webPopupTotalCount  = data.totalCount;
                //$("#txt_noticeTotalCount").text(noticeTotalCount);

                webPopupTotalPages = Math.ceil(webPopupTotalCount/webPopupLimit);

                // 리스트 조회
                webPopupAgGridData = data.rows.map(row => {
                    if(row.filePath) {
                        return { ...row, filePath: CDN_URL + row.filePath.replace(/^C:/, "") };
                    }
                    return row;
                });
                webPopupGridOptions.api.setRowData(webPopupAgGridData);

                if(0<data.rows.length){
                    //페이징 처리
                    window.pagObj = $('#webPopupPagination').twbsPagination({
                        startPage    : ((webPopupStart/webPopupLimit)+1),
                        totalPages   : (webPopupTotalPages==0)?1:webPopupTotalPages,
                        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_webPopupPagination(page);
                        }
                    }).on('page', function (event, page) {
                        //console.info(page + ' (from event listening)');
                    });
                }
                else{

                }
            }
            else{
                modalEvent.danger("조회 오류", data.msgDesc);
            }
        },
        error : function(xhr, status, error) {
            modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
        },
        beforeSend:function(){
            // 로딩열기
            webPopupGridOptions.api.showLoadingOverlay();
        },
        complete:function(){

        }
    });
}

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

    fn_webPopupPaginReset();

    webPopupSearchKeywordParam = $("#webPopupSearchKeyword").val();

    webPopupCategoryName = $("#webPopupCategoryName").val();

    //webPopupSearchDateType  = $("#webPopupSearchDateType").val();
    //webPopupSearchStartDate = $("#webPopupSearchStartDate").val();
    //webPopupSearchEndDate   = $("#webPopupSearchEndDate").val();

    fn_selectListWebPopupJson();
}


/****************************************************************************
 * 초기화하기
 ****************************************************************************/
function fn_webPopupReset(){
    $("#webPopupSearchKeyword").val("");

    fn_webPopupSearch();
}

/****************************************************************************
 * 페이징 처리
 ****************************************************************************/
function fn_webPopupPagination(param){
    webPopupStart = (parseInt(param)-1)*webPopupLimit;

    fn_selectListWebPopupJson();
}

/****************************************************************************
 * 페이징 리셋
 ****************************************************************************/
function fn_webPopupPaginReset(){
    webPopupSearchKeywordParam = '';

    webPopupStart        = 0;
    webPopupLimit        = 100;
    webPopupTotalCount   = 0;
    webPopupTotalPages   = 0;

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

/****************************************************************************
 * 콘텐츠 삭제
 ****************************************************************************/
function fn_deleteWebPopup(){
    if("Y"!=deleteUseYn){
        modalEvent.warning("", "삭제 권한이 없습니다.");
        return false;
    }

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

    modalEvent.info("삭제", "선택한 콘텐츠 정보를 삭제하시겠습니까?", function(){
        let formData = new FormData();
        formData.append("menuClass", menuClass);
        formData.append("selectId", webPopupSelectId);

        $.ajax({
            url: encodeURI('/webpopup/deleteWebPopup.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_webPopupOk();
                    });
                }
                else{
                    modalEvent.danger("삭제 오류", data.msgDesc);
                }
            },
            error : function(xhr, status, error) {
                modalEvent.danger("삭제 오류", "삭제 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            },
            beforeSend:function(){

            },
            complete:function(){

            }
        });
    });
}

/****************************************************************************
 * 검색 엔터 이벤트
 ****************************************************************************/
function fn_webPopupEnter(e){
    if(e.which){
        // 파이어폭스
        if(13 == e.which) {
            //로그인 액션 스크립트
            fn_webPopupSearch();
        }
    }
    else{
        // 윈도우, 사파리, 크롬
        if(13 == event.keyCode) {
            //로그인 액션 스크립트
            fn_webPopupSearch();
        }
    }
}

/****************************************************************************
 * 완료
 ****************************************************************************/
function fn_webPopupOk(){
    fn_webPopupReset();
}

/****************************************************************************
 * 등록 화면으로 이동.
 ****************************************************************************/
function fn_insertWebPopupIntro(){
    if("Y"==insertUseYn){
        if(10<=webPopupAgGridData.length){
            modalEvent.warning("", "등록 갯수를 초과하였습니다.");
            return false;
        }else{
            let pagingParam = "?menuClass="+menuClass;
            fn_leftFormAction("/webpopup/insertWebPopupIntro.do"+pagingParam);
        }
    }else{
        modalEvent.warning("", "등록 권한이 없습니다.");
        return false;
    }

}

/****************************************************************************
 * 수정 화면으로 이동.
 ****************************************************************************/
function fn_updateWebPopupIntro(muWebPopupId){
    if("Y"==updateUseYn){
        let pagingParam = "?menuClass="+menuClass;
        pagingParam    += "&muWebPopupId="+muWebPopupId;
        fn_leftFormAction("/webpopup/updateWebPopupIntro.do"+pagingParam);
    }else{
        modalEvent.warning("", "수정 권한이 없습니다.");
        return false;
    }
}
function thumbnailCellRenderer(params) {
    if(!params.value)
        return
    else
        return `<img src="${params.value.replace("C:", "")}" width="40" height="40" alt="Thumbnail">`;
}

let webPopupColumnDefs = [
    {field: "checkbox", headerName:"", minWidth:55, maxWidth:55, headerCheckboxSelection: true, checkboxSelection: true},
    /* {field: "rowNum", headerName:"번호", minWidth:80,maxWidth:80, sortable: false}, */	
    {field: "rowNum", headerName:"번호", minWidth:60, maxWidth:60,sortable: false, cellStyle:{textAlign: 'center'}},
	{field: "homepageDivCd", headerName:"홈페이지 구분", minWidth:150, maxWidth:150, cellStyle:{textAlign: 'center'},	
			valueFormatter: function(params) {
		        if (params.value === "01") return "다이어트";
		        if (params.value === "02") return "쁘띠";
		        return params.value;
		    }},
    {field: "filePath", headerName:"이미지", minWidth:100, cellRenderer: thumbnailCellRenderer},
    {field: "title", headerName:"제목", minWidth:250, cellStyle:{cursor: 'pointer', color:'#3985EA'}},
    // {field: "content", headerName:"내용",minWidth:500},
    {field: "writeDate", headerName:"등록일",minWidth:150, maxWidth:150},
    {field: "writeName", headerName:"작성자",minWidth:150, maxWidth:150},
];

// let the grid know which columns and what data to use
let webPopupGridOptions = {
    suppressRowTransform: true,
    columnDefs: webPopupColumnDefs,
    defaultColDef: {		// 리스트 기본 설정
        flex: 1,
        sortable: true,		//정렬 여부
        resizable: true,	//리사이즈
        editable: false,	// 그리드에서 데이터 수정
        cellStyle:{textAlign:'left',fontSize:'14px',padding:'0'},
        //suppressSizeToFit:true,		//자동 맞춤
        //enableRowGroup: true,		// 그룹 묶음
        enablePivot: true,
        enableValue : true
    },
    //suppressMultiSort:true,  //단일솔트 true가 단일, false가 다중 shift + sort 시
    headerHeight : 41, // header 높이
    rowHeight : 41, // row 높이
    rowData : webPopupAgGridData,
    suppressRowClickSelection : true, // 로우 클릭시 체크박스 선택 true no, false yes
    localeText : {
        noRowsToShow : '조회 결과가 없습니다.'
    }, //데이터 없을 시 나오는 문구
    rowSelection : 'multiple', // row 다중 선택
    debug : false,
    onCellClicked: function(event){ //셀 클릭 이벤트
        /* alert(event.column.colId); */
        if('title'==event.column.colId){
            fn_updateWebPopupIntro(event.data.muWebPopupId);
        }
    },
    onSelectionChanged: function(event){ //체크박스 선택
        let selectRows = [];
        selectRows = event.api.getSelectedRows();

        webPopupSelectId = '';
        for(let i=0; i<selectRows.length; i++){
            webPopupSelectId += selectRows[i].muWebPopupId + ",";
        }
        webPopupSelectId = webPopupSelectId.substring(0, webPopupSelectId.lastIndexOf(','));
    },
    onSortChanged: function(event){
        //정렬
        webPopupSort = ''; //기존 정렬 초기화
        let columnArr = event.columnApi.getColumnState();
        if(0<columnArr.length){
            //sort index 순으로 재정렬
            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){
                    webPopupStart = 0;
                    webPopupSort += gridSortModel+' '+ gridSort + ',';
                }
                else{
                    nullCnt++;
                    if(nullCnt == columnArr.length){
                        webPopupSort = '';
                        webPopupDir = '';
                        webPopupStart = 0;
                    }
                }
            }
        }
        webPopupSort = webPopupSort.substring(0,webPopupSort.lastIndexOf( ",")); //맨끝 콤마 지우기

        fn_webPopupSearch();
    }
};

// lookup the container we want the Grid to use
let webPopupGridDiv = document.querySelector('#webPopupGrid');

// create the grid passing in the div to use together with the columns & data we want to use
new agGrid.Grid(webPopupGridDiv, webPopupGridOptions);





/****************************************************************************
 * 페이지 init
 ****************************************************************************/
function fn_pageInit(){

    // 초기 페이징 처리
    $("#webPopupSearchKeyword").val(webPopupSearchKeywordParam);

    fn_webPopupSearch("A");
}

/****************************************************************************
 * 페이지 event
 ****************************************************************************/
function fn_pageEvent(){
    // 검색 input
    $(document).on('keypress', '#webPopupSearchKeyword', function(e) {
        fn_webPopupEnter(e);
    });

    // 검색 조회 버튼
    $("#btnSearchWebPopup").click(function () {
        fn_webPopupSearch();
    });

    // 콘텐츠 등록 팝업 버튼
    $("#btnInsertWebPopup").click(function () {
        fn_insertWebPopupIntro();
    });

    // 콘텐츠 삭제 버튼
    $("#btnDeleteWebPopup").click(function () {
        fn_deleteWebPopup();
    });
}

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

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