
/* ##############################################################
	설  명 : [Modal]진료 시술 조회 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/
let treatmentProcedureSelectModal = {
	callback : null,
	reqParam : null,
	dataList : null,
	/* 모달 초기화 작업 */
	init : function () {
		$('#treatmentProcedureSelectModal').remove();
		$('body').append( this.HtmlTemplate);
		//그리드 이벤트
		this.setEvent();
	},
	/* 그리드 이벤트 설정 */
	setEvent:function() {
		$('#treatmentProcedureSelectModal .btnCancle').on("click", function(){
			treatmentProcedureSelectModal.close();
		});
		
		$('#treatmentProcedureSelectModal .btnSave').on("click", function(){
			treatmentProcedureSelectModal.save("I");
		});
	},
	/* 데이터 선택 */
	setSelect:function(selectNumber) {
		let checkedData = dataList[selectNumber];
		if(dataList==null||checkedData==undefined){
			return ;
		}
		
		if( treatmentProcedureSelectModal.callback )  {
			treatmentProcedureSelectModal.callback(checkedData);
		}
		treatmentProcedureSelectModal.close();
	},
	// 상세 조회
	search:function(state) {
		let muTreatmentProcedureId  = treatmentProcedureSelectModal.reqParam.muTreatmentProcedureId;
		
		if(true != fn_emptyCheck(muTreatmentProcedureId)){
			modalEvent.warning("조회", "진료 시술 정보가 없습니다.");	
			return;
		}
		
		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("muTreatmentProcedureId", muTreatmentProcedureId);

		$.ajax({
			url: encodeURI('/webtreatmentprocedure/selectTreatmentProcedure.do'),
			data: formData,
			dataType: "json",
			processData: false,
			contentType: false,
			type: 'POST',
			async: true,
			success: function(data){
				if('0'==data.msgCode){
					$("#treatmentProcedureSelectModal #modalProcedureName").val(data.rows[0].procedureName);

					let priceData = data.rows[0].priceRows[0];
					$("#treatmentProcedureSelectModal .select_option_list .option_list_item").each(function() {
						const spanText = $(this).find('span').text().trim();
						if (spanText === priceData.insuranceType) {
							$(this).click();
						}
					});
					$("#treatmentProcedureSelectModal #totalPrice").val(priceData.totalPrice);
					$("#treatmentProcedureSelectModal #price").text(priceData.price);
					$("#treatmentProcedureSelectModal #vat").text(priceData.vat);

					// 시술 약품 상세 정보
					fn_searchModal_treatmentProcedureAreaAddRow(data.rows[0].productRows);
					// 닥터 상세 정보
					fn_searchModal_treatmentProcedureDoctorAddRow(data.rows[0].doctorRows);
				}
				else{
					modalEvent.danger("조회 오류", data.msgDesc);
				}
			},
			error : function(xhr, status, error) {
				modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend:function(){
				
			},
			complete:function(){
				
			}
		});
	},
	/*
	 * 팝업
	 * callback : 콜백함수, reqParam: 팝업파라미터
	 */
	popup:function(callback, reqParam) {
		// 초기화 후 열기
		treatmentProcedureSelectModal.init();
		
		//콜백함수 지정.
		treatmentProcedureSelectModal.callback = callback;
		treatmentProcedureSelectModal.reqParam = reqParam;
		treatmentProcedureSelectModal.dataList = null;
		
		treatmentProcedureSelectModal.search();
		
		setTimeout(function(){
			$('#treatmentProcedureSelectModal').modal('show')
		}, 200);
	},
	/*
	 * 팝업 닫기
	 */
	close:function() {
		$('#treatmentProcedureSelectModal').modal('hide');

		setTimeout(function(){
			$('#treatmentProcedureSelectModal').remove();
		},500);
	},
	HtmlTemplate : `
	<div id="treatmentProcedureSelectModal" class="modal add_treatment_modal fade" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<p class="title">시술 조회</p>
				</div>
	
				<div class="modal-body">
						<div class="form_box">
							<div class="input_box first">
								<label>시술명</label>
								<input type="text" id="modalProcedureName" placeholder="시술명 입력" maxlength="50" readonly>
							</div>

							<div class="right_tabel_wrap">
								<div class="teble_box">
									<table class="treatment_product_teble">
										<thead>
											<tr>
												<th>번호</th>
												<th>약품명</th>
												<th>거래처</th>
												<th>용량/단위</th>
												<th>단가</th>
												<th>사용용량/단위</th>
												<th></th>
											</tr>
										</thead>
										<tbody>
											
										</tbody>
										<tfoot>
											<tr>
												<td colspan="7">
													시술약품 : <span id="productInfo">-</span>
												</td>
											</tr>
										</tfoot>
									</table>
								</div>

								<div class="teble_box">
									<table class="doctor_teble">
										<thead>
											<tr>
												<th>번호</th>
												<th>시술 닥터명</th>
												<th></th>
											</tr>
										</thead>
										<tbody>
										</tbody>
									</table>
								</div>
							</div>
							<div class="left_tabel_wrap">
								<div class="teble_box">
									<table class="treatment_price_teble">
										<thead>
											<tr>
												<th>선택</th>
												<th>총 시술 금액</th>
												<th>공급가</th>
												<th>vat</th>
											</tr>
										</thead>
										<tbody>
											<tr>
												<td>
													<div class="select_list">
														<div class="select_box dropdown" style="background:none">
															<button class="label" type="button" aria-haspopup="true" aria-expanded="true">선택</button>
															<input type="hidden" id="insuranceType">
															<ul class="select_option_list dropdown-menu">
																<li class="option_list_item" onclick="fn_searchModal_clickSelectValue(this)">
																	<input type="hidden" value="Y">
																		<span>급여</span>
																	</input>
																</li>
																<li class="option_list_item" onclick="fn_searchModal_clickSelectValue(this)">
																	<input type="hidden" value="N">
																		<span>비급여</span>
																	</input>
																</li>
															</ul>
														</div>
													</div>
												</td>
												<td>
													<div class="input_box">
														<input type="text" id="totalPrice" placeholder="0" readonly/>
													</div>
												</td>
												<td id="price">0</td>
												<td id="vat">0</td>
											</tr>
										</tbody>
									</table>
								</div>
							</div>
						</div>
					</div>

					<div class="modal-footer">
						<div class="btn_box">
							<button type="button" class="registration_bth btnCancle">확인</button>
						</div>
					</div>
				</div>
			</div>
		</div>
    `
};

/****************************************************************************
* 시술 부위 row 추가 이벤트
****************************************************************************/
function fn_searchModal_treatmentProcedureAreaAddRow(param){
	let detailList = param;
	
	let parentTable = $('#treatmentProcedureSelectModal .treatment_product_teble tbody');
	
	let addRowHtml = '';
	if(null!=detailList && detailList.length>0){
		for(let i = 0; i < detailList.length; i++){
			let orderNumber  = detailList[i].orderNumber;
			let productName  = detailList[i].productName;
			let muProductId  = detailList[i].muProductId;
			let companyName  = detailList[i].companyName;
			let volume  	 = detailList[i].volume;
			let unitCode  	 = detailList[i].unitCode;
			let unitName  	 = detailList[i].unitName;
			let useVolume  	 = detailList[i].useVolume;
			let useUnit  	 = detailList[i].useUnit;
			let price  	     = detailList[i].price;

			addRowHtml += '<tr>';
			addRowHtml += '	<td name="modalTreatmentProductOrderNumber">'+orderNumber+'</td>';
			addRowHtml += '	<td>';
			addRowHtml += '		<div class="search_box">';
			addRowHtml += '		    <img src="/image/web/search_G.svg" alt="search"/>';
			addRowHtml += '			<input type="text" name="modalProductName" value="'+productName+'" placeholder="약품 검색" readonly>';
			addRowHtml += '		</div>';
			addRowHtml += '	</td>';
			addRowHtml += '	<td><span name="modalProductCompanyName">'+companyName+'</span></td>';
			addRowHtml += '	<td><span name="modalProductVolume">'+volume+'('+unitName+')'+'</span></td>';
			addRowHtml += '	<td><span name="modalProductPrice">'+price+'</span></td>';
			addRowHtml += ' <td>';
			addRowHtml += '     <div class="input_box short">';
			addRowHtml += '         <input type="text" name="modalProductUseVolume" value="'+useVolume+'" readonly>';
			addRowHtml += '         <span name="modalProductUnit" data="'+unitCode+'">'+useUnit+'</span>';
			addRowHtml += '     </div>';
			addRowHtml += ' </td>';
			addRowHtml += '</tr>';
		}
	}
	parentTable.append(addRowHtml).trigger("create");
	
	fn_searchModal_treatmentProcedureRefreshOrderNumber(parentTable);
	fn_searchModal_productInfo();
}
/****************************************************************************
 *  select box 선택 값 셋팅
 ****************************************************************************/
function fn_searchModal_clickSelectValue(target){
	let selectId    = $(target).children("input").val();
	let selectName  = $(target).children("span").text();

	$(target).parent().siblings("button").text(selectName);
	$(target).parent().siblings("input").val(selectId);

	if('insuranceType'===$(target).parent().siblings("input").attr('id')){
		fn_updateModal_changeInsuranceType();
	}
}
/****************************************************************************
* 시술 닥터 row 추가 이벤트
****************************************************************************/
function fn_searchModal_treatmentProcedureDoctorAddRow(param){
	let detailList = param;
	
	let parentTable = $('#treatmentProcedureSelectModal .doctor_teble tbody');
	
	let addRowHtml = '';
	if(null!=detailList && detailList.length>0){
		for(let i = 0; i < detailList.length; i++){
			let orderNumber  = detailList[i].orderNumber;
			let muMemberId   = detailList[i].muMemberId;
			let memberName   = detailList[i].memberName;
			let groupName    = detailList[i].groupName;
			
			addRowHtml += '<tr>';
			addRowHtml += '	<td name="modalTreatmentProcedureDoctorOrderNumber">'+orderNumber+'</td>';
			addRowHtml += '	<td name="modalTreatmentProcedureDoctorName">'+groupName+' '+memberName+'</td>';
			addRowHtml += '</tr>';
		}
	}
	
	parentTable.append(addRowHtml).trigger("create");
	
	fn_searchModal_treatmentProcedureRefreshOrderNumber(parentTable);
}

/****************************************************************************
* 전체 row 정렬순번 변경
****************************************************************************/
function fn_searchModal_treatmentProcedureRefreshOrderNumber(param){
	$(param).find("tr").each(function(index){
		$(this).find('td').eq(0).text(index+1);
	});
	
	// // row 추가/삭제 버튼 처리
	// $(param).find(".add_box").hide();
	// $(param).find('.subtract_box').show();
	// $(param).find("tr:first").find("td:last").prev().find(".subtract_box").hide();
	// $(param).find("tr:first").find("td:last").prev().find(".add_box").show();
}
/****************************************************************************
 * 약품검색 하단 요약정보 표출 이벤트
 ****************************************************************************/
function fn_searchModal_productInfo(){
	let treatmentDetails = [];
	$('.treatment_product_teble tbody tr').each(function() {
		let productName = $(this).find('input[name="modalProductName"]').val();
		let productVolume = $(this).find('input[name="modalProductUseVolume"]').val();
		let productUnit = $(this).find('span[name="modalProductUnit"]').text();

		if (productName && productVolume && productUnit) {
			treatmentDetails.push(`${productName} ${productVolume}${productUnit}`);
		}
	});

	$('.treatment_product_teble tfoot span').text(treatmentDetails.join(', '));
}