/* 페이징 관련 변수 */
let smsTotalCount   = 0;
let smsTotalPages   = 0;


let smsAgGridData = [];
let muUserData=[];

let selectedRows = [];

/****************************************************************************
* 검색 날짜 설정
//(A:오늘, B:3일, C:7일, D:최근30일, E:최근90일, F:이번달, G:올해, H:지난주, I:지난달)
****************************************************************************/
function fn_smsSetDate(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;
		
		smsSearchStartDate = year+'-'+month+'-'+day;
		smsSearchEndDate   = 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;
		
		smsSearchEndDate   = 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;
		
		smsSearchStartDate = 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;
		
		smsSearchEndDate   = 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;
		
		smsSearchStartDate = 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;
		
		smsSearchStartDate = startYear+'-'+startMonth+'-'+startDay;
		smsSearchEndDate   = 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;
		
		smsSearchEndDate   = 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;
		
		smsSearchStartDate = 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;
		
		smsSearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		smsSearchStartDate = 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;
		
		smsSearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		smsSearchStartDate = 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;
		
		smsSearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		smsSearchStartDate = 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;
		
		smsSearchEndDate   = year+'-'+month+'-'+day;
		
		// 검색 시작일자
		smsSearchStartDate = year+'-01-01';
	}
	
	$("#smsSearchStartDate").val(smsSearchStartDate).trigger("change");
	$("#smsSearchEndDate").val(smsSearchEndDate).trigger("change");
}

/****************************************************************************
 * 알림톡 발송내역 정보 리스트 조회
 ****************************************************************************/
function fn_selectListUserMarketingJson() {

    let formData = new FormData();
    formData.append("menuClass", menuClass);
    formData.append("smsSearchKeywordParam", smsSearchKeywordParam);
    formData.append("smsSearchStartDate", smsSearchStartDate);
    formData.append("smsSearchEndDate", smsSearchEndDate);
    formData.append("smsSearchDateType", smsSearchDateType);
    formData.append("smsSort", smsSort);
    formData.append("smsStart", smsStart);
    formData.append("smsLimit", smsLimit);


    $.ajax({
        url: encodeURI('/websms/selectListSms.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async: true,
        success: function (data) {
            if ('0' == data.msgCode) {
                smsTotalCount = data.totalCount;
                $("#marketingSmsTotalCount").text(fn_numberFormat(smsTotalCount)+'명');

                smsTotalPages = Math.ceil(smsTotalCount / smsLimit);
                smsAgGridData = data.rows;
                smsGridOptions.api.setRowData(smsAgGridData);

                if (0 < data.rows.length) {
                    //페이징 처리
                    window.pagObj = $('#smsPagination').twbsPagination({
                        startPage: ((smsStart / smsLimit) + 1),
                        totalPages: (smsTotalPages == 0) ? 1 : smsTotalPages,
                        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_smsPagination(page);
                        }
                    }).on('page', function (event, page) {
                    });

                }
            } else {
                modalEvent.danger("조회 오류", data.msgDesc);
            }

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

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

    fn_smsPaginReset();

    smsSearchKeywordParam  = $("#txt_smsSearchKeyword").val();

	smsSearchDateType  = $("#smsSearchDateType").val();
	smsSearchStartDate = $("#smsSearchStartDate").val();
	smsSearchEndDate   = $("#smsSearchEndDate").val();

    fn_selectListUserMarketingJson();
}

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

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

	fn_smsSearch();
}

/****************************************************************************
 * 페이징 처리
 ****************************************************************************/
function fn_smsPagination(param){
    smsStart = (parseInt(param)-1)*smsLimit;
    fn_selectListUserMarketingJson();
}

/****************************************************************************
 * 페이징 리셋
 ****************************************************************************/
function fn_smsPaginReset(){
    smsSearchKeywordParam      = '';
    smsStart                   = 0;
    smsLimit                   = 100;
    smsTotalCount              = 0;
    smsTotalPages              = 0;

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

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

/****************************************************************************
* 정렬 이벤트
****************************************************************************/
function fn_alignEvent(param, param2){
	let align = "";
	
	if("A"==param){
		align = "오늘";
		
		fn_smsSetDate('A');
	}
	else if("B"==param){
		align = "최근30일";
		
		fn_smsSetDate('D');
	}
	else if("C"==param){
		align = "최근90일";
		
		fn_smsSetDate('E');
	}
	else if("D"==param){
		align = "이번주";
		
		fn_smsSetDate('C');
	}
	else if("E"==param){
		align = "이번달";
		
		fn_smsSetDate('F');
	}
	else if("F"==param){
		align = "올해";
		
		fn_smsSetDate('G');
	}
	else if("G"==param){
		align = "지난주";
		
		fn_smsSetDate('H');
	}
	else if("H"==param){
		align = "지난달";
		
		fn_smsSetDate('I');
	}
	else{
		align = "";
	}
	$("#smsSearchDateType").val(param);
	$("#smsSearchDateType").siblings("button").text(align);
}

/****************************************************************************
 * select box 선택 이벤트
 ****************************************************************************/
function fn_clickSelectBox(target) {
    $(target).find('.select_option_list').toggle();
}

function fn_clickEvent() {
    // $('.select_box').off('click');
//     //$(document).off('click');
//
//     $('.select_box').on('click', function () {
        $('.select_box').not(this).find('.select_option_list').hide();
        // fn_clickSelectBox($(this));
    // });
    // 옵션 선택 이벤트
    $('.select_box').on('click', 'li', function (e) {
        fn_OptionSelection($(this), e);
    });
//
// // 다른 곳을 클릭했을 때 옵션 숨기기
//     $(document).on('click', function (event) {
//         if (!$(event.target).closest('.select_box').length) {
//             $('.user .select_option_list').hide();
//         }
//     });
}

/****************************************************************************
 * 옵션선택
 ****************************************************************************/
function fn_OptionSelection(target,e) {
    // 옵션 선택 이벤트 핸들러
    let selectedOption = $(target).text();
    if ('' !== selectedOption) {
        // 선택된 옵션의 텍스트를 .label 요소에 설정
        $(target).closest('.select_box').find('.label').text(selectedOption);
    } else {
        // 선택된 옵션이 텍스트가 아닌 경우(예: 이미지), .html()을 사용
        selectedOption = $(target).html();
        $(target).closest('.select_box').find('.label').html(selectedOption);
    }
    $(target).closest('.select_box').find('input')?.val($(target).attr('id')??selectedOption);
    $(target).closest('.select_box').find('.option_list_item').removeClass('selected');
    $(target).addClass('selected');
    // $(target).closest('.select_option_list').hide();

    // e.stopPropagation();
}

/****************************************************************************
 * 검색필터 조회
 ****************************************************************************/
function fn_selectCategoryList(){
    let result = []
    let formData = new FormData();
    formData.append("menuClass", menuClass);
    $.ajax({
        url: encodeURI('/webcategory/selectCategoryList.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async: false,
        success: function(data){
            if('0'==data.msgCode){
                if(0<data.rows.length){
                    result = data.rows;
                }
            }
            else{
                modalEvent.danger("조회 오류", data.msgDesc);
            }
        },
        error : function(xhr, status, error) {
            modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
        },
        beforeSend:function(){

        },
        complete:function(){

        }
    });
    return result;
}

function fn_selectListOtherOption(categoryCode){
    let formData = new FormData();
    formData.append('categoryCode',categoryCode);
    $.ajax({
        url: encodeURI('/webcategory/selectCategoryItem.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async: false,
        success: function(data){
            if('0'==data.msgCode){
                let listHTML = '';
                if (0 < Object.keys(data.rows).length) {
                    Object.keys(data.rows).forEach(category => {
                        // for(let i = 0; i < data.rows[key].length; i++){
                        let categoryItem = data.rows[category];
                        let categoryItemCode = categoryItem.categoryItemCode;
                        let categoryItemName = categoryItem.categoryItemName;

                        let selectedYn = '';
                        let nationality = '';

                        if(categoryItem.categoryName === '국적') {
                             nationality = categoryItemName.toLowerCase().includes('한국'.toLowerCase()) ? 'local' : 'foreigner';
                        }
                        if(categoryItem.filePath){
                            let url = categoryItem.filePath.replace("C:", "");
                            categoryItemName = `<img src="${url}">`
                        }
                        listHTML = `<li class="option_list_item ${nationality}" data-code="${categoryCode}" id="${categoryItemCode}">${categoryItemName}</li>`;
                        let categoryName = categoryItem.categoryName;
                        $('.select_box button').each(function() {
                            if ($(this).text() === categoryName) {
                                $(this).parent().find('ul').append(listHTML);
                            }
                        });
                    });
                }

            }else if(data.msgCode=='-1'){
                modalEvent.warning("조회 오류", data.msgDesc);
            }else{
                modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            }
        },
        error : function(xhr, status, error) {
            modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
        },
        beforeSend:function(){
        },
        complete:function(){
        }
    });
}

function fn_selectSmsIntro(param){
    let reqParam =  {
        "muSmsId" : param
    };

    if("Y"==selectUseYn){
        marketingSmsSelectModal.popup(function(obj, reqParam) {
            fn_smsSearch();
        }, reqParam);
    }

}

function userTypeCellRenderer(params) {
    if(!params.value)
        return
        if('T'===params.value)
            return '간편예약고객';
        if('Y'===params.value||''===params.value)
            return '-';
        else
            return `<img src="${params.value.replace("C:", "")}" alt="고객구분">`;
}

let smsColumnDefs = [
        /*{
            field: "checkbox",
            headerName: "",
            minWidth: 55,
            maxWidth: 55,
            headerCheckboxSelection: true,
            checkboxSelection: true
        },*/
        {field: "rowNum", headerName:"번호", minWidth:60, maxWidth:60, sortable: false, cellStyle:{textAlign: 'center'}},
        {field: "userName", headerName: "고객명", minWidth: 100, maxWidth: 140},
        {field: "nationality", headerName: "국적", minWidth: 90, maxWidth: 90},
        {field: "birthday", headerName: "생년월일", minWidth: 100, maxWidth: 130},
        {field: "age", headerName: "나이", minWidth: 100, maxWidth: 130},
        {field: "gender", headerName: "성별", minWidth: 70,maxWidth: 90},
        {field: "userType", headerName: "고객구분", minWidth: 70, maxWidth: 130, cellRenderer: userTypeCellRenderer},
        {field: "smsContent", headerName: "전송내용", minWidth: 260, maxWidth: 260, cellStyle:{cursor: 'pointer', color:'#3985EA'}},
        {field: "popbillState", headerName: "팝빌 전송상태", minWidth: 130, maxWidth: 130},
        {field: "memberName", headerName: "담당자", minWidth: 100, maxWidth: 230},
        {field: "sendDate", headerName: "전송일자", minWidth: 100, maxWidth: 230}
];

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

    },
    onRowSelected: function (event) { // 체크박스 선택

    },
    onSortChanged: function (event) {
        //정렬
        smsSort = ''; //기존 정렬 초기화
        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) {
                    smsStart = 0;

                    smsSort += gridSortModel + ' ' + gridSort + ',';

                } else {
                    nullCnt++;

                    if (nullCnt == columnArr.length) {
                        smsSort = '';
                        smsDir = '';

                        smsStart = 0;
                    }
                }
            }
        }

        smsSort = smsSort.substring(0, smsSort.lastIndexOf(",")); //맨끝 콤마 지우기

        fn_smsSearch();
    }
};

let smsGridDiv = document.querySelector('#smsGrid');

new agGrid.Grid(smsGridDiv, smsGridOptions);

function fn_setSelectBox(num){
    let category=fn_selectCategoryList();
    for(let i = 0; i < num; i++){
        let categoryCode     = category[i].categoryCode;
        if(num>2){
            fn_selectModalOtherOption(categoryCode)
        }else{
            fn_selectListOtherOption(categoryCode);
        }
    }
}

/****************************************************************************
* 페이지 init
****************************************************************************/
function fn_pageInit(){
	// 날짜 datepicker
	fn_searchDatePicker("#divSmsSearchStartDate", "#divSmsSearchEndDate");
	
	if(!smsSearchStartDate&&!smsSearchEndDate){
		// 검색 오늘날짜 셋팅
		fn_smsSetDate('D');
	}else{
		$("#smsSearchStartDate").val(smsSearchStartDate).trigger("change");;
		$("#smsSearchEndDate").val(smsSearchEndDate).trigger("change");;
	}
	
	// 초기 페이징 처리
	$("#smsSearchKeyword").val(smsSearchKeywordParam);

    // fn_clickEvent();
	
	fn_smsSearch("A");
}

/****************************************************************************
* 페이지 event
****************************************************************************/
function fn_pageEvent(){
	// 검색 input
	$(document).on('keypress', '#txt_smsSearchKeyword', function(e) {
		fn_smsEnter(e);
	});
	
	// 검색 조회 버튼
	$("#searchBtn").click(function () {
		fn_smsSearch();
	});

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