
/* ##############################################################
	설  명 : [Modal]진료 시술 수정 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/
let treatmentProcedureUpdateModal = {
	callback : null,
	reqParam : null,
	dataList : null,
	/* 모달 초기화 작업 */
	init : function () {
		$('#treatmentProcedureUpdateModal').remove();
		$('body').append( this.HtmlTemplate);
		//그리드 이벤트
		this.setEvent();
	},
	/* 그리드 이벤트 설정 */
	setEvent:function() {
		$('#treatmentProcedureUpdateModal .btnCancle').on("click", function(){
			treatmentProcedureUpdateModal.close();
		});
		
		$('#treatmentProcedureUpdateModal .btnSave').on("click", function(){
			treatmentProcedureUpdateModal.save("I");
		});
		
        $('#treatmentProcedureUpdateModal [name=modalProductUseVolume]').on('input', function() {
            // 입력된 키가 숫자가 아닌 경우 입력을 막음
            this.value = this.value.replace(/\D/g, '');
        });

        $('#treatmentProcedureUpdateModal #totalPrice').on('input', function() {
            // 입력된 키가 숫자가 아닌 경우 입력을 막음
            this.value = this.value.replace(/\D/g, '');
        });
		// $('#treatmentProcedureUpdateModal #modalProductName').on("click", function(){
		// 	let muTreatmentId  = treatmentProcedureUpdateModal.reqParam.muTreatmentId;
		//
		// 	let reqParam = {
		// 		'muTreatmentId' : muTreatmentId
		// 	};
		// 	productSearchModal.popup(function (obj, reqParam) {
		// 		$("#treatmentProcedureUpdateModal #modalProductId").val(obj.muProductId);
		// 		$("#treatmentProcedureUpdateModal #modalProductName").val(obj.productName);
		// 		$("#treatmentProcedureUpdateModal #modalProductCompanyName").text(obj.companyName);
		// 		$("#treatmentProcedureUpdateModal #modalProductVolume").text(obj.volume+'('+obj.unitName+')');
		// 		$("#treatmentProcedureUpdateModal #modalProductPrice").text(obj.price);
		// 	}, reqParam);
		// });
	},
	/* 데이터 선택 */
	setSelect:function(selectNumber) {
		let checkedData = dataList[selectNumber];
		if(dataList==null||checkedData==undefined){
			return ;
		}
		
		if( treatmentProcedureUpdateModal.callback )  {
			treatmentProcedureUpdateModal.callback(checkedData);
		}
		treatmentProcedureUpdateModal.close();
	},
	// 상세 조회
	search:function(state) {
		let muTreatmentProcedureId  = treatmentProcedureUpdateModal.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){
					$("#treatmentProcedureUpdateModal #modalProcedureName").val(data.rows[0].procedureName);
					// $('#treatmentProcedureUpdateModal #li_'+data.rows[0].muTreatmentId).click();

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


					// // 약품
					// $("#treatmentProcedureUpdateModal #modalProductId").val(data.rows[0].muProductId);
					// $("#treatmentProcedureUpdateModal #modalProductName").val(data.rows[0].productName);
					// $("#treatmentProcedureUpdateModal #modalProductCompanyName").text(data.rows[0].companyName);
					// $("#treatmentProcedureUpdateModal #modalProductVolume").text(data.rows[0].volume+'('+data.rows[0].unitName+')');
					// $("#treatmentProcedureUpdateModal #modalProductPrice").text(data.rows[0].price);
					//
					// 시술 약품 상세 정보
					fn_updateModal_treatmentProcedureAreaAddRow(data.rows[0].productRows);
					// 닥터 상세 정보
					fn_updateModal_treatmentProcedureDoctorAddRow(data.rows[0].doctorRows);
				}
				else{
					modalEvent.danger("조회 오류", data.msgDesc);
				}
			},
			error : function(xhr, status, error) {
				modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend:function(){
				
			},
			complete:function(){
				
			}
		});
	},
	//저장
	save:function(state) {
		let muTreatmentProcedureId  = treatmentProcedureUpdateModal.reqParam.muTreatmentProcedureId;
		let muTreatmentId           = treatmentProcedureUpdateModal.reqParam.muTreatmentId;
		let procedureName           = $("#treatmentProcedureUpdateModal #modalProcedureName").val();

		let detailProductArray   = new Object(); // 시술 약품 정보
		let detailDoctorArray = new Object(); // 닥터 정보
		
		if(true != fn_emptyCheck(muTreatmentProcedureId)){
			modalEvent.warning("수정", "진료 시술 정보가 없습니다.");	
			return;
		}
		
		if(true != fn_emptyCheck(muTreatmentId)){
			modalEvent.warning("수정", "진료 정보가 없습니다.");	
			return;
		}
		
		if(true != fn_emptyCheck(procedureName)){
			modalEvent.warning("수정", "시술명 정보가 없습니다.");	
			return;
		}
		else{
			if(true != fn_lengthCheck(procedureName, 50)) {
				modalEvent.warning("수정", "시술명 정보는 50자를 넘을 수 없습니다.");	
				return;
			}
		}
		
		// 시술 약품 정보
		let productTr = $('#treatmentProcedureUpdateModal .treatment_product_teble tbody').children('tr');
		let productTempArray = new Array();
		for(let i=0 ; i < productTr.length; i++){
			let orderNumber       = productTr.eq(i).find('td[name="modalTreatmentProductOrderNumber"]').text();
			let productName 	  = productTr.eq(i).find('input[name="modalProductName"]').val();
			let muProductId 	  = productTr.eq(i).find('input[name="modalProductId"]').val();
			let productUseVolume  = productTr.eq(i).find('input[name="modalProductUseVolume"]').val();
			let unitCode  	  = productTr.eq(i).find('span[name="modalProductUnit"]').attr('data');
			let unitName         = productTr.eq(i).find('span[name="modalProductUnit"]').text();
			if(true != fn_emptyCheck(orderNumber)){
				modalEvent.warning("수정", "약품 정렬순번 정보가 없습니다.");
				return;
			}

			if(true == fn_emptyCheck(productName)){
				let arr_sub = new Object();
				arr_sub.orderNumber       = orderNumber;
				arr_sub.productName 	  = productName;
				arr_sub.muProductId 	  = muProductId;
				arr_sub.productUseVolume  = productUseVolume;
				arr_sub.unitName 	      = unitName;
				arr_sub.unitCode 	      = unitCode;
				productTempArray.push(arr_sub);

				detailProductArray.data = productTempArray;
			}
		}
		
		// 시술 단가 정보
		let insuranceType          			= $('#treatmentProcedureUpdateModal #insuranceType').val();
		let price        = $('#treatmentProcedureUpdateModal #price').text();
		let discountprice        = $('#treatmentProcedureUpdateModal #discountPrice').val();
		let vat          = $('#treatmentProcedureUpdateModal #vat').text();

		if(true != fn_emptyCheck(insuranceType)){
			modalEvent.warning("수정", "시술단가의 선택 정보가 없습니다.");
			return;
		}

        if(true != fn_emptyCheck(price)){
            modalEvent.warning("수정", "시술단가의 단가 정보가 없습니다.");
            return;
        }

        if(true != fn_emptyCheck(vat)){
            modalEvent.warning("수정", "시술단가의 Vat 정보가 없습니다.");
            return;
        }
		if(true != fn_emptyCheck(discountprice)){
			modalEvent.warning("등록", "시술단가의 할인 금액 정보가 없습니다.");
			return;
		}

		// 닥터 정보
		let doctorTr = $('#treatmentProcedureUpdateModal .doctor_teble tbody').children('tr');
		let doctorTempArray = new Array();
		for(let i=0 ; i < doctorTr.length; i++){
			let orderNumber = doctorTr.eq(i).find('td[name="modalTreatmentProcedurePriceOrderNumber"]').text();
			let muMemberId  = doctorTr.eq(i).find('input[name="modalDoctorId"]').val();
			
			if(true != fn_emptyCheck(orderNumber)){
				modalEvent.warning("수정", "닥터의 정렬순번 정보가 없습니다.");	
				return;
			}

			if(true == fn_emptyCheck(muMemberId)){
				let arr_sub = new Object();
				arr_sub.orderNumber       = orderNumber;
				arr_sub.muMemberId        = muMemberId;
				doctorTempArray.push(arr_sub);

				detailDoctorArray.data = doctorTempArray;
			}
		}
		
		modalEvent.info("수정", "진료 시술 정보를 수정하시겠습니까?", function(){
			let formData = new FormData();
			formData.append("menuClass", menuClass);
			formData.append("muTreatmentProcedureId", muTreatmentProcedureId);
			formData.append("muTreatmentId", muTreatmentId);
			formData.append("procedureName", procedureName);
			formData.append("insuranceType", insuranceType);
			formData.append("price", price);
			formData.append("discountprice", discountprice);
			formData.append("vat", vat);
			formData.append("productRows",JSON.stringify(detailProductArray));
			formData.append("doctorRows",JSON.stringify(detailDoctorArray));
			$.ajax({
				url: encodeURI('/webtreatmentprocedure/updateTreatmentProcedure.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(){
							if( treatmentProcedureUpdateModal.callback )  {
								treatmentProcedureUpdateModal.callback();
							}
							treatmentProcedureUpdateModal.close();
						});
					}
					else{
						modalEvent.danger("수정 오류", data.msgDesc);
					}
				},
				error : function(xhr, status, error) {
					modalEvent.danger("수정 오류", "수정 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
				},
				beforeSend:function(){
					
				},
				complete:function(){
					
				}
			});
		});
	},
	/*
	 * 팝업
	 * callback : 콜백함수, reqParam: 팝업파라미터
	 */
	popup:function(callback, reqParam) {
		// 초기화 후 열기
		treatmentProcedureUpdateModal.init();
		
		//콜백함수 지정.
		treatmentProcedureUpdateModal.callback = callback;
		treatmentProcedureUpdateModal.reqParam = reqParam;
		treatmentProcedureUpdateModal.dataList = null;
		
		treatmentProcedureUpdateModal.search();
		
		setTimeout(function(){
			$('#treatmentProcedureUpdateModal').modal('show')
		}, 200);
	},
	/*
	 * 팝업 닫기
	 */
	close:function() {
		$('#treatmentProcedureUpdateModal').modal('hide');

		setTimeout(function(){
			$('#treatmentProcedureUpdateModal').remove();
		},500);
	},
	HtmlTemplate : `
	<div id="treatmentProcedureUpdateModal" 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">
							</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">스컬트라 2cc, 라쥬란 10ml</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 class="teble_box">
									<table class="treatment_price_teble">
										<thead>
											<tr>
												<th>선택</th>
												<th>총 시술 금액</th>
												<th>할인 금액</th>
												<th>공급가</th>
												<th>vat</th>
											</tr>
										</thead>
										<tbody>
											<tr>
												<td>
													<div class="select_list">
														<div class="select_box dropdown">
															<button class="label" type="button" data-toggle="dropdown" 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_updateModal_clickSelectValue(this)">
																	<input type="hidden" value="Y">
																		<span>급여</span>
																	</input>
																</li>
																<li class="option_list_item" onclick="fn_updateModal_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" onchange="fn_updateModal_changeInsuranceType()"/>
													</div>
												</td>
												<td>
													<div class="input_box">
														<input type="text" id="discountPrice"/>
													</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="cancel_btn btnCancle">취소</button>
							<button type="button" class="registration_bth btnSave">저장</button>
						</div>
					</div>
				</div>
			</div>
		</div>
    `
};

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

/****************************************************************************
 * 약품 검색 팝업
 ****************************************************************************/
function fn_searchPop_treatmentProcedure(target){
	let reqParam = {};
	productSearchModal.popup(function (obj, reqParam) {
		let parentElement = $(target).parent().parent().parent();

		parentElement.find('span[name="modalProductCompanyName"]').text(obj.companyName);
		parentElement.find('span[name="modalProductVolume"]').text(`${obj.volume}(${obj.unitName})`);
		parentElement.find('span[name="modalProductPrice"]').text(obj.price);
		parentElement.find('span[name="modalProductUnit"]').text(obj.unitName);
		parentElement.find('span[name="modalProductUnit"]').attr('data',obj.unitCode);

		$(target).val(obj.productName)
		$(target).parent().find('input[name="modalProductId"]').val(obj.muProductId);
		fn_updateModal_productInfo();
	}, reqParam);
}
/****************************************************************************
 * 약품 검색 row 추가 이벤트
 ****************************************************************************/
function fn_updateModal_treatmentProcedureAreaAddRow(param){

	let detailList = param;

	let parentTable = $('#treatmentProcedureUpdateModal .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 unitName  	 = detailList[i].unitName;
			let unitCode  	 = detailList[i].unitCode;
			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="hidden" name="modalProductId" value="'+muProductId+'">';
            addRowHtml += '			<input type="text" name="modalProductName" onclick="fn_searchPop_treatmentProcedure(this)" 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" onchange="fn_updateModal_productInfo()" value="'+useVolume+'">';
            addRowHtml += '         <span name="modalProductUnit" data="'+unitCode+'">'+useUnit+'</span>';
            addRowHtml += '     </div>';
            addRowHtml += ' </td>';
            addRowHtml += ' <td>';
            addRowHtml += '     <div class="add_box" style="display:'+(orderNumber === 1?'block':'none')+'">';
            addRowHtml += '			<button onclick="javascript:fn_updateModal_treatmentProcedureAreaAddRow();"><img src="/image/web/add.svg" alt="추가"></button>';
            addRowHtml += '		</div>';
            addRowHtml += '		<div class="subtract_box" style="display:'+(orderNumber !== 1?'block':'none')+'">';
            addRowHtml += '			<button onclick="javascript:fn_updateModal_treatmentProcedureRemoveRow(this);"><img src="/image/web/subtract.svg" alt="삭제"></button>';
            addRowHtml += '		</div>';
            addRowHtml += '	</td>';
            addRowHtml += '</tr>';
        }
    }
    else{
		let liNum = parentTable.find('tr').length;

		addRowHtml += '<tr>';
        addRowHtml += '	<td name="modalTreatmentProductOrderNumber">'+(liNum+1)+'</td>';
        addRowHtml += '	<td>';
        addRowHtml += '		<div class="search_box">';
        addRowHtml += '		    <img src="/image/web/search_G.svg" alt="search"/>';
        addRowHtml += '		    <input type="hidden" name="modalProductId">';
        addRowHtml += '			<input type="text" name="modalProductName" onclick="fn_searchPop_treatmentProcedure(this)" placeholder="약품 검색" readonly>';
        addRowHtml += '		</div>';
        addRowHtml += '	</td>';
        addRowHtml += '	<td><span name="modalProductCompanyName">-</span></td>';
        addRowHtml += '	<td><span name="modalProductVolume">-</span></td>';
        addRowHtml += '	<td><span name="modalProductPrice">-</span></td>';
        addRowHtml += ' <td>';
        addRowHtml += '     <div class="input_box short">';
        addRowHtml += '         <input type="text" value="" name="modalProductUseVolume" onchange="fn_updateModal_productInfo()"/>';
        addRowHtml += '         <span name="modalProductUnit">cc</span>';
        addRowHtml += '     </div>';
        addRowHtml += ' </td>';
        addRowHtml += ' <td>';
        addRowHtml += '     <div class="add_box" style="display:'+(liNum === 0?'block':'none')+'">';
        addRowHtml += '			<button onclick="javascript:fn_updateModal_treatmentProcedureAreaAddRow();"><img src="/image/web/add.svg" alt="추가"></button>';
        addRowHtml += '		</div>';
        addRowHtml += '		<div class="subtract_box" style="display:'+(liNum !== 0?'block':'none')+'">';
        addRowHtml += '			<button onclick="javascript:fn_updateModal_treatmentProcedureRemoveRow(this);"><img src="/image/web/subtract.svg" alt="삭제"></button>';
        addRowHtml += '		</div>';
        addRowHtml += '	</td>';
        addRowHtml += '</tr>';
	}
	parentTable.append(addRowHtml).trigger("create");
	
	$('#treatmentProcedureUpdateModal [name=modalProductUseVolume]').on('input', function() {
		// 입력된 키가 숫자가 아닌 경우 입력을 막음
		this.value = this.value.replace(/\D/g, '');
	});


	fn_updateModal_treatmentProcedureRefreshOrderNumber(parentTable);
	fn_updateModal_productInfo();
}

/****************************************************************************
* 시술 닥터 콤보데이타 설정
****************************************************************************/
function fn_updateModal_setDoctorCombo(){
	let comboData = fn_selectListMemberDoctorOption();
	
	let comboHTML = '';
	for(let i = 0; i < comboData.length; i++){
		let muMemberId        = comboData[i].muMemberId;
		let memberName        = comboData[i].memberName;
		let groupName         = comboData[i].groupName;
		
		comboHTML += '<li onClick="fn_updateModal_clickSelectValue(this);" class="option_list_item ">';
		comboHTML += '	<input type="hidden" name="MODAL_COMBO_DOCTOR_ID" value="'+muMemberId+'">';
		comboHTML += '	<span>'+groupName + ' ' +memberName+'</span>';
		comboHTML += '</li>';
	}
	
	return comboHTML;
}

// /****************************************************************************
// * 시술 닥터 select box 선택 값 셋팅
// ****************************************************************************/
// function fn_updateModal_clickSelectDoctorValue(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);
// }
/****************************************************************************
 *  select box 선택 값 셋팅
 ****************************************************************************/
function fn_updateModal_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')){
		$("#treatmentProcedureUpdateModal #insuranceType").val(selectId);
		fn_updateModal_changeInsuranceType();
	}
}

/****************************************************************************
* 시술 닥터 row 추가 이벤트
****************************************************************************/
function fn_updateModal_treatmentProcedureDoctorAddRow(param){
	let detailList = param;

	let parentTable = $('#treatmentProcedureUpdateModal .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="modalTreatmentProcedurePriceOrderNumber">'+orderNumber+'</td>';
			addRowHtml += '	<td>';
			addRowHtml += '		<div class="select_box dropdown">';
			addRowHtml += '			<button class="label" class="label dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">'+groupName+' '+memberName+'</button>';
			addRowHtml += '			<input type="hidden" name="modalDoctorId" value="'+muMemberId+'"></input>';
			addRowHtml += '			<ul class="select_option_list dropdown-menu">';
			addRowHtml += fn_updateModal_setDoctorCombo();
			addRowHtml += '			</ul>';
			addRowHtml += '		</div>';
			addRowHtml += '	</td>';
			addRowHtml += '	<td>';
			addRowHtml += '		<div class="add_box" style="display:'+(orderNumber === 1?'block':'none')+'">';
			addRowHtml += '			<button onclick="javascript:fn_updateModal_treatmentProcedureDoctorAddRow();"><img src="/image/web/add.svg" alt="추가"></button>';
			addRowHtml += '		</div>';
			addRowHtml += '		<div class="subtract_box"  style="display:none">';
			addRowHtml += '			<button onclick="javascript:fn_updateModal_treatmentProcedureRemoveRow(this);"><img src="/image/web/subtract.svg" alt="삭제"></button>';
			addRowHtml += '		</div>';
			addRowHtml += '	</td>';
			addRowHtml += '</tr>';
		}
	}
	else{
		let trNum       = parentTable.find('tr').length;

		addRowHtml += '<tr>';
		addRowHtml += '	<td name="modalTreatmentProcedurePriceOrderNumber">'+(trNum+1)+'</td>';
		addRowHtml += '	<td>';
		addRowHtml += '		<div class="select_box dropdown">';
		addRowHtml += '			<button class="label" class="label btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">닥터</button>';
		addRowHtml += '			<input type="hidden" name="modalDoctorId"></input>';
		addRowHtml += '			<ul class="select_option_list dropdown-menu">';
		addRowHtml += fn_updateModal_setDoctorCombo();
		addRowHtml += '			</ul>';
		addRowHtml += '		</div>';
		addRowHtml += '	</td>';
		addRowHtml += '	<td>';
		addRowHtml += '		<div class="add_box" style="display:'+(trNum === 0?'block':'none')+'">';
		addRowHtml += '			<button onclick="javascript:fn_updateModal_treatmentProcedureDoctorAddRow();"><img src="/image/web/add.svg" alt="추가"></button>';
		addRowHtml += '		</div>';
		
		addRowHtml += '		<div class="subtract_box" style="display:'+(trNum !== 0?'block':'none')+'">';
		addRowHtml += '			<button onclick="javascript:fn_updateModal_treatmentProcedureRemoveRow(this);"><img src="/image/web/subtract.svg" alt="삭제"></button>';
		addRowHtml += '		</div>';
		addRowHtml += '	</td>';
		addRowHtml += '</tr>';
	}
	
	parentTable.append(addRowHtml).trigger("create");
	
	fn_updateModal_treatmentProcedureRefreshOrderNumber(parentTable);
}

/****************************************************************************
* row 삭제 이벤트
****************************************************************************/
function fn_updateModal_treatmentProcedureRemoveRow(param){
	let parentTable = $(param).closest('table').find("tbody");
	let liLength = parentTable.children('tr').length;
	
	if(1 < liLength){
		let liNum = $(param).closest('tr').prevAll().length;
		parentTable.children('tr').eq(liNum).remove();
		
		fn_updateModal_treatmentProcedureRefreshOrderNumber(parentTable);
	}
	else{
		modalEvent.warning("입력 오류", "더 이상 삭제할 수 없습니다.");
	}
}



/****************************************************************************
* row 정렬순번 변경 이벤트
 - type : A 위로, B 아래로
****************************************************************************/
function fn_updateModal_treatmentProcedureMoveRow(param, type){
	if('A' == type){
		let $tr = $(param).closest('tr'); // 클릭한 버튼이 속한 tr 요소
		$tr.prev().before($tr);
	}
	else{
		let $tr = $(param).closest('tr'); // 클릭한 버튼이 속한 tr 요소
		$tr.next().after($tr);
	}
	
	let parentTable = $(param).closest('table').find("tbody");
	fn_updateModal_treatmentProcedureRefreshOrderNumber(parentTable);
}

/****************************************************************************
* 전체 row 정렬순번 변경
****************************************************************************/
function fn_updateModal_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_updateModal_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(', '));
}

function fn_updateModal_changeInsuranceType(){
	let insuranceType = $("#insuranceType").val();
	let totalPrice =$('#treatmentProcedureUpdateModal #totalPrice').val();
	if(""!==totalPrice){
		if('N'===insuranceType){
			$('#treatmentProcedureUpdateModal #price').text(Math.round(totalPrice/1.1));
			$('#treatmentProcedureUpdateModal #vat').text(totalPrice-Math.round(totalPrice/1.1));
		}else if('Y'===insuranceType){
			$('#treatmentProcedureUpdateModal #price').text(totalPrice);
			$('#treatmentProcedureUpdateModal #vat').text('0');
		}
	}
}
