/* 페이징 관련 변수 */
let userOriginalChartTotalCount   = 0;
let userOriginalChartTotalPages   = 0;
let selectRows = [];
/*aggird*/
let userOriginalChartAgGridData = [];

let userOriginalChartSelectId = "";

/****************************************************************************
* 진료 콤보데이타 설정
****************************************************************************/
function fn_setChartDiviCombo(){
	let target = $("#sel_chartDivi");

	target.find("li.option_list_item").click(function () {
		// 1. 선택값 셋팅
		let selectValue = $(this).data("value");
		let selectName  = $(this).text();

		$(this).parent().siblings("button").text(selectName);
		$(this).parent().siblings("input").val(selectValue);
	});

	// 초기화
	target.find("li:eq(0)").click();
}


/****************************************************************************
* 고객 상세 - 고객 상담차트 정보 리스트 조회 (List)
****************************************************************************/
function fn_selectListUserOriginalChart(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("sort", userOriginalChartSort);
	formData.append("dir", userOriginalChartDir);
	formData.append("start", userOriginalChartStart);
	formData.append("limit", userOriginalChartLimit);
	formData.append("searchChartDivi", searchChartDivi);
	formData.append("muUserId", muUserId);

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

				userOriginalChartTotalPages = Math.ceil(userOriginalChartTotalCount/userOriginalChartLimit);
				
				// 리스트 조회
				userOriginalChartAgGridData = data.rows;
				userOriginalChartGridOptions.api.setRowData(userOriginalChartAgGridData);
				
				if(0<data.rows.length){
					//페이징 처리
					window.pagObj = $('#userOriginalChartPagination').twbsPagination({
						startPage    : ((userOriginalChartStart/userOriginalChartLimit)+1),
						totalPages   : (userOriginalChartTotalPages==0)?1:userOriginalChartTotalPages,
						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_userOriginalChartPagination(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(){
			// 로딩열기
			userOriginalChartGridOptions.api.showLoadingOverlay();
		},
		complete:function(){
			
		}
	});
}

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

	searchChartDivi = $("#userOriginalChartDivi").val();
	
	fn_selectListUserOriginalChart();
}


/****************************************************************************
* 초기화하기
****************************************************************************/
function fn_userOriginalChartReset(){

	fn_userOriginalChartSearch();
}

/****************************************************************************
* 페이징 처리
****************************************************************************/
function fn_userOriginalChartPagination(param){
	userOriginalChartStart = (parseInt(param)-1)*userOriginalChartLimit;
	
	fn_selectListUserOriginalChart();
}

/****************************************************************************
* 페이징 리셋
****************************************************************************/
function fn_userOriginalChartPaginReset(){

	userOriginalChartStart        = 0;
	userOriginalChartLimit        = 100;
	userOriginalChartTotalCount   = 0;
	userOriginalChartTotalPages   = 0;
	
	//페이징 초기화
	if($("#userOriginalChartPagination").data("twbs-pagination")){
		$("#userOriginalChartPagination").twbsPagination("destroy");
	}
}


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

/****************************************************************************
* 완료
****************************************************************************/
function fn_userOriginalChartOk(){
	fn_userOriginalChartReset();
}

function fn_userOriginalChartCancel(){
	let pagingParam = "?menuClass="+menuClass;
	pagingParam    += "&searchChartDivi="+searchChartDivi;
	pagingParam    += "&userOriginalChartSort="+userOriginalChartSort;
	pagingParam    += "&userOriginalChartDir="+userOriginalChartDir;
	pagingParam    += "&userOriginalChartStart="+userOriginalChartStart;
	pagingParam    += "&userOriginalChartLimit="+userOriginalChartLimit;
	pagingParam    += "&muUserId="+muUserId;

	fn_leftFormAction("/webuseroriginalchart/selectListUserOriginalChartIntro.do"+pagingParam);
}

/****************************************************************************
* 수정 화면으로 이동.
****************************************************************************/
function fn_updateUserOriginalChartIntro(param){
	if("Y"!=selectUseYn){
		modalEvent.warning("", "조회 권한이 없습니다.");
		return false;
	}

	let reqParam =  {"pId":param};
	userOriginalChartSelectModal.popup(function(obj, reqParam) {

	}, reqParam);
}

let userOriginalChartColumnDefs = [
	/*{field: "checkbox", headerName:"", minWidth: 50, maxWidth: 50, headerCheckboxSelection: true, checkboxSelection: true},*/
	/* {field: "rowNum", headerName:"번호", minWidth: columnWidth, maxWidth: columnWidth, sortable: false}, */
	{field: "rowNum", headerName:"번호", minWidth:60, maxWidth: 60,sortable: false, cellStyle:{textAlign: 'center'}},
	{field: "chartDivi", headerName:"차트 구분", minWidth: 150, maxWidth: 150, cellStyle:{cursor: 'pointer', color:'#3985EA'}},
	{field: "picName", headerName:"종류", minWidth: 90},
	{field: "picTitle", headerName:"제목", minWidth: 120},
	{field: "crmDocName", headerName:"담당의사", minWidth: 100, maxWidth: 100},
	{field: "crmStaffName", headerName:"담당직원", minWidth: 100, maxWidth: 100},
	{field: "writeDate", headerName:"작성일자",minWidth:100, maxWidth:100}
];

// let the grid know which columns and what data to use
let userOriginalChartGridOptions = {
	suppressRowTransform: true,
	columnDefs: userOriginalChartColumnDefs,
	defaultColDef: {		// 리스트 기본 설정
		flex: 1,
		sortable: true,		//정렬 여부
		resizable: true,	//리사이즈
		editable: false,	// 그리드에서 데이터 수정
		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 : userOriginalChartAgGridData,
	suppressRowClickSelection : true, // 로우 클릭시 체크박스 선택 true no, false yes
	localeText : {
		noRowsToShow : '조회 결과가 없습니다.'
	}, //데이터 없을 시 나오는 문구
	rowSelection : 'multiple', // row 다중 선택
	debug : false,
	onCellClicked: function(event){ //셀 클릭 이벤트
		if(event.column.colId=='chartDivi'){
			fn_updateUserOriginalChartIntro(event.data.pId);
		}
	},
	onSelectionChanged: function(event){ //체크박스 선택
		selectRows = event.api.getSelectedRows();
	},
	onSortChanged: function(event){
		 //정렬
		userOriginalChartSort = ''; //기존 정렬 초기화
		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){
					userOriginalChartStart = 0;
					userOriginalChartSort += gridSortModel+' '+ gridSort + ',';
				}
				else{
					nullCnt++;
					if(nullCnt == columnArr.length){
						userOriginalChartSort = '';
						userOriginalChartDir = '';
						userOriginalChartStart = 0;
					}
				}
			}
		}
		userOriginalChartSort = userOriginalChartSort.substring(0,userOriginalChartSort.lastIndexOf( ",")); //맨끝 콤마 지우기

		fn_userOriginalChartSearch();
	}
};

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

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


/****************************************************************************
* 페이지 init
****************************************************************************/
function fn_pageInit(){
	
	// 진료 콤보데이타 설정
	fn_setChartDiviCombo();
		
	
	
	fn_userOriginalChartSearch("A");
}



/****************************************************************************
* 페이지 event
****************************************************************************/
function fn_pageEvent(){
	// 검색 조회 버튼
	$("#btnSearchUserReserveHistory").click(function () {
		fn_userOriginalChartSearch();
	});
}

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