/* 페이징 관련 변수 */
let appUserInquiryTotalCount   = 0;
let appUserInquiryTotalPages   = 0;

/*aggird*/
let appUserInquiryAgGridData = [];

let appUserInquirySelectId = "";

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

        appUserInquirySearchStartDate = year+'-'+month+'-'+day;
        appUserInquirySearchEndDate   = 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;

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

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

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

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

        appUserInquirySearchStartDate = startYear+'-'+startMonth+'-'+startDay;
        appUserInquirySearchEndDate   = 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;

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

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

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

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

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

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

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

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

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

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

    $("#appUserInquirySearchStartDate").val(appUserInquirySearchStartDate).trigger("change");
    $("#appUserInquirySearchEndDate").val(appUserInquirySearchEndDate).trigger("change");
}


/****************************************************************************
 * 공지사항 정보 리스트 조회
 ****************************************************************************/
function fn_selectListAppUserInquiryJson(){
    let formData = new FormData();
    formData.append("menuClass", menuClass);
    formData.append("appUserInquirySearchKeywordParam", appUserInquirySearchKeywordParam);
    formData.append("appUserInquirySort", appUserInquirySort);
    formData.append("appUserInquiryDir", appUserInquiryDir);
    formData.append("appUserInquiryStart", appUserInquiryStart);
    formData.append("appUserInquiryLimit", appUserInquiryLimit);
    formData.append("appUserInquirySearchStartDate", appUserInquirySearchStartDate);
    formData.append("appUserInquirySearchEndDate", appUserInquirySearchEndDate);
    formData.append("appUserInquirySearchDateType", appUserInquirySearchDateType);

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

                appUserInquiryTotalPages = Math.ceil(appUserInquiryTotalCount/appUserInquiryLimit);

                // 리스트 조회
                appUserInquiryAgGridData = data.rows;
                appUserInquiryGridOptions.api.setRowData(appUserInquiryAgGridData);

                if(0<data.rows.length){
                    //페이징 처리
                    window.pagObj = $('#appUserInquiryPagination').twbsPagination({
                        startPage    : ((appUserInquiryStart/appUserInquiryLimit)+1),
                        totalPages   : (appUserInquiryTotalPages==0)?1:appUserInquiryTotalPages,
                        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_appUserInquiryPagination(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(){
            // 로딩열기
            appUserInquiryGridOptions.api.showLoadingOverlay();
        },
        complete:function(){

        }
    });
}

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

    fn_appUserInquiryPaginReset();

    appUserInquirySearchKeywordParam = $("#appUserInquirySearchKeyword").val();

    appUserInquirySearchDateType  = $("#appUserInquirySearchDateType").val();
    appUserInquirySearchStartDate = $("#appUserInquirySearchStartDate").val();
    appUserInquirySearchEndDate   = $("#appUserInquirySearchEndDate").val();

    fn_selectListAppUserInquiryJson();
}


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

    $("#appUserInquirySearchKeyword").val("");

    fn_appUserInquirySearch();
}

/****************************************************************************
 * 페이징 처리
 ****************************************************************************/
function fn_appUserInquiryPagination(param){
    appUserInquiryStart = (parseInt(param)-1)*appUserInquiryLimit;

    fn_selectListAppUserInquiryJson();
}

/****************************************************************************
 * 페이징 리셋
 ****************************************************************************/
function fn_appUserInquiryPaginReset(){
    appUserInquirySearchKeywordParam = '';

    appUserInquiryStart        = 0;
    appUserInquiryLimit        = 100;
    appUserInquiryTotalCount   = 0;
    appUserInquiryTotalPages   = 0;

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

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

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

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

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

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

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

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

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

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

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

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

/****************************************************************************
 * 완료
 ****************************************************************************/
function fn_appUserInquiryOk(){
    fn_appUserInquiryReset();
}

function fn_updateAppUserInquiryPopup(param,status){
    let reqParam =  {
        "muAppUserInquiryId" : param
    };

    if('답변완료'===status){
        if("Y"==updateUseYn){
            // 수정가능
            appUserInquiryUpdateModal.popup(function(obj, reqParam) {
                fn_appUserInquiryOk();
            }, reqParam);
        }
        else{
            // 조회만
            appUserInquirySelectModal.popup(function(obj, reqParam) {
                fn_appUserInquiryOk();
            }, reqParam);
        }
    }else {
        if("Y"==insertUseYn){
            // 등록가능
            appUserInquiryInsertModal.popup(function(obj, reqParam) {
                fn_appUserInquiryOk();
            }, reqParam);
        }
        else{
            // 조회만
            appUserInquirySelectModal.popup(function(obj, reqParam) {
                fn_appUserInquiryOk();
            }, reqParam);
        }
    }
}

function fn_phoneFormatter(params){
    return fn_setFormatPhone(params.value);
}

let appUserInquiryColumnDefs = [
    {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,sortable: false, cellStyle:{textAlign: 'center'}},
    {field: "userName", headerName:"고객명", minWidth:60,sortable: false},
    {field: "membershipAccount", headerName:"아이디", minWidth:60,sortable: false},
    {field: "phoneNumber", headerName:"연락처", minWidth:60,sortable: false, valueFormatter: fn_phoneFormatter},
    {field: "title", headerName:"문의제목", minWidth:250, maxWidth:250},
    {field: "content", headerName:"문의내용",minWidth:250 ,cellStyle:{cursor: 'pointer', color:'#3985EA'}},
    {field: "writeDate", headerName:"문의일자",minWidth:250},
    {field: "answerStatus", headerName:"답변상태",minWidth:250},
    {field: "answerDate", headerName:"답변일자",minWidth:100, maxWidth:100},
    {field: "memberName", headerName:"담당자",minWidth:100, maxWidth:100}
];

// let the grid know which columns and what data to use
let appUserInquiryGridOptions = {
    suppressRowTransform: true,
    columnDefs: appUserInquiryColumnDefs,
    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 : appUserInquiryAgGridData,
    suppressRowClickSelection : true, // 로우 클릭시 체크박스 선택 true no, false yes
    localeText : {
        noRowsToShow : '조회 결과가 없습니다.'
    }, //데이터 없을 시 나오는 문구
    rowSelection : 'multiple', // row 다중 선택
    debug : false,
    onCellClicked: function(event){ //셀 클릭 이벤트
        /* alert(event.column.colId); */
        if('content'==event.column.colId){
                fn_updateAppUserInquiryPopup(event.data.muAppUserInquiryId,event.data.answerStatus);
        }
    },
    onSelectionChanged: function(event){ //체크박스 선택
        let selectRows = [];
        selectRows = event.api.getSelectedRows();

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

        fn_appUserInquirySearch();
    }
};

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

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





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

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

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

    fn_appUserInquirySearch("A");
}

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

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

    // 공지사항 등록 팝업 버튼
    $("#btnInsertAppUserInquiry").click(function () {
        fn_insertAppUserInquiryPopup();
    });

    // 공지사항 삭제 버튼
    $("#btnDeleteAppUserInquiry").click(function () {
        fn_deleteAppUserInquiry();
    });

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

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

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