/* 페이징 관련 변수 */
let membershipProcedureTotalCount = 0;
let membershipProcedureTotalPages = 0;

/*aggird*/
let membershipProcedureAgGridData = [];
let membershipSelectedId   = "";

let selectRows = [];
/****************************************************************************
 * 멤버십 고객 정보 리스트 조회
 ****************************************************************************/
function fn_selectListMembershipProcedureJson(){
    let formData = new FormData();
    formData.append("menuClass", menuClass);
    formData.append("membershipProcedureSort", membershipProcedureSort);
    formData.append("membershipProcedureDir", membershipProcedureDir);
    formData.append("membershipProcedureStart", membershipProcedureStart);
    formData.append("membershipProcedureLimit", membershipProcedureLimit);

    $.ajax({
        url: encodeURI('/webmembership/selectListMembershipProcedure.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async: true,
        success: function(data){
            if('0'==data.msgCode){
                // 페이징 처리
                membershipProcedureTotalCount  = data.totalCount;
                membershipProcedureTotalPages = Math.ceil(membershipProcedureTotalCount/membershipProcedureLimit);

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

                if(0<data.rows.length){
                    //페이징 처리
                    window.pagObj = $('#membershipProcedurePagination').twbsPagination({
                        startPage    : ((membershipProcedureStart/membershipProcedureLimit)+1),
                        totalPages   : (membershipProcedureTotalPages===0)?1:membershipProcedureTotalPages,
                        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_membershipProcedurePagination(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_deleteMembershipProcedure(){
    if("Y"!=deleteUseYn){
        modalEvent.warning("", "삭제 권한이 없습니다.");
        return false;
    }

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

    modalEvent.info("삭제", "선택한 멤버십 상품을 삭제하시겠습니까?", function(){
        let formData = new FormData();
        formData.append("menuClass", menuClass);
        formData.append("muTreatmentProcedureId", membershipSelectedId);

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

            },
            complete:function(){

            }
        });
    });
}
/****************************************************************************
 * 멤버십상품추가 모달
 ****************************************************************************/
function fn_insertMembershipProcedure(){
    if("Y"!=insertUseYn){
        modalEvent.warning("", "등록 권한이 없습니다.");
        return false;
    }

    let reqParam =  {};
    membershipProcedureModal.popup(function(obj, reqParam) {
        fn_membershipOk();
    }, reqParam);
}

/****************************************************************************
 * 초기화하기
 ****************************************************************************/
function fn_membershipReset(){
    fn_membershipProcedurePaginReset();
    fn_selectListMembershipProcedureJson();
}

/****************************************************************************
 * 페이징 처리
 ****************************************************************************/
function fn_membershipProcedurePagination(param){
    membershipProcedureStart = (parseInt(param)-1)*membershipProcedureLimit;

    fn_selectListMembershipProcedureJson();
}

/****************************************************************************
 * 페이징 리셋
 ****************************************************************************/
function fn_membershipProcedurePaginReset(){
    membershipProcedureStart        = 0;
    membershipProcedureLimit        = 100;
    membershipProcedureTotalCount   = 0;
    membershipProcedureTotalPages   = 0;

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


/****************************************************************************
 * 완료
 ****************************************************************************/
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    += "&membershipProcedureStart="+membershipProcedureStart;
        pagingParam    += "&membershipProcedureLimit="+membershipProcedureLimit;
        pagingParam    += "&pageType="+"userDetail";
        pagingParam    += "&muUserId="+param;

        fn_leftFormAction("/webmembership/updateMembershipIntro.do"+pagingParam);
    }
    else{
        modalEvent.warning("", "조회 및 수정 권한이 없습니다.");
        return false;
    }
}
function fn_formatAmount(amount){
    let data = typeof amount === 'number'?amount:amount.value;
    if(data>0)
        return data.toLocaleString();
    else
        return '-'
}

let membershipColumnDefs = [
    // {field: "checkbox", headerName:"", minWidth:55, maxWidth:55, headerCheckboxSelection: true, checkboxSelection: true},

    {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: "treatmentProcedureName", headerName:"멤버십 상품명", minWidth:150, maxWidth:150},
    {field: "totalPrice", headerName:"상품금액(원)",minWidth:262,cellRenderer:fn_formatAmount},
    {field: "price", headerName:"공급가(원)",minWidth:262,cellRenderer:fn_formatAmount},
    {field: "vat", headerName:"VAT(원)",minWidth:262,cellRenderer:fn_formatAmount},
    {field: "additionalAmount", headerName:"추가지급액(원)",minWidth:262,cellRenderer:fn_formatAmount},
    {field: "totalAmount", headerName:"총지급액(원)",minWidth:262,cellRenderer:fn_formatAmount},
];

// 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 : membershipProcedureAgGridData,
    suppressRowClickSelection : true, // 로우 클릭시 체크박스 선택 true no, false yes
    localeText : {
        noRowsToShow : '조회 결과가 없습니다.'
    }, //데이터 없을 시 나오는 문구
    rowSelection : 'multiple',        // row 다중 선택
    debug : false,
    onCellClicked: function(event){   //셀 클릭 이벤트
        console.log(event.column.colId);
    },
    onSelectionChanged: function(event){ //체크박스 선택
        let selectRows = [];
        selectRows = event.api.getSelectedRows();

        membershipSelectedId = '';
        for(let i=0; i<selectRows.length; i++){
            membershipSelectedId += selectRows[i].muTreatmentProcedureId + ",";
        }
        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){
                    membershipProcedureStart = 0;
                    membershipSort += gridSortModel+' '+ gridSort + ',';
                }
                else{
                    nullCnt++;

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

        fn_membershipProcedureSearch();
    }
};

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

// 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(){
    fn_membershipOk();
}

/****************************************************************************
 * 페이지 event
 ****************************************************************************/
function fn_pageEvent(){
     $('.membership_registration_btn').on('click',function(){
         fn_insertMembershipProcedure();
     });
    $("#btnDeleteMembershipProcedure").click(function () {
        fn_deleteMembershipProcedure(selectRows);
    });
}

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

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