/* 페이징 관련 변수 */
let webPhotoPetitTotalCount   = 0;
let webPhotoPetitTotalPages   = 0;

/*aggird*/
let webPhotoPetitAgGridData = [];

let webPhotoPetitSelectId = "";
let webPhotoPetitSelectCategoryNo = "";

/****************************************************************************
 * 검색 날짜 설정
 //(A:오늘, B:3일, C:7일, D:최근30일, E:최근90일, F:이번달, G:올해, H:지난주, I:지난달)
 ****************************************************************************/
function fn_webPhotoPetitSetDate(param){
    if("A"==param){
        // 오늘
        let toDate = new Date();
        let year  = toDate.getFullYear();
        let month = toDate.getMonth() + 1;
        let day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        webPhotoPetitSearchStartDate = year+'-'+month+'-'+day;
        webPhotoPetitSearchEndDate   = year+'-'+month+'-'+day;
    }
    else if("B"==param){
        // 3일
        // 검색 종료일자
        let toDate = new Date();
        let year  = toDate.getFullYear();
        let month = toDate.getMonth() + 1;
        let day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        webPhotoPetitSearchEndDate   = year+'-'+month+'-'+day;

        // 검색 시작일자
        toDate.setDate(toDate.getDate() - 3);
        year  = toDate.getFullYear();
        month = toDate.getMonth() + 1;
        day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        webPhotoPetitSearchStartDate = year+'-'+month+'-'+day;
    }
    else if("C"==param){
        // 이번주
        // 검색 종료일자
        let toDate = new Date();
        let year  = toDate.getFullYear();
        let month = toDate.getMonth() + 1;
        let day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        webPhotoPetitSearchEndDate   = year+'-'+month+'-'+day;

        // 검색 시작일자
        toDate.setDate(toDate.getDate() - 7);
        year  = toDate.getFullYear();
        month = toDate.getMonth() + 1;
        day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        webPhotoPetitSearchStartDate = year+'-'+month+'-'+day;
    }
    else if("D"==param){
        // 최근30일
        let toDate = new Date();
        let year  = toDate.getFullYear();
        let month = toDate.getMonth() + 1;
        let day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        //최근30일
        toDate.setDate(toDate.getDate() - 30);
        startYear  = toDate.getFullYear();
        startMonth = toDate.getMonth() + 1;
        startDay   = toDate.getDate();

        if(startMonth < 10) startMonth = "0" + startMonth;
        if(startDay < 10) startDay = "0" + startDay;

        webPhotoPetitSearchStartDate = startYear+'-'+startMonth+'-'+startDay;
        webPhotoPetitSearchEndDate   = year+'-'+month+'-'+day;

    }
    else if("E"==param){
        // 최근90일
        // 검색 종료일자
        let toDate = new Date();
        let year  = toDate.getFullYear();
        let month = toDate.getMonth() + 1;
        let day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        webPhotoPetitSearchEndDate   = year+'-'+month+'-'+day;

        // 검색 시작일자
        toDate.setDate(toDate.getDate() - 90);
        year  = toDate.getFullYear();
        month = toDate.getMonth() + 1;
        day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        webPhotoPetitSearchStartDate = year+'-'+month+'-'+day;
    }
    else if("F"==param){
        //F:이번달
        // 검색 종료일자
        let toDate = new Date();
        let year  = toDate.getFullYear();
        let month = toDate.getMonth() + 1;
        let day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        webPhotoPetitSearchEndDate   = year+'-'+month+'-'+day;

        // 검색 시작일자
        webPhotoPetitSearchStartDate = year+'-'+month+'-01';
    }
    else if("G"==param){
        // G:올해
        // 검색 종료일자
        let toDate = new Date();
        let year  = toDate.getFullYear();
        let month = toDate.getMonth() + 1;
        let day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        webPhotoPetitSearchEndDate   = year+'-'+month+'-'+day;

        // 검색 시작일자
        webPhotoPetitSearchStartDate = year+'-01-01';
    }
    else if("H"==param){
        // H:지난주, I:지난달
        // 검색 종료일자
        let toDate = new Date();
        let year  = toDate.getFullYear();
        let month = toDate.getMonth() + 1;
        let day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        webPhotoPetitSearchEndDate   = year+'-'+month+'-'+day;

        // 검색 시작일자
        webPhotoPetitSearchStartDate = year+'-01-01';
    }
    else if("I"==param){
        // I:지난달
        // 검색 종료일자
        let toDate = new Date();
        let year  = toDate.getFullYear();
        let month = toDate.getMonth() + 1;
        let day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        webPhotoPetitSearchEndDate   = year+'-'+month+'-'+day;

        // 검색 시작일자
        webPhotoPetitSearchStartDate = year+'-01-01';
    }

    $("#webPhotoPetitSearchStartDate").val(webPhotoPetitSearchStartDate).trigger("change");
    $("#webPhotoPetitSearchEndDate").val(webPhotoPetitSearchEndDate).trigger("change");
}


/****************************************************************************
 * 전후 사진(쁘띠) 정보 리스트 조회
 ****************************************************************************/
function fn_selectListWebPhotoPetitJson(){
    let formData = new FormData();
    formData.append("menuClass", menuClass);
    formData.append("webPhotoPetitSearchKeywordParam0", webPhotoPetitSearchKeywordParam0);
	formData.append("webPhotoPetitSearchKeywordParam1", webPhotoPetitSearchKeywordParam1);
	formData.append("webPhotoPetitSearchKeywordParam2", webPhotoPetitSearchKeywordParam2);
	formData.append("webPhotoPetitSearchKeywordParam3", webPhotoPetitSearchKeywordParam3);
    formData.append("webPhotoPetitSort", webPhotoPetitSort);
    formData.append("webPhotoPetitDir", webPhotoPetitDir);
    formData.append("webPhotoPetitStart", webPhotoPetitStart);
    formData.append("webPhotoPetitLimit", webPhotoPetitLimit);
    formData.append("webPhotoPetitSearchStartDate", webPhotoPetitSearchStartDate);
    formData.append("webPhotoPetitSearchEndDate", webPhotoPetitSearchEndDate);
    formData.append("webPhotoPetitSearchDateType", webPhotoPetitSearchDateType);

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

                webPhotoPetitTotalPages = Math.ceil(webPhotoPetitTotalCount/webPhotoPetitLimit);

                // 리스트 조회
                webPhotoPetitAgGridData = data.rows;
                webPhotoPetitGridOptions.api.setRowData(webPhotoPetitAgGridData);

                if(0<data.rows.length){
                    //페이징 처리
                    window.pagObj = $('#webPhotoPetitPagination').twbsPagination({
                        startPage    : ((webPhotoPetitStart/webPhotoPetitLimit)+1),
                        totalPages   : (webPhotoPetitTotalPages==0)?1:webPhotoPetitTotalPages,
                        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 (photopetit, page) {
                            fn_webPhotoPetitPagination(page);
                        }
                    }).on('page', function (photopetit, page) {
                        //console.info(page + ' (from photopetit listening)');
                    });
                }
                else{

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

        }
    });
}

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

    fn_webPhotoPetitPaginReset();

    webPhotoPetitSearchKeywordParam0 = $("#webPhotoPetitSearchKeyword0").val();
	webPhotoPetitSearchKeywordParam1 = $("#webPhotoPetitSearchKeyword1").val();
	webPhotoPetitSearchKeywordParam2 = $("#webPhotoPetitSearchKeyword2").val();
	webPhotoPetitSearchKeywordParam3 = $("#webPhotoPetitSearchKeywordParam3").val();

    webPhotoPetitSearchDateType  = $("#webPhotoPetitSearchDateType").val();
    webPhotoPetitSearchStartDate = $("#webPhotoPetitSearchStartDate").val();
    webPhotoPetitSearchEndDate   = $("#webPhotoPetitSearchEndDate").val();

    fn_selectListWebPhotoPetitJson();
}


/****************************************************************************
 * 초기화하기
 ****************************************************************************/
function fn_webPhotoPetitReset(){
    fn_webPhotoPetitSetDate('D');
    $("#webPhotoPetitSearchDateType option:eq(0)").prop("selected", true);

    $("#webPhotoPetitSearchKeyword0").val("");
	$("#webPhotoPetitSearchKeyword1").val("");
	$("#webPhotoPetitSearchKeyword2").val("");
	$("#webPhotoPetitSearchKeyword3").val("");

    fn_webPhotoPetitSearch();
}

/****************************************************************************
 * 페이징 처리
 ****************************************************************************/
function fn_webPhotoPetitPagination(param){
    webPhotoPetitStart = (parseInt(param)-1)*webPhotoPetitLimit;

    fn_selectListWebPhotoPetitJson();
}

/****************************************************************************
 * 페이징 리셋
 ****************************************************************************/
function fn_webPhotoPetitPaginReset(){
    webPhotoPetitSearchKeywordParam0 = '';
	webPhotoPetitSearchKeywordParam1 = '';
	webPhotoPetitSearchKeywordParam2 = '';
	webPhotoPetitSearchKeywordParam3 = '';

    webPhotoPetitStart        = 0;
    webPhotoPetitLimit        = 100;
    webPhotoPetitTotalCount   = 0;
    webPhotoPetitTotalPages   = 0;

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

/****************************************************************************
 * 전후 사진(쁘띠) 삭제
 ****************************************************************************/
function fn_deleteWebPhotoPetit(){
    if("Y"!=deleteUseYn){
        modalEvent.warning("", "삭제 권한이 없습니다.");
        return false;
    }

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

    // categoryno 값 가져오기 (여러 개일 수 있음)
    let selectRows = webPhotoPetitGridOptions.api.getSelectedRows();
    let categoryNos = selectRows.map(function(row) { return row.categoryno; }).join(",");

    modalEvent.info("삭제", "선택한 전후 사진(쁘띠) 정보를 삭제하시겠습니까?", function(){
        let formData = new FormData();
        formData.append("menuClass", menuClass);
        formData.append("selectId", webPhotoPetitSelectId);
        formData.append("categoryno", categoryNos); // categoryno 추가

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

            },
            complete:function(){

            }
        });
    });
}

/****************************************************************************
 * 검색 엔터 전후 사진(쁘띠)
 ****************************************************************************/
function fn_webPhotoPetitEnter(e){
    if(e.which){
        // 파이어폭스
        if(13 == e.which) {
            //로그인 액션 스크립트
            fn_webPhotoPetitSearch();
        }
    }
    else{
        // 윈도우, 사파리, 크롬
        if(13 == photopetit.keyCode) {
            //로그인 액션 스크립트
            fn_webPhotoPetitSearch();
        }
    }
}

/****************************************************************************
 * 정렬 전후 사진(쁘띠)
 ****************************************************************************/
function fn_alignPhotoPetit(param, param2){
    let align = "";

    if("A"==param){
        align = "오늘";

        fn_webPhotoPetitSetDate('A');
    }
    else if("B"==param){
        align = "최근30일";

        fn_webPhotoPetitSetDate('D');
    }
    else if("C"==param){
        align = "최근90일";

        fn_webPhotoPetitSetDate('E');
    }
    else if("D"==param){
        align = "이번주";

        fn_webPhotoPetitSetDate('C');
    }
    else if("E"==param){
        align = "이번달";

        fn_webPhotoPetitSetDate('F');
    }
    else if("F"==param){
        align = "올해";

        fn_webPhotoPetitSetDate('G');
    }
    else if("G"==param){
        align = "지난주";

        fn_webPhotoPetitSetDate('H');
    }
    else if("H"==param){
        align = "지난달";

        fn_webPhotoPetitSetDate('I');
    }
    else{
        align = "";
    }
    $("#webPhotoPetitSearchDateType").val(param);
    $("#webPhotoPetitSearchDateType").siblings("button").text(align);
}

/****************************************************************************
 * 완료
 ****************************************************************************/
function fn_webPhotoPetitOk(){
    fn_webPhotoPetitReset();
}

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

}

/****************************************************************************
 * 수정 화면으로 이동.
 ****************************************************************************/
function fn_updateWebPhotoPetitIntro(muWebPhotoPetitId, categoryno){
    if("Y"==updateUseYn){
        let pagingParam = "?menuClass="+menuClass;
        pagingParam    += "&muWebPhotoPetitId="+muWebPhotoPetitId;
		pagingParam    += "&categoryno="+categoryno;
        fn_leftFormAction("/webphotopetit/updateWebPhotoPetitIntro.do"+pagingParam);
    }else{
        modalEvent.warning("", "수정 권한이 없습니다.");
        return false;
    }
}


let webPhotoPetitColumnDefs = [
    {field: "checkbox", headerName:"", minWidth:55, maxWidth:55, headerCheckboxSelection: true, checkboxSelection: true},    
    {field: "rowNum", headerName:"번호", minWidth:60, maxWidth:60,sortable: false, cellStyle:{textAlign: 'center'}},
	{field: "category", headerName:"카테고리", minWidth:60},
    {field: "title", headerName:"제목", minWidth:150, cellStyle:{cursor: 'pointer', color:'#3985EA'}},    
	{field: "content", headerName:"내용요약", minWidth:150},
	{field: "hashtag", headerName:"해시태그", minWidth:150},
    {field: "writeDate", headerName:"등록일",minWidth:100, maxWidth:150},
    {field: "writeName", headerName:"작성자",minWidth:100, maxWidth:150},
];

// let the grid know which columns and what data to use
let webPhotoPetitGridOptions = {
    suppressRowTransform: true,
    columnDefs: webPhotoPetitColumnDefs,
    defaultColDef: {		// 리스트 기본 설정
        flex: 1,
        sortable: true,		//정렬 여부
        resizable: true,	//리사이즈
        editable: true,	// 그리드에서 데이터 수정
        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 : webPhotoPetitAgGridData,
    suppressRowClickSelection : true, // 로우 클릭시 체크박스 선택 true no, false yes
    localeText : {
        noRowsToShow : '조회 결과가 없습니다.'
    }, //데이터 없을 시 나오는 문구
    rowSelection : 'multiple', // row 다중 선택
    debug : false,
    onCellClicked: function(photopetit){ //셀 클릭 전후 사진(쁘띠)
        /* alert(photopetit.column.colId); */
        if('title'==photopetit.column.colId){
            fn_updateWebPhotoPetitIntro(photopetit.data.muWebPhotoPetitId, photopetit.data.categoryno);
        }
    },
    onSelectionChanged: function(photopetit){ //체크박스 선택
        let selectRows = [];
        selectRows = photopetit.api.getSelectedRows();

        webPhotoPetitSelectId = '';
        for(let i=0; i<selectRows.length; i++){
            webPhotoPetitSelectId += selectRows[i].muWebPhotoPetitId + ",";
        }
        webPhotoPetitSelectId = webPhotoPetitSelectId.substring(0, webPhotoPetitSelectId.lastIndexOf(','));
    },
    onSortChanged: function(photopetit){
        //정렬
        webPhotoPetitSort = ''; //기존 정렬 초기화
        let columnArr = photopetit.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){
                    webPhotoPetitStart = 0;
                    webPhotoPetitSort += gridSortModel+' '+ gridSort + ',';
                }
                else{
                    nullCnt++;
                    if(nullCnt == columnArr.length){
                        webPhotoPetitSort = '';
                        webPhotoPetitDir = '';
                        webPhotoPetitStart = 0;
                    }
                }
            }
        }
        webPhotoPetitSort = webPhotoPetitSort.substring(0,webPhotoPetitSort.lastIndexOf( ",")); //맨끝 콤마 지우기

        fn_webPhotoPetitSearch();
    }
};

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

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





/****************************************************************************
 * 페이지 init
 ****************************************************************************/
function fn_pageInit(){
    // 날짜 datepicker
    fn_searchDatePicker("#divWebPhotoPetitSearchStartDate", "#divWebPhotoPetitSearchEndDate");

    if(!webPhotoPetitSearchStartDate&&!webPhotoPetitSearchEndDate){
        // 검색 오늘날짜 셋팅
        fn_webPhotoPetitSetDate('D');
    }else{
        $("#webPhotoPetitSearchStartDate").val(webPhotoPetitSearchStartDate).trigger("change");
        $("#webPhotoPetitSearchEndDate").val(webPhotoPetitSearchEndDate).trigger("change");
    }

    // 초기 페이징 처리
    $("#webPhotoPetitSearchKeyword0").val(webPhotoPetitSearchKeywordParam0);
	$("#webPhotoPetitSearchKeyword1").val(webPhotoPetitSearchKeywordParam1);
	$("#webPhotoPetitSearchKeyword2").val(webPhotoPetitSearchKeywordParam2);
	$("#webPhotoPetitSearchKeyword3").val(webPhotoPetitSearchKeywordParam3);

    fn_webPhotoPetitSearch("A");
}

/****************************************************************************
 * 페이지 photopetit
 ****************************************************************************/
function fn_pagePhotoPetit(){
    // 검색 input
    $(document).on('keypress', '#webPhotoPetitSearchKeyword0', function(e) {
        fn_webPhotoPetitEnter(e);
    });
	// 검색 input
    $(document).on('keypress', '#webPhotoPetitSearchKeyword1', function(e) {
        fn_webPhotoPetitEnter(e);
    });
	// 검색 input
    $(document).on('keypress', '#webPhotoPetitSearchKeyword2', function(e) {
        fn_webPhotoPetitEnter(e);
    });
	// 검색 input
    $(document).on('keypress', '#webPhotoPetitSearchKeyword3', function(e) {
        fn_webPhotoPetitEnter(e);
    });

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

    // 전후 사진(쁘띠) 등록 팝업 버튼
    $("#btnInsertWebPhotoPetit").click(function () {
        fn_insertWebPhotoPetitIntro();
    });

    // 전후 사진(쁘띠) 삭제 버튼
    $("#btnDeleteWebPhotoPetit").click(function () {
        fn_deleteWebPhotoPetit();
    });

    // 기간 선택 콤보 전후 사진(쁘띠)
    const target = $("#webPhotoPetitSearchDateType").siblings("ul.select_option_list");
    target.find("li.option_list_item").click(function () {
        let selectIdArr = $(this).prop("id").split('_');
        let selectId    = selectIdArr[1];
        let selectName  = $(this).text();

        $(this).parent().siblings("button").text(selectName);
        $(this).parent().siblings("input").val(selectId);

        fn_alignPhotoPetit(selectId);
    });
}

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

    // 페이지 photopetit
    fn_pagePhotoPetit();
});