
/* ##############################################################
	설  명 : [Modal]진료 시술 등록 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/
let treatmentProcedureInsertModal = {
	callback : null,
	reqParam : null,
	dataList : null,
	/* 모달 초기화 작업 */
	init : function () {
		$('#treatmentProcedureInsertModal').remove();
		$('body').append( this.HtmlTemplate);
		//그리드 이벤트
		this.setEvent();
	},
	/* 그리드 이벤트 설정 */
	setEvent:function() {
		$('#treatmentProcedureInsertModal .btnCancle').on("click", function(){
			treatmentProcedureInsertModal.close();
		});

		$('#treatmentProcedureInsertModal .btnSave').on("click", function(){
			treatmentProcedureInsertModal.save("I");
		});

        $('#treatmentProcedureInsertModal [name=modalProductUseVolume]').on('input', function() {
            // 입력된 키가 숫자가 아닌 경우 입력을 막음
            this.value = this.value.replace(/\D/g, '');
        });

        $('#treatmentProcedureInsertModal #totalPrice').on('input', function() {
            // 입력된 키가 숫자가 아닌 경우 입력을 막음
            this.value = this.value.replace(/\D/g, '');
        });
	},
	/* 데이터 선택 */
	setSelect:function(selectNumber) {
		let checkedData = dataList[selectNumber];
		if(dataList==null||checkedData==undefined){
			return ;
		}

		if( treatmentProcedureInsertModal.callback )  {
			treatmentProcedureInsertModal.callback(checkedData);
		}
		treatmentProcedureInsertModal.close();
	},
	//저장
	save:function(state) {
		let muTreatmentId  = treatmentProcedureInsertModal.reqParam.muTreatmentId;
		let procedureName  = $("#treatmentProcedureInsertModal #modalProcedureName").val();

		let detailProductArray   = {'data':[]};// 약품 정보
		let detailDoctorArray = {'data':[]}; // 닥터 정보

		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;
			}
		}
/*공급가 = 총금액/1.1
vat= 총금액 -공급가
*소수점 반올림(공통)
비급여항목은 부가세 X*/

		// 시술 약품 정보
		let productTr = $('#treatmentProcedureInsertModal .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          = $('#treatmentProcedureInsertModal #insuranceType').val();
		let price        = $('#treatmentProcedureInsertModal #price').text();
		let discountprice        = $('#treatmentProcedureInsertModal #discountPrice').val();
		let vat          = $('#treatmentProcedureInsertModal #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 = $('#treatmentProcedureInsertModal .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("muTreatmentId", muTreatmentId);
			formData.append("procedureName", procedureName);
			formData.append("insuranceType", insuranceType);
			formData.append("price", price);
			formData.append("discountprice", discountprice);
			formData.append("vat", vat);
			if(0<detailProductArray.data.length)
				formData.append("productRows",JSON.stringify(detailProductArray));
			if(0<detailDoctorArray.data.length)
				formData.append("doctorRows",JSON.stringify(detailDoctorArray));
			$.ajax({
				url: encodeURI('/webtreatmentprocedure/insertTreatmentProcedure.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( treatmentProcedureInsertModal.callback )  {
								treatmentProcedureInsertModal.callback();
							}
							treatmentProcedureInsertModal.close();
						});
					}
					else{
						modalEvent.danger("등록 오류", data.msgDesc);
					}
				},
				error : function(xhr, status, error) {
					modalEvent.danger("등록 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
				},
				beforeSend:function(){

				},
				complete:function(){

				}
			});
		});
	},
	/*
	 * 팝업
	 * callback : 콜백함수, reqParam: 팝업파라미터
	 */
	popup:function(callback, reqParam) {
		// 초기화 후 열기
		treatmentProcedureInsertModal.init();

		//콜백함수 지정.
		treatmentProcedureInsertModal.callback = callback;
		treatmentProcedureInsertModal.reqParam = reqParam;
		treatmentProcedureInsertModal.dataList = null;

		// 시술 부위
		fn_insertModal_treatmentProcedureAreaAddRow();
		// 닥터
		fn_insertModal_treatmentProcedureDoctorAddRow();

		setTimeout(function(){
			$('#treatmentProcedureInsertModal').modal('show')
		}, 200);
	},
	/*
	 * 팝업 닫기
	 */
	close:function() {
		$('#treatmentProcedureInsertModal').modal('hide');

		setTimeout(function(){
			$('#treatmentProcedureInsertModal').remove();
		},500);
	},
	HtmlTemplate : `
	<div class="modal add_treatment_modal fade" id="treatmentProcedureInsertModal" 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"></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_insertModal_clickSelectValue(this)">
																	<input type="hidden" value="Y">
																		<span>급여</span>
																	</input>
																</li>
																<li class="option_list_item" onclick="fn_insertModal_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_insertModal_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_insertModalSearchEnter(e, type){
	if(e.which){
		// 파이어폭스
		if(13 == e.which) {
			//로그인 액션 스크립트
			if('M' == type){
				// 약품
				fn_insertModal_setTreatmentCombo();
			}
		}
	}
	else{
		// 윈도우, 사파리, 크롬
		if(13 == event.keyCode) {
			//로그인 액션 스크립트
			if('M' == type){
				// 약품
				fn_insertModal_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_insertModal_productInfo();
		}, reqParam);
}
/****************************************************************************
 * 약품 검색 row 추가 이벤트
 ****************************************************************************/
function fn_insertModal_treatmentProcedureAreaAddRow(type){
	let addBtnType = type === 'a'?'none':'block'
	let subtractBtnType=type !== 'a'?'none':'block'
	let parentTable = $('#treatmentProcedureInsertModal .treatment_product_teble tbody');

	let liNum = parentTable.find('tr').length;

	let addRowHtml = '';
	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_insertModal_productInfo()"/>';
	addRowHtml += '         <span name="modalProductUnit">cc</span>';
    addRowHtml += '     </div>';
    addRowHtml += ' </td>';
    addRowHtml += ' <td>';
    addRowHtml += '     <div class="add_box" style="display:'+addBtnType+'">';
	addRowHtml += '			<button onclick="javascript:fn_insertModal_treatmentProcedureAreaAddRow(\'a\');"><img src="/image/web/add.svg" alt="추가"></button>';
	addRowHtml += '		</div>';
	addRowHtml += '		<div class="subtract_box" style="display:'+subtractBtnType+'">';
	addRowHtml += '			<button onclick="javascript:fn_insertModal_treatmentProcedureRemoveRow(this);"><img src="/image/web/subtract.svg" alt="삭제"></button>';
	addRowHtml += '		</div>';
	addRowHtml += '	</td>';
	addRowHtml += '</tr>';
	parentTable.append(addRowHtml).trigger("create");

	$('#treatmentProcedureInsertModal [name=modalProductUseVolume]').on('input', function() {
		// 입력된 키가 숫자가 아닌 경우 입력을 막음
		this.value = this.value.replace(/[^0-9.]/g, '');
	});


	fn_insertModal_treatmentProcedureRefreshOrderNumber(parentTable);
}

/****************************************************************************
 * 시술 닥터 콤보데이타 설정 (동적 추가)
 ****************************************************************************/
function fn_insertModal_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_insertModal_clickSelectValue(this);" class="option_list_item ">';
		comboHTML += '	<input type="hidden" name="modalComboDoctorId" value="'+muMemberId+'">';
		comboHTML += '	<span>'+groupName + ' ' +memberName+'</span>';
		comboHTML += '</li>';
	}

	return comboHTML;
}

/****************************************************************************
 *  select box 선택 값 셋팅
 ****************************************************************************/
function fn_insertModal_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')){
		$("#treatmentProcedureInsertModal #insuranceType").val(selectId);
		fn_insertModal_changeInsuranceType();
	}
}

/****************************************************************************
 * 시술 닥터 row 추가 이벤트
 ****************************************************************************/
function fn_insertModal_treatmentProcedureDoctorAddRow(type){
	let addBtnType = type === 'a'?'none':'block'
	let subtractBtnType=type !== 'a'?'none':'block'
	let parentTable = $('#treatmentProcedureInsertModal .doctor_teble tbody');
	let trNum       = parentTable.find('tr').length;

	let addRowHtml = '';
	addRowHtml += '<tr>';
	addRowHtml += '	<td name="modalTreatmentProcedurePriceOrderNumber">'+(trNum+1)+'</td>';
	addRowHtml += '	<td>';
	addRowHtml += '	    <div class="select_list">';
	addRowHtml += '		    <div class="select_box dropdown">';
	addRowHtml += '			    <button type="button" class="label dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">닥터</button>';
	addRowHtml += '			    <input type="hidden" name="modalDoctorId"></input>';
	addRowHtml += '			    <ul class="select_option_list dropdown-menu">';
	addRowHtml +=   fn_insertModal_setDoctorCombo();
	addRowHtml += '			    </ul>';
	addRowHtml += '		    </div>';
	addRowHtml += '		</div>';
	addRowHtml += '	</td>';
	addRowHtml += '	<td>';
	addRowHtml += '		<div class="add_box" style="display:'+addBtnType+'">';
	addRowHtml += '			<button onclick="javascript:fn_insertModal_treatmentProcedureDoctorAddRow(\'a\');"><img src="/image/web/add.svg" alt="추가"></button>';
	addRowHtml += '		</div>';
	addRowHtml += '		<div class="subtract_box" style="display:'+subtractBtnType+'">';
	addRowHtml += '			<button onclick="javascript:fn_insertModal_treatmentProcedureRemoveRow(this);"><img src="/image/web/subtract.svg" alt="삭제"></button>';
	addRowHtml += '		</div>';
	addRowHtml += '	</td>';
	addRowHtml += '</tr>';
	parentTable.append(addRowHtml).trigger("create");

	fn_insertModal_treatmentProcedureRefreshOrderNumber(parentTable);
}

/****************************************************************************
 * row 삭제 이벤트
 ****************************************************************************/
function fn_insertModal_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_insertModal_treatmentProcedureRefreshOrderNumber(parentTable);
	}
	else{
		modalEvent.warning("입력 오류", "더 이상 삭제할 수 없습니다.");
	}
}



/****************************************************************************
 * row 정렬순번 변경 이벤트
 - type : A 위로, B 아래로
 ****************************************************************************/
function fn_insertModal_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_insertModal_treatmentProcedureRefreshOrderNumber(parentTable);
}

/****************************************************************************
 * 전체 row 정렬순번 변경
 ****************************************************************************/
function fn_insertModal_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_insertModal_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_insertModal_changeInsuranceType(){
	let insuranceType = $("#insuranceType").val();
	let totalPrice =$('#treatmentProcedureInsertModal #totalPrice').val();
	if(""!==totalPrice){
		if('N'===insuranceType){
			$('#treatmentProcedureInsertModal #price').text(Math.round(totalPrice/1.1));
			$('#treatmentProcedureInsertModal #vat').text(totalPrice-Math.round(totalPrice/1.1));
		}else if('Y'===insuranceType){
			$('#treatmentProcedureInsertModal #price').text(totalPrice);
			$('#treatmentProcedureInsertModal #vat').text(0);
		}
	}
}
