/* 페이징 관련 변수 */
let treatmentProcedureTotalCount   = 0;
let treatmentProcedureTotalPages   = 0;

/*aggird*/
let treatmentProcedureAgGridData = [];

let treatmentProcedureSelectId = "";

/****************************************************************************
* 진료 정보 리스트 조회
****************************************************************************/
function fn_selectListTreatment(){
	let formData = new FormData();
	formData.append("menuClass", menuClass);

	$.ajax({
		url: encodeURI('/webtreatment/selectListTreatment.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				$("#diagnosisList li").not(":lt(2)").remove();
				
				let listHTML = '';
				
				if(0<data.rows.length){
					for(let i = 0; i < data.rows.length; i++){
						let muTreatmentId     = data.rows[i].muTreatmentId;
						let treatmentName     = data.rows[i].treatmentName;
						let procedureCount    = data.rows[i].procedureCount;
						
						listHTML += '<li>';
						listHTML += '	<div onclick="javascript:fn_selectListTreatmentProcedure(\''+muTreatmentId+'\');" class="diagnosis_division_box">'+treatmentName+'</div>';
						listHTML += '	<div onclick="javascript:fn_selectListTreatmentProcedure(\''+muTreatmentId+'\');" class="surgery_box">'+procedureCount+'</div>';
						listHTML += '	<div class="dropdown_box">';
						listHTML += '		<button type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">';
						listHTML += '			<img src="/image/web/day_list_dropdown_icon.svg" alt="dropdown"/>';
						listHTML += '		</button>';
						listHTML += '		<ul class="dropdown-menu" aria-labelledby="dLabel">';
						listHTML += '			<li onclick="javascript:fn_deleteTreatment(\''+muTreatmentId+'\');">';
						listHTML += '				<p class="list red_list">진료항목삭제</p>';
						listHTML += '			</li>';
						listHTML += '		</ul>';
						listHTML += '	</div>';
						listHTML += '</li>';
					}
					$("#diagnosisList").append(listHTML);
					
					fn_selectListTreatmentProcedure(data.rows[0].muTreatmentId);
				}
			}
			else{
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){
			
		},
		complete:function(){
			
		}
	});
}

// 진료 추가 row
function fn_addTreatmentRow(){
	fn_cancelTreatment();
	
	let addRowHTML = '';
	
	addRowHTML += '<li class="on open liAddRow">';
	addRowHTML += '	<div>';
	addRowHTML += '		<input type="text" id="txt_treatmentName" placeholder="진료명 입력"/>';
	addRowHTML += '		<div class="button_box">';
	addRowHTML += '			<button class="cancel" onclick="javascript:fn_cancelTreatment();">취소</button>';
	addRowHTML += '			<button class="save" onclick="javascript:fn_insertTreatment();">저장</button>';
	addRowHTML += '		</div>';
	addRowHTML += '	</div>';
	addRowHTML += '</li>';
	$("#diagnosisList").append(addRowHTML);
}

// 진료 추가 취소
function fn_cancelTreatment(){
	$("#diagnosisList .liAddRow").remove();
}


/****************************************************************************
* 진료 추가
****************************************************************************/
function fn_insertTreatment(){
	let treatmentName  = $("#txt_treatmentName").val();
	
	if("Y"!=insertUseYn){
		modalEvent.warning("등록", "등록 권한이 없습니다.");
		return false;
	}
	
	if(!treatmentName){
		modalEvent.warning("등록", "진료명 정보가 없습니다.");
		return false;
	}

	modalEvent.info("등록", "진료 정보를 등록하시겠습니까?", function(){
		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("treatmentName", treatmentName);

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


/****************************************************************************
* 진료 삭제
****************************************************************************/
function fn_deleteTreatment(param){
	let muTreatmentId      = param;
	
	if("Y"!= deleteUseYn){
		modalEvent.warning("삭제", "삭제 권한이 없습니다.");
		return false;
	}
	
	if(!muTreatmentId){
		modalEvent.warning("삭제", "진료 정보가 없습니다.");
		return false;
	}

	modalEvent.info("삭제", "권한 정보를 삭제하시겠습니까?", function(){
		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("muTreatmentId", muTreatmentId);
		
		$.ajax({
			url: encodeURI('/webtreatment/deleteTreatment.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_selectListTreatment();
					});
				}
				else{
					modalEvent.danger("삭제 오류", data.msgDesc);
				}
			},
			error : function(xhr, status, error) {
				modalEvent.danger("삭제 오류", "삭제 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend:function(){
				
			},
			complete:function(){
				
			}
		});
	});
}


/****************************************************************************
* 진료 시술 정보 리스트 조회
****************************************************************************/
function fn_selectListTreatmentProcedure(param){
	let muTreatmentId = param;
	
	if(!muTreatmentId){
		modalEvent.warning("", "진료 정보가 없습니다.");
		return false;
	}
	
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("muTreatmentId", muTreatmentId);
	formData.append("treatmentProcedureSearchKeywordParam", treatmentProcedureSearchKeywordParam);
	formData.append("treatmentProcedureSort", treatmentProcedureSort);
	formData.append("treatmentProcedureDir", treatmentProcedureDir);
	formData.append("treatmentProcedureStart", treatmentProcedureStart);
	formData.append("treatmentProcedureLimit", treatmentProcedureLimit);

	$.ajax({
		url: encodeURI('/webtreatmentprocedure/selectListTreatmentProcedure.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function(data){
			if('0'==data.msgCode){
				
				$(".diagnosis_table_box .filter_box P.active").text('진료 ('+data.treatmentName+')');
				$("#muTreatmentId").val(muTreatmentId);
				
				// 페이징 처리
				treatmentProcedureTotalCount  = data.totalCount;
				//$("#txt_treatmentProcedureTotalCount").text(treatmentProcedureTotalCount);

				treatmentProcedureTotalPages = Math.ceil(treatmentProcedureTotalCount/treatmentProcedureLimit);
				
				// 리스트 조회
				let listHTML = '';

				treatmentProcedureAgGridData = data.rows;
				treatmentProcedureGridOptions.api.setRowData(treatmentProcedureAgGridData);

				if(0<data.rows.length){
					//페이징 처리
					window.pagObj = $('#treatmentProcedurePagination').twbsPagination({
						startPage    : ((treatmentProcedureStart/treatmentProcedureLimit)+1),
						totalPages   : (treatmentProcedureTotalPages==0)?1:treatmentProcedureTotalPages,
						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_treatmentProcedurePagination(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(){
			// 로딩열기
			treatmentProcedureGridOptions.api.showLoadingOverlay();
		},
		complete:function(){
			
		}
	});
}

/****************************************************************************
* 페이징 처리
****************************************************************************/
function fn_treatmentProcedurePagination(param){
	treatmentProcedureStart = (parseInt(param)-1)*treatmentProcedureLimit;
	
	let muTreatmentId = $("#muTreatmentId").val();
	fn_selectListTreatmentProcedure(muTreatmentId);
}

/****************************************************************************
* 페이징 리셋
****************************************************************************/
function fn_treatmentProcedurePaginReset(){
	treatmentProcedureSearchKeywordParam = '';

	treatmentProcedureStart        = 0;
	treatmentProcedureLimit        = 100;
	treatmentProcedureTotalCount   = 0;
	treatmentProcedureTotalPages   = 0;
	
	//페이징 초기화
	if($("#treatmentProcedurePagination").data("twbs-pagination")){
		$("#treatmentProcedurePagination").twbsPagination("destroy");
	}
}

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

	fn_treatmentProcedurePaginReset();
	
	treatmentProcedureSearchKeywordParam = $("#treatmentProcedureSearchKeyword").val();

	let muTreatmentId = $("#muTreatmentId").val();
	fn_selectListTreatmentProcedure(muTreatmentId);
}

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


/****************************************************************************
* 시술 활성여부 처리 (단건)
****************************************************************************/
function fn_updateTreatmentProcedureEnableYn(param, param2, param3){
	let muTreatmentId           = param;
	let muTreatmentProcedureId  = param2;
	let enableYn                = param3;

	if("Y"!= updateUseYn){
		modalEvent.warning("수정", "수정 권한이 없습니다.");
		return false;
	}

	if(!muTreatmentId){
		modalEvent.warning("수정", "진료 정보가 없습니다.");
		return false;
	}

	if(!muTreatmentProcedureId){
		modalEvent.warning("수정", "진료 시술 정보가 없습니다.");
		return false;
	}

	if(!enableYn){
		modalEvent.warning("수정", "활성여부 정보가 없습니다.");
		return false;
	}

	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("muTreatmentId", muTreatmentId);
	formData.append("selectId", muTreatmentProcedureId);
	formData.append("enableYn", enableYn);

	$.ajax({
		url: encodeURI('/webtreatmentprocedure/updateTreatmentProcedureEnableYn.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		success: function(data){
			if('0'==data.msgCode){
				modalEvent.success("수정 성공", data.msgDesc, function(){
					fn_selectListTreatmentProcedure(muTreatmentId);
				});
			}
			else{
				modalEvent.danger("수정 오류", data.msgDesc);
			}
		},
		error : function(xhr, status, error) {
			modalEvent.danger("수정 오류", "수정 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend:function(){

		},
		complete:function(){

		}
	});
}


/****************************************************************************
* 시술 비활성 처리 (다건)
****************************************************************************/
function fn_updateTreatmentProcedureEnableYn2(){
	let muTreatmentId           = $("#muTreatmentId").val();

	if("Y"!= updateUseYn){
		modalEvent.warning("수정", "수정 권한이 없습니다.");
		return false;
	}

	if(!muTreatmentId){
		modalEvent.warning("수정", "진료 정보가 없습니다.");
		return false;
	}

	if(!treatmentProcedureSelectId){
		modalEvent.warning("", "비활성화 대상을 선택하세요.");
		return false;
	}

	modalEvent.info("수정", "선택한 시술 정보를 비활성화하시겠습니까?", function(){
		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("muTreatmentId", muTreatmentId);
		formData.append("selectId", treatmentProcedureSelectId);
		formData.append("enableYn", "N");

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

			},
			complete:function(){

			}
		});
	});
}

function fn_insertTreatmentProcedurePopup(){
	if("Y"!=insertUseYn){
		modalEvent.warning("", "등록 권한이 없습니다.");
		return false;
	}
	
	let muTreatmentId = $("#muTreatmentId").val();
	
	if(!muTreatmentId){
		modalEvent.warning("", "진료 정보가 없습니다.");
		return false;
	}
	
	let reqParam =  {'muTreatmentId' : muTreatmentId};
	treatmentProcedureInsertModal.popup(function(obj, reqParam) {
		fn_selectListTreatmentProcedure(muTreatmentId);
	}, reqParam);
}

function fn_updateTreatmentProcedureTreatmentIdPopup(){
	if("Y"!=updateUseYn){
		modalEvent.warning("", "수정 권한이 없습니다.");
		return false;
	}

	if(!treatmentProcedureSelectId){
		modalEvent.warning("", "진료이동할 대상을 선택하세요.");
		return false;
	}

	let muTreatmentId = $("#muTreatmentId").val();

	if(!muTreatmentId){
		modalEvent.warning("", "진료 정보가 없습니다.");
		return false;
	}

	let reqParam =  {'muTreatmentId' : muTreatmentId,'selectId' : treatmentProcedureSelectId};
	treatmentProcedureTreatmentIdUpdateModal.popup(function(obj, reqParam) {
		fn_selectListTreatmentProcedure(muTreatmentId);
	}, reqParam);
}

function fn_updateTreatmentProcedurePopup(param){
	if(!param){
		modalEvent.warning("", "진료 시술 정보가 없습니다.");
		return false;
	}

	let muTreatmentId = $("#muTreatmentId").val();

	if(!muTreatmentId){
		modalEvent.warning("", "진료 정보가 없습니다.");
		return false;
	}

	let reqParam =  {'muTreatmentId' : muTreatmentId,'muTreatmentProcedureId' : param};

	if("Y"==updateUseYn){
		// 수정가능
		treatmentProcedureUpdateModal.popup(function(obj, reqParam) {
			fn_selectListTreatmentProcedure(muTreatmentId);
		}, reqParam);
	}
	else{
		treatmentProcedureSelectModal.popup(function(obj, reqParam) {
			fn_selectListTreatmentProcedure(muTreatmentId);
		}, reqParam);
	}
}

/****************************************************************************
* 페이지 init
****************************************************************************/
function fn_pageInit(){
	fn_selectListTreatment();
}

/****************************************************************************
* 페이지 event
****************************************************************************/
function fn_pageEvent(){
	// 진료항목 추가 버튼
	$("#btnAddTreatmentRow").click(function () {
		fn_addTreatmentRow();
	});
	
	// 검색 input
	$(document).on('keypress', '#treatmentProcedureSearchKeyword', function(e) {
		fn_treatmentProcedureEnter(e);
	});
	
	// 검색 조회 버튼
	$("#btnSearchTreatmentProcedure").click(function () {
		fn_treatmentProcedureSearch();
	});
	
	// 진료이동 버튼
	$("#btnUpdateTreatmentProcedureTreatmentId").click(function () {
		fn_updateTreatmentProcedureTreatmentIdPopup();
	});
	
	// 시술추가 버튼
	$("#btnInsertTreatmentProcedure").click(function () {
		fn_insertTreatmentProcedurePopup();
	});
	
	// 비활성화 버튼
	$("#btnUpdateTreatmentProcedureEnableYn2").click(function () {
		fn_updateTreatmentProcedureEnableYn2();
	});
	
}

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

let treatmentProcedureColumnDefs = [
	{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: "procedureName", headerName:"시술명", minWidth:150, cellStyle:{cursor: 'pointer', color:'#3985EA'}},
	/*{field: "productName", headerName:"약품",minWidth:150},
	{field: "productVolume", headerName:"용량",minWidth:106},
	{field: "doctorName", headerName:"닥터",minWidth:106},*/
	{field: "insuranceType", headerName:"수납형태",minWidth:106},
	{field: "procedurePriceTotal", headerName:"총액",minWidth:106},
	{field: "procedurePrice", headerName:"공급가",minWidth:106},
	{field: "procedurePriceVat", headerName:"Vat",minWidth:106},
	{field: "enableYn", headerName:"활성여부",minWidth:106,
		cellRenderer: function(params) {
			const muTreatmentId = params.node.data.muTreatmentId;
			const muTreatmentProcedureId = params.node.data.muTreatmentProcedureId;

			const parentDiv = document.createElement('div');
			parentDiv.setAttribute("class", "wrapper");

			let input1 = document.createElement("input");
			input1.id = "enableYn"+muTreatmentProcedureId;
			input1.type = "checkbox";
			input1.checked = params.value=='Y'?true:false;
			input1.addEventListener("click", function(event) {
				const enableYn = this.checked==true?'Y':'N';

				fn_updateTreatmentProcedureEnableYn(muTreatmentId, muTreatmentProcedureId, enableYn);
			});
			input1.setAttribute("class", "switch_input");

			let label1 = document.createElement("label");
			label1.setAttribute("for", "enableYn"+muTreatmentProcedureId);
			label1.setAttribute("class", "switch_label");

			let span1 = document.createElement("span");
			span1.setAttribute("class", "switch_btn");
			label1.appendChild(span1);

			parentDiv.appendChild(input1);
			parentDiv.appendChild(label1);

			return parentDiv;
		}
	}
];

// let the grid know which columns and what data to use
let treatmentProcedureGridOptions = {
	suppressRowTransform: true,
	columnDefs: treatmentProcedureColumnDefs,
	defaultColDef: {		// 리스트 기본 설정
		flex: 1,
		sortable: true,		//정렬 여부
		resizable: 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 : treatmentProcedureAgGridData,
	suppressRowClickSelection : true, // 로우 클릭시 체크박스 선택 true no, false yes
	localeText : {
		noRowsToShow : '조회 결과가 없습니다.'
	}, //데이터 없을 시 나오는 문구
	rowSelection : 'multiple', // row 다중 선택
	debug : false,
	onCellClicked: function(event){ //셀 클릭 이벤트
		/* alert(event.column.colId); */
		if('procedureName'==event.column.colId){
			fn_updateTreatmentProcedurePopup(event.data.muTreatmentProcedureId);
		}
	},
	onSelectionChanged: function(event){ //체크박스 선택
		let selectRows = [];
		selectRows = event.api.getSelectedRows();

		treatmentProcedureSelectId = '';
		for(let i=0; i<selectRows.length; i++){
			treatmentProcedureSelectId += selectRows[i].muTreatmentProcedureId + ",";
		}
		treatmentProcedureSelectId = treatmentProcedureSelectId.substring(0, treatmentProcedureSelectId.lastIndexOf(','));
	},
	onSortChanged: function(event){
		 //정렬
		treatmentProcedureSort = ''; //기존 정렬 초기화
		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){
					treatmentProcedureStart = 0;
					treatmentProcedureSort += gridSortModel+' '+ gridSort + ',';
				}
				else{
					nullCnt++;
					
					if(nullCnt == columnArr.length){
						treatmentProcedureSort = '';
						treatmentProcedureDir = '';
						treatmentProcedureStart = 0;
					}
				}
			}
		}
		treatmentProcedureSort = treatmentProcedureSort.substring(0,treatmentProcedureSort.lastIndexOf( ",")); //맨끝 콤마 지우기

		let muTreatmentId = $("#muTreatmentId").val();
		fn_selectListTreatmentProcedure(muTreatmentId);
	}
};

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

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