/* 페이징 관련 변수 */
let membershipTotalCount = 0;
let membershipTotalPages = 0;

/*aggird*/
let membershipAgGridData = [];

let membershipSelectedId   = "";

/****************************************************************************
 * 멤버십 고객 정보 리스트 조회
 ****************************************************************************/
function fn_selectListMembershipJson(){
    let formData = new FormData();
    formData.append("menuClass", menuClass);
    formData.append("membershipSearchKeywordParam", membershipSearchKeywordParam);
    formData.append("membershipSort", membershipSort);
    formData.append("membershipDir", membershipDir);
    formData.append("membershipStart", membershipStart);
    formData.append("membershipLimit", membershipLimit);

    $.ajax({
        url: encodeURI('/webmembership/selectListMembership.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async: true,
        success: function(data){
            if('0'==data.msgCode){
                // 페이징 처리
                membershipTotalCount  = data.totalCount;
                $("#totalMembershipUser").text(data.totalMembershipCount+' 명')
                if(data.sumMembershipBalanceMap[0]){
                    let balance = data.sumMembershipBalanceMap[0];
                    $("#sumChargeBalance").text((balance.sumChargeBalance !== '0' ? '+' : '') + balance.sumChargeBalance + ' 원');

                    $("#sumUsageBalance").text((balance.sumUsageBalance !== '0' ? '-' : '') + balance.sumUsageBalance+' 원');
                }
                membershipTotalPages = Math.ceil(membershipTotalCount/membershipLimit);

                // 리스트 조회
                membershipAgGridData = data.rows.map((item, index) => ({
                    ...item,
                    rowNum: index + 1
                }));
                membershipGridOptions.api.setRowData(membershipAgGridData);

                if(0<data.rows.length){
                    //페이징 처리
                    window.pagObj = $('#membershipPagination').twbsPagination({
                        startPage    : ((membershipStart/membershipLimit)+1),
                        totalPages   : (membershipTotalPages==0)?1:membershipTotalPages,
                        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_membershipPagination(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(){
            // 로딩열기
            membershipGridOptions.api.showLoadingOverlay();
        },
        complete:function(){

        }
    });
}

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

    fn_membershipPaginReset();

    membershipSearchKeywordParam = $("#membershipSearchKeyword").val();

    fn_selectListMembershipJson();
}


/****************************************************************************
 * 초기화하기
 ****************************************************************************/
function fn_membershipReset(){
    $("#memberSearchKeyword").val('');

    fn_membershipSearch();
}

/****************************************************************************
 * 페이징 처리
 ****************************************************************************/
function fn_membershipPagination(param){
    membershipStart = (parseInt(param)-1)*membershipLimit;

    fn_selectListMembershipJson();
}

/****************************************************************************
 * 페이징 리셋
 ****************************************************************************/
function fn_membershipPaginReset(){
    membershipSearchKeywordParam = '';

    membershipStart        = 0;
    membershipLimit        = 100;
    membershipTotalCount   = 0;
    membershipTotalPages   = 0;

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

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

/****************************************************************************
 * 완료
 ****************************************************************************/
function fn_membershipOk(){
    fn_membershipReset();
}

/****************************************************************************
 * 멤버십 고객상세내역  화면으로 이동.
 ****************************************************************************/
function fn_updateMembershipIntro(param){
    if("Y"==updateUseYn){
        // 수정가능
        let pagingParam = "?menuClass="+menuClass;
        pagingParam    += "&membershipSearchKeywordParam="+membershipSearchKeywordParam;
        pagingParam    += "&membershipSort="+membershipSort;
        pagingParam    += "&membershipDir="+membershipDir;
        pagingParam    += "&membershipStart="+membershipStart;
        pagingParam    += "&membershipLimit="+membershipLimit;
        pagingParam    += "&pageType="+"userDetail";
        pagingParam    += "&muUserId="+param;

        fn_leftFormAction("/webmembership/updateMembershipIntro.do"+pagingParam);
    }
    else{
        modalEvent.warning("", "조회 및 수정 권한이 없습니다.");
        return false;
    }
}
/****************************************************************************
 * 수정 화면으로 이동.
 ****************************************************************************/
function fn_updateUserIntro(param) {
    if ("Y" == updateUseYn || "Y" == selectUseYn) {
        // 수정가능
        let pagingParam = "?muUserId=" + param;
        fn_leftFormAction2('0201010205', "/webmembership/updateMembershipIntro.do" + pagingParam);
    } else {
        modalEvent.warning("", "조회 및 수정 권한이 없습니다.");
        return false;
    }
}
/****************************************************************************
 * 엑셀 다운 다운로드
 ****************************************************************************/
function fn_downloadMembershipExcel(){
    if("Y"==downloadUseYn){
        // 수정가능
        let pagingParam = "?menuClass="+menuClass;
        pagingParam    += "&membershipSearchKeywordParam="+membershipSearchKeywordParam;
        pagingParam    += "&membershipSort="+membershipSort;
        pagingParam    += "&membershipDir="+membershipDir;
        pagingParam    += "&membershipStart="+membershipStart;
        pagingParam    += "&membershipLimit="+membershipLimit;

        let url = encodeURI("/webmembership/downloadMembershipExcel.do"+pagingParam);
        $("#excelForm").prop("action",url);
        $("#excelForm").submit();
    }
    else{
        modalEvent.warning("", "내려받기 권한이 없습니다.");
        return false;
    }
}



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

let membershipColumnDefs = [
    // {field: "checkbox", headerName:"", minWidth:55, maxWidth:55, headerCheckboxSelection: true, checkboxSelection: true},
     {field: "rowNum", headerName:"번호", minWidth:60,cellStyle:{textAlign: 'center'}},
    {field: "userName", headerName:"고객명",minWidth: 170, maxWidth: 170, cellStyle:{cursor: 'pointer', color:'#3985EA'}},
    {field: "nationality", headerName:"국적", minWidth:120, maxWidth:120},
    {field: "birth", headerName:"생년월일",minWidth:170,maxWidth:170},
    {field: "age", headerName:"나이",minWidth:120, maxWidth:120},
    {field: "gender", headerName:"성별",minWidth:120, maxWidth:120},
    {field: "phoneNumber", headerName:"연락처",minWidth:200, maxWidth:200, valueFormatter: fn_phoneFormatter},
    {field: "membershipBalance", headerName:"멤버십 잔액",minWidth:211,maxWidth:211, cellStyle:{textAlign: 'right',cursor: 'pointer', color:'#3985EA'}},
    {field: "lastRechargeDate", headerName:"최근 충전일",minWidth:200,maxWidth:200},
    {field: "lastUseDate", headerName:"최근 사용일",minWidth:200,maxWidth:200}
];

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

    },
    onSelectionChanged: function(event){ //체크박스 선택
        let selectRows = [];
        selectRows = event.api.getSelectedRows();

        membershipSelectedId = '';
        for(let i=0; i<selectRows.length; i++){
            membershipSelectedId += selectRows[i].muMemberId + ",";
        }
        membershipSelectedId = membershipSelectedId.substring(0, membershipSelectedId.lastIndexOf(','));
    },
    onSortChanged: function(event){
        //정렬
        membershipSort = ''; //기존 정렬 초기화
        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){
                    membershipStart = 0;
                    membershipSort += gridSortModel+' '+ gridSort + ',';
                }
                else{
                    nullCnt++;

                    if(nullCnt == columnArr.length){
                        membershipSort  = '';
                        membershipDir   = '';
                        membershipStart = 0;
                    }
                }
            }
        }
        membershipSort = membershipSort.substring(0,membershipSort.lastIndexOf( ",")); //맨끝 콤마 지우기

        fn_membershipSearch();
    }
};

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

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


/****************************************************************************
 * 페이지 init
 ****************************************************************************/
function fn_pageInit(){
    $("#memberSearchKeyword").val(membershipSearchKeywordParam);

    fn_membershipSearch("A");
}

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

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

    // 엑셀다운
    $("#btnDownloadMembershipExcel").click(function () {
        fn_downloadMembershipExcel();
    });
}

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

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