
/* ##############################################################
	설  명 : [Modal]보드 생성- 콘텐츠 검색 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/
/*aggird*/
let appContentModalAgGridData = [];
let appContentModalGridDiv;
let appContentModalGridOptions;
let selectRows = [];

let appContentsSelectModal = {
    callback : null,
    reqParam : null,
    dataList : null,
    /* 모달 초기화 작업 */
    init : function () {
        $('#appContentsSelectModal').remove();
        $('body').append( this.HtmlTemplate);
        fn_searchDatePicker("#appContentsSelectModal #divAppContentSearchStartDate", "#appContentsSelectModal #divAppContentSearchEndDate");
        //그리드 이벤트
        this.setEvent();
    },
    /* 그리드 이벤트 설정 */
    setEvent:function() {
        $('#appContentsSelectModal .btnCancle').on("click", function(){
            appContentsSelectModal.close();
        });
        $('#appContentsSelectModal .btnSave').on("click", function(){
            appContentsSelectModal.save();
        });

        // 기간 선택 콤보 이벤트
        const target = $("#appContentsSelectModal #appContentSearchDateType").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_alignContent(selectId);
        });

        // 카테고리 선택 콤보 이벤트
        const categoryTarget = $("#appContentsSelectModal #appContentCategoryName").siblings("ul.select_option_list");
        categoryTarget.find("li.option_list_item").click(function () {
            let selectIdArr = $(this).prop("id").split('_');
            let selectId    = selectIdArr[1];
            let selectName  = $(this).text();

            if(selectId.match("ALL")){
                selectId = '';
            }
            $(this).parent().siblings("button").text(selectName);
            $(this).parent().siblings("input").val(selectId);
        });

        fn_alignContent('F');
        // $("#appContentsSelectModal #appContentSearchStartDate").val(appContentSearchStartDate).trigger("change");
        // $("#appContentsSelectModal #appContentSearchEndDate").val(appContentSearchEndDate).trigger("change");

        $(document).on('keypress', '#appContentsSelectModal #appContentSearchKeyword', function(e) {
            fn_appContentEnter(e);
        });

        $("#appContentsSelectModal #btnSearchAppContent").click(function () {
            appContentsSelectModal.search();
        });

    },
    // 상세 조회
    search:function(state) {

        let appContentSearchKeywordParam = $("#appContentsSelectModal #appContentSearchKeyword").val();
        let appContentCategoryName = $("#appContentsSelectModal #appContentCategoryName").val();
        let appContentSearchDateType  = $("#appContentsSelectModal #appContentSearchDateType").val();
        let appContentSearchStartDate = $("#appContentsSelectModal #appContentSearchStartDate").val();
        let appContentSearchEndDate   = $("#appContentsSelectModal #appContentSearchEndDate").val();

        let formData = new FormData();
        formData.append("menuClass", menuClass);
        formData.append("appContentSearchKeywordParam", appContentSearchKeywordParam);
        formData.append("appContentCategoryName", appContentCategoryName);
        formData.append("appContentSearchStartDate", appContentSearchStartDate);
        formData.append("appContentSearchEndDate", appContentSearchEndDate);
        formData.append("appContentSearchDateType", appContentSearchDateType);

        $.ajax({
            url: encodeURI('/webappcontents/selectListAppContents.do'),
            data: formData,
            dataType: "json",
            processData: false,
            contentType: false,
            type: 'POST',
            async: true,
            success: function(data){
                if('0'==data.msgCode){
                    appContentModalAgGridData = data.rows;
                    appContentModalGridOptions.api.setRowData(appContentModalAgGridData);
                }
                else{
                    modalEvent.danger("조회 오류", data.msgDesc);
                }
            },
            error : function(xhr, status, error) {
                modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            },
            beforeSend:function(){

            },
            complete:function(){

            }
        });
    },
    /*
     * 팝업
     * callback : 콜백함수, reqParam: 팝업파라미터
     */
    popup:function(callback, reqParam) {
        //콜백함수 지정.
        appContentsSelectModal.callback = callback;
        appContentsSelectModal.reqParam = reqParam;
        appContentsSelectModal.dataList = null;

        // 초기화 후 열기
        appContentsSelectModal.init();

        appContentsSelectModal.search();

        setTimeout(function(){
            fn_setContentModalGrid();
            $('#appContentsSelectModal').modal('show')
        }, 200);

    },
    save:function() {
        if( appContentsSelectModal.callback )  {
            appContentsSelectModal.callback(selectRows);
        }
        appContentsSelectModal.close();
    },
    /*
     * 팝업 닫기
     */
    close:function() {
        $('#appContentsSelectModal').modal('hide');

		setTimeout(function(){
			$('#appContentsSelectModal').remove();
		},500);
    },
    HtmlTemplate : `
	<div class="modal bring_modal fade" id="appContentsSelectModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <p class="title">콘텐츠 불러오기</p>
                </div>
    
                <div class="modal-body">
                    <div class="filter_box">
                        <div class="form_box">
                            <div class="select_box first dropdown">
                                <button class="label" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">기간</button>
                                <input type="hidden" id="appContentSearchDateType">
                                <ul class="select_option_list dropdown-menu" id="">
                                    <li id="li_A" class="option_list_item first" >오늘</li>
                                    <li id="li_B" class="option_list_item">최근30일</li>
                                    <li id="li_C" class="option_list_item">최근90일</li>
                                    <li id="li_D" class="option_list_item">이번주</li>
                                    <li id="li_E" class="option_list_item">이번달</li>
                                    <li id="li_F" class="option_list_item">올해</li>
                                    <li id="li_G" class="option_list_item">지난주</li>
                                    <li id="li_H" class="option_list_item">지난달</li>
                                </ul>
                            </div>

                            <!-- 캘린더input -->
                            <div class="calendar_box">
                                <div class="date_box date" id="divAppContentSearchStartDate">
                                    <img src="/image/web/calendar.svg" alt="calendar"/>
                                    <input type="date" class="date_picker" id="appContentSearchStartDate">
                                </div>
            
                                <span class="slash">-</span>
            
                                <div class="date_box last date" id="divAppContentSearchEndDate">
                                    <img src="/image/web/calendar.svg" alt="calendar"/>
                                    <input type="date" class="date_picker" id="appContentSearchEndDate">
                                </div>
                            </div>
            
                            <div class="select_box dropdown">
                                <button class="label" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">카테고리 전체</button>
                                <input type="hidden" id="appContentCategoryName">
                                <ul class="select_option_list dropdown-menu">
                                    <li class="option_list_item" id="li_ALL">카테고리 전체</li>
                                    <li class="option_list_item" id="li_피부">피부</li>
                                    <li class="option_list_item" id="li_쁘띠">쁘띠</li>
                                    <li class="option_list_item" id="li_비만">비만</li>
                                    <li class="option_list_item" id="li_기타">기타</li>
                                </ul>
                            </div>
            
                            <!-- 이름input -->
                            <div class="search_list">
                                <div class="search_box">
                                    <img src="/image/web/search_G.svg" alt="search"/>
                                    <input type="text" id="appContentSearchKeyword" required placeholder="제목, 내용">
            
                                    <div class="search_list"></div><!-- 검색내역 나오는곳 -->
                                </div>
                                <button  id="btnSearchAppContent" class="search_btn" data-toggle="modal" data-target=".work_closed_modal" style="transition: all 0.2s ease-in-out 0s;">조회</button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="table_box">
                        <div class="ag-theme-balham grid" id="appContentModalGrid"></div> 
                    </div>
                </div>

                <div class="modal-footer">
                    <div class="btn_box">
                        <button type="button" class="cancel_btn btnCancle">취소</button>
                        <button type="button" class="correction_bth btnSave">불러오기</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    `
};


/****************************************************************************
 * 검색 날짜 설정
 //(A:오늘, B:3일, C:7일, D:최근30일, E:최근90일, F:이번달, G:올해, H:지난주, I:지난달)
 ****************************************************************************/
function fn_appContentSetDate(param){
    let appContentSearchStartDate;
    let appContentSearchEndDate;
    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;

        appContentSearchStartDate = year+'-'+month+'-'+day;
        appContentSearchEndDate   = 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;

        appContentSearchEndDate   = 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;

        appContentSearchStartDate = 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;

        appContentSearchEndDate   = 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;

        appContentSearchStartDate = 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);
        let startYear  = toDate.getFullYear();
        let startMonth = toDate.getMonth() + 1;
        let startDay   = toDate.getDate();

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

        appContentSearchStartDate = startYear+'-'+startMonth+'-'+startDay;
        appContentSearchEndDate   = 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;

        appContentSearchEndDate   = 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;

        appContentSearchStartDate = 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;

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

        // 검색 시작일자
        appContentSearchStartDate = 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;

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

        // 검색 시작일자
        appContentSearchStartDate = 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;

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

        // 검색 시작일자
        appContentSearchStartDate = 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;

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

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

    $("#appContentSearchStartDate").val(appContentSearchStartDate).trigger("change");
    $("#appContentSearchEndDate").val(appContentSearchEndDate).trigger("change");
}

/****************************************************************************
 * 정렬 이벤트
 ****************************************************************************/
function fn_alignContent(param, param2){
    let align = "";

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

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

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

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

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

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

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

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

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

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

function thumbnailCellRenderer(params) {
    if(!params.value)
        return
    else
        return `<img src="${params.value.replace("C:", "")}" width="40" height="40" alt="Thumbnail">`;
}

function fn_setContentModalGrid(){
    let selectedData = appContentsSelectModal.reqParam;

    let appContentColumnDefs = [
        {
            field: "checkbox",
            headerName: "",
            minWidth: 55,
            maxWidth: 55,
            headerCheckboxSelection: true,
            // checkboxSelection: selectedData?appContentsSelectModal.reqParam.some(item => item.muAppContentId !== params.data.muAppContentId):true,
            checkboxSelection:true,
            checked:true
        },
        /* {field: "rowNum", headerName:"번호", minWidth:80,maxWidth:80, sortable: false}, */
        // {field: "rowNum", headerName: "번호", minWidth: 60, sortable: false, cellStyle: {textAlign: 'center'}},
        {field: "appContentCategoryName", headerName: "카테고리", minWidth: 100},
        {field: "filePath2", headerName: "섬네일", minWidth: 100, cellRenderer: thumbnailCellRenderer},
        {field: "title", headerName: "제목", minWidth: 200},
        {field: "content", headerName: "내용", minWidth: 400},
        {field: "writeDate", headerName: "등록일", minWidth: 150, maxWidth: 150},
        {field: "writeName", headerName: "작성자", minWidth: 130, maxWidth: 130},
    ];

// let the grid know which columns and what data to use
    appContentModalGridOptions= {
        suppressRowTransform: true,
        columnDefs: appContentColumnDefs,
        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: appContentModalAgGridData,
        suppressRowClickSelection: true, // 로우 클릭시 체크박스 선택 true no, false yes
        localeText: {
            noRowsToShow: '조회 결과가 없습니다.'
        }, //데이터 없을 시 나오는 문구
        rowSelection: 'multiple', // row 다중 선택
        debug: false,
        getRowId: function(params) {
            return params.data.muAppContentId; // muAppContentId를 각 row의 ID로 사용
        },
        onGridReady: function(params) {
        //     선택된 데이터의 muAppContentId 기반으로 체크 상태 설정
        if (typeof appContentModalGridOptions.getRowId === 'function') {
                if (selectedData) {
                    selectedData.forEach(item => {
                        // rowData에서 해당 muAppContentId를 가진 데이터를 찾고, 그리드에서 해당 행을 선택
                        let matchingNode = params.api.getRowNode(item.muAppContentId);
                        if (matchingNode) {
                            matchingNode.setSelected(true); // 해당 행을 선택 상태로 설정
                        }
                    });
                }
                }
        },
        onCellClicked: function (event) { //셀 클릭 이벤트
            /* alert(event.column.colId); */
            if ('title' == event.column.colId) {
                // fn_updateAppContentIntro(event.data.muAppContentId);
            }
        },
        onSelectionChanged: function (event) { //체크박스 선택
            selectRows = event.api.getSelectedRows();

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

            appContentsSelectModal.search();
        }
    };
    appContentModalGridDiv = document.querySelector('#appContentModalGrid');
    new agGrid.Grid(appContentModalGridDiv, appContentModalGridOptions);
}




