function fn_init(){
    fn_selectPhysicalList();
}


document.getElementById('downLoadBtn').addEventListener('click',()=>{
    fn_downloadPhysicalExcel();
});

document.getElementById('inbody_btn').addEventListener('click',()=>{
    fn_insertInbodyApi();
});

/****************************************************************************
 * 고객 신체기록 리스트 조회
 ****************************************************************************/
function fn_selectPhysicalList(){
    var formData = new FormData();
    formData.append("muUserId",muUserId);
    formData.append("userStart",userStart);
    formData.append("userLimit",userLimit);
    formData.append("menuClass", menuClass);

    $.ajax({
        url: encodeURI('/webuser/selectUserPhysicalList.do'),
        data: formData,
        dataType: 'json',
        processData: false,
        contentType: false,
        type: 'POST',
        async: true,
        success: function(data){
            if('0'==data.msgCode){
                userTotalCount  = data.totalCount;
                userTotalPages = Math.ceil(userTotalCount/userLimit);
                muUserData = data.recentData;
                document.getElementById("userName").innerHTML = `${muUserData.userName}<span id="userInfo"></span>`;

                if(0<userTotalCount){
                    let userInfo = `(${muUserData.writeDate}, ${muUserData.height}cm, ${muUserData.weight}kg, ${muUserData.bmi}kg/m2)`;
                    document.getElementById("userInfo").textContent=userInfo
                }
                userAgGridData = data.rows.map(item => {
                    const formatWithDecimal = value => Number.isInteger(value) ? `${value}.0` : value.toString();
                    // 각 필드에 대한 단위 추가
                    item.height = formatWithDecimal(item.height) + " cm";
                    item.weight = formatWithDecimal(item.weight) + " kg";
                    item.muscle = formatWithDecimal(item.muscle) + " kg";
                    item.fatMass = formatWithDecimal(item.fatMass) + " kg";
                    item.fatPercent = formatWithDecimal(item.fatPercent) + " %";
                    item.bmi = formatWithDecimal(item.bmi) + " kg/m2";
                    return item;
                });
                userGridOptions.api.setRowData(userAgGridData);

                if(0<userTotalCount){
                    //페이징 처리
                    window.pagObj = $('#userPagination').twbsPagination({
                        startPage    : ((userStart/userLimit)+1),
                        totalPages   : (userTotalPages==0)?1:userTotalPages,
                        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_userPagination(page);
                        }
                    }).on('page', function (event, page) {
                    });
                }
            }else{
                modalEvent.danger("조회 오류", data.msgDesc);
            }
        },
        error : function(xhr, status, error) {
            modalEvent.danger("조회 오류", "정상적으로 수행되지 않았습니다. 관리자에게 문의하시기 바랍니다.");
        },
        beforeSend:function(){
        },
        complete:function(){
        }
    });
}
/****************************************************************************
 * 페이징 처리
 ****************************************************************************/
function fn_userPagination(param){
    userStart = (parseInt(param)-1)*userLimit;
    fn_selectPhysicalList();
}

/****************************************************************************
 * 컬럼명 클릭(재정렬)
 ****************************************************************************/
function fn_userSearch(param){
    if("A"!=param && "Y"!=selectUseYn){
        modalEvent.warning("", "조회 권한이 없습니다.");
        return false;
    }

    fn_userPaginReset();
    fn_selectPhysicalList();
}
/****************************************************************************
 * 엑셀 다운 다운로드
 ****************************************************************************/
function fn_downloadPhysicalExcel(){
    if("Y"==downloadUseYn){
        // 수정가능
        let pagingParam = "?menuClass="+menuClass;
        pagingParam    += "&userSort="+userSort;
        pagingParam    += "&userDir="+userDir;
        pagingParam    += "&userStart="+userStart;
        pagingParam    += "&userLimit="+userLimit;
        pagingParam    += "&muUserId="+muUserId;

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


/****************************************************************************
 * 고객 인바디 정보 조회
 ****************************************************************************/
function fn_insertInbodyApi(){
	
	modalEvent.info("등록", "고객의 인바디 정보를 불러오기하시겠습니까?", function(){
		var formData = new FormData();
	    formData.append("menuClass", menuClass);
	    formData.append("muUserId",muUserId);
	
		$.ajax({
			url: encodeURI('/webuser/insertUserPhysicalInbodyApi.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_selectPhysicalList();
					});
				}
				else{
					modalEvent.danger("등록 오류", data.msgDesc);
				}
			},
			error : function(xhr, status, error) {
				modalEvent.danger("등록 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend:function(){
				
			},
			complete:function(){
				
			}
		});
	});
}
/****************************************************************************
 * 고객 신체기록 등록팝업
 ****************************************************************************/
document.getElementById('insertBtn').addEventListener('click',()=> {
    let reqParam =  {
    };
    if("Y"==insertUseYn){
        // 조회만
        userPhysicalInsertModal.popup(function(obj, reqParam) {
            fn_selectPhysicalList();
        }, reqParam);
    }
})
/****************************************************************************
 * 고객 신체기록 상세보기
 ****************************************************************************/
function fn_selectUserPhysicalPopup(param){
	let reqParam =  {
		"muUserPhysicalId" : param
	};
	
	if("Y"==selectUseYn){
		// 조회만
		userPhysicalSelctModal.popup(function(obj, reqParam) {
			fn_selectPhysicalList();
		}, reqParam);
	}
}

var userColumnDefs = [
    {field: "checkbox", headerName:"", minWidth:55, maxWidth:55, headerCheckboxSelection: true, checkboxSelection: true},
    {field: "rowNum", headerName:"번호", minWidth:60,sortable: false, cellStyle:{textAlign: 'center'}},
    {field: "writeDate", headerName:"날짜", minWidth:100, maxWidth:100, cellStyle:{cursor: 'pointer', color:'#3985EA'}},
    {field: "height", headerName:"키", minWidth:100,maxWidth:100},
    {field: "weight", headerName:"체중", minWidth:100,maxWidth:100},
    {field: "muscle", headerName:"골격근량", minWidth:100, maxWidth:100},
    {field: "fatMass", headerName:"체지방량", minWidth:100, maxWidth:100},
    {field: "fatPercent", headerName:"체지방률", minWidth:100,maxWidth:100},
    {field: "bmi", headerName:"BMI", minWidth:130, maxWidth:130},
    {field: "memberName", headerName:"담당자",minWidth:100, maxWidth:130},
    {field: "memo", headerName:"메모",minWidth:600},
];

// let the grid know which columns and what data to use
var userGridOptions = {
    suppressRowTransform: true,
    columnDefs: userColumnDefs,
    defaultColDef: {		// 리스트 기본 설정
        flex: 1,
        sortable: true,		//정렬 여부
        resizable: true,	//리사이즈
        editable: false,		// 그리드에서 데이터 수정
        cellStyle:{textAlign:'left',fontSize:'14px',padding:'10'},
        //suppressSizeToFit:true,		//자동 맞춤
        //enableRowGroup: true,		// 그룹 묶음
        enablePivot: true,
        enableValue : true
    },
    //suppressMultiSort:true,  //단일솔트 true가 단일, false가 다중 shift + sort 시
    headerHeight : 41, // header 높이
    rowHeight : 41, // row 높이
    rowData : userAgGridData,
    suppressRowClickSelection : true, // 로우 클릭시 체크박스 선택 true no, false yes
    localeText : {
        noRowsToShow : '조회 결과가 없습니다.'
    }, //데이터 없을 시 나오는 문구
    rowSelection : 'multiple', // row 다중 선택
    debug : false,
    onCellClicked: function(event){ //셀 클릭 이벤트
        /* alert(event.column.colId); */
        if(event.column.colId=='writeDate'){
            fn_selectUserPhysicalPopup(event.data.muUserPhysicalId);
        }
    },
    onSelectionChanged: function(event){ //체크박스 선택
        var selectRows = [];
        selectRows = event.api.getSelectedRows();

        userSelectId = '';

        for(var i=0; i<selectRows.length; i++){
            userSelectId += selectRows[i].muUserId + ",";
        }

        userSelectId = userSelectId.substring(0, userSelectId.lastIndexOf(','));
    },
    onSortChanged: function(event){
        //정렬
        userSort = ''; //기존 정렬 초기화
        var columnArr = event.columnApi.getColumnState();
        if(0<columnArr.length){

            //sort index 순으로 재정렬
            columnArr.sort(function(a,b){
                return a.sortIndex - b.sortIndex;
            });


            var nullCnt = 0;
            for(var i=0; i<columnArr.length; i++){
                var gridSortModel = columnArr[i].colId;
                var gridSort = columnArr[i].sort;

                if(gridSort != null){
                    userStart = 0;

                    userSort += gridSortModel+' '+ gridSort + ',';

                }else{
                    nullCnt++;

                    if(nullCnt == columnArr.length){
                        userSort = '';
                        userDir = '';

                        userStart = 0;
                    }
                }
            }
        }

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

        fn_userSearch();
    }
};

// lookup the container we want the Grid to use
var userGridDiv = document.querySelector('#userGrid');

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

fn_init();