
/* ##############################################################
	설  명 : [Modal]거래처관리 등록 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/
let companyInsertModal = {
	callback : null,
	reqParam : null,
	dataList : null,
	/* 모달 초기화 작업 */
	init : function () {
		$('#companyInsertModal').remove();
		$('body').append( this.HtmlTemplate);
		//그리드 이벤트
		this.setEvent();
	},
	/* 그리드 이벤트 설정 */
	setEvent:function() {
		$('#companyInsertModal .btnCancle').on("click", function(){
			companyInsertModal.close();
		});
		
		$('#companyInsertModal .btnSave').on("click", function(){
			companyInsertModal.save("I");
		});
	},
	/* 데이터 선택 */
	setSelect:function(selectNumber) {
		let checkedData = dataList[selectNumber];
		if(dataList==null||checkedData==undefined){
			return ;
		}
		
		if( companyInsertModal.callback )  {
			companyInsertModal.callback(checkedData);
		}
		companyInsertModal.close();
	},
	//저장
	save:function(state) {
		let companyName      = $("#companyInsertModal #modalCompanyName").val();
		let businessNumber   = $("#companyInsertModal #modalBusinessNumber").val();
		let userName         = $("#companyInsertModal #modalUserName").val();
		let phoneNumber      = $("#companyInsertModal #modalPhoneNumber").val();
		let email            = $("#companyInsertModal #modalEmail").val();
		let memo             = $("#companyInsertModal #modalMemo").val();
		
		let reg_email    = /^([0-9a-zA-Z_\.-]+)@([0-9a-zA-Z_-]+)(\.[0-9a-zA-Z_-]+){1,2}$/;
		let reg_tel      = /^[0-9]{8,11}$/;
	
		// 제품 정보
		let detailArray = new Object();
		
		if("Y"!=insertUseYn){
			modalEvent.warning("등록", "등록 권한이 없습니다.");
			return false;
		}

		if(true != fn_emptyCheck(companyName)){
			modalEvent.warning("등록", "거래처명 정보가 없습니다.");
			return;
		}
		else{
			if(true != fn_lengthCheck(companyName, 35)) {
				modalEvent.warning("등록", "거래처명 정보는 35자를 넘을 수 없습니다.");
				return;
			}
		}
		//
		// if(true != fn_emptyCheck(businessNumber)){
		// 	modalEvent.warning("등록", "사업자번호 정보가 없습니다.");
		// 	return;
		// }
		//
		// if(true != fn_emptyCheck(userName)){
		// 	modalEvent.warning("등록", "담당자 정보가 없습니다.");
		// 	return;
		// }
		if(true == fn_emptyCheck(userName)&&true != fn_lengthCheck(userName, 35)) {
			modalEvent.warning("등록", "담당자명 정보는 35자를 넘을 수 없습니다.");
			return;
		}
		if(true == fn_emptyCheck(phoneNumber)&&reg_tel.test(phoneNumber) != true){
			modalEvent.warning("등록", "연락처 정보는 숫자 8~11자리여야 합니다");
			return;
		}
		else{
			phoneNumber = phoneNumber.replace("-", "");
		}

		// if(true != fn_emptyCheck(email)){
		// 	modalEvent.warning("등록", "이메일 정보를 입력하세요");
		// 	return;
		// }
		if(true == fn_emptyCheck(email)&&!reg_email.test(email)) {
			modalEvent.warning("등록", "이메일 정보를 형식에 맞게 입력해주세요");
			return ;
		}
		
		// 제품 정보
		let productTr = $('#companyInsertModal #modalProductList').children('tr');
		let trLength  = productTr.length;
		
		let tempArray = new Array();
		for(let i=0 ; i < trLength ; i++){
			let categoryCode  = productTr.eq(i).find('input[name="categoryCode"]').val();
			let productName    = productTr.eq(i).find('input[name="productName"]').val();
			let volume         = productTr.eq(i).find('input[name="volume"]').val();
			let unitCode       = productTr.eq(i).find('input[name="unit"]').val();
			let unitName 	   = productTr.eq(i).find('input[name="unit"]').siblings('button').text();
			let usage_volume   = productTr.eq(i).find('input[name="usage_volume"]').val();
			let usage_unitCode = productTr.eq(i).find('input[name="usage_unit"]').val();
			let usage_unitName = productTr.eq(i).find('input[name="usage_unit"]').siblings('button').text();

			let arr_sub = new Object();
			arr_sub.categoryCode 	= categoryCode;
			arr_sub.productName   	= productName;
			arr_sub.volume        	= volume;
			arr_sub.unitCode        = unitCode;
			arr_sub.unitName        = unitName==='제품단위'?'':unitName;
			arr_sub.usage_volume    = usage_volume;
			arr_sub.usage_unitCode  = usage_unitCode;
			arr_sub.usage_unitName  = usage_unitName==='제품단위'?'':usage_unitName;

			if(categoryCode||productName||volume||unitCode||unitCode||arr_sub.unitName) {
				if (true != fn_emptyCheck(categoryCode)) {
					modalEvent.warning("등록", "거래처 제품 중 구분 정보가 없습니다.");
					return;
				} else if (true != fn_emptyCheck(productName)) {
					modalEvent.warning("등록", "거래처 제품 중 제품명 정보가 없습니다.");
					return;
				} else if (true != fn_emptyCheck(volume)) {
					modalEvent.warning("등록", "거래처 제품 중 용량 정보가 없습니다.");
					return;
				} else if (true != fn_emptyCheck(unitCode)) {
					modalEvent.warning("등록", "거래처 제품 중 단위 정보가 없습니다.");
					return;
				} else if (true != fn_emptyCheck(unitName)) {
					modalEvent.warning("등록", "거래처 제품 중 단위 정보가 없습니다.");
					return;
				} else if (true != fn_emptyCheck(usage_volume)) {
					modalEvent.warning("등록", "거래처 제품 중 사용량 정보가 없습니다.");
					return;
				} else if (true != fn_emptyCheck(usage_unitCode)) {
					modalEvent.warning("등록", "거래처 제품 중 사용량 단위 정보가 없습니다.");
					return;
				} else if (true != fn_emptyCheck(usage_unitName)) {
					modalEvent.warning("등록", "거래처 제품 중 사용량 단위 정보가 없습니다.");
					return;
				}
				tempArray.push(arr_sub);
			}
			detailArray.data = tempArray;
		}
		
		modalEvent.info("등록", "거래처 정보를 등록하시겠습니까?", function(){
			let formData = new FormData();
			formData.append("menuClass", menuClass);
			formData.append("companyName", companyName);
			formData.append("businessNumber", businessNumber);
			formData.append("userName", userName);
			formData.append("phoneNumber", phoneNumber);
			formData.append("email", email);
			formData.append("memo", memo);
			formData.append("companyProductRows",JSON.stringify(detailArray));
	
			$.ajax({
				url: encodeURI('/webcompany/insertCompany.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( companyInsertModal.callback )  {
								companyInsertModal.callback();
							}
							companyInsertModal.close();
						});
					}
					else{
						modalEvent.danger("등록 오류", data.msgDesc);
					}
				},
				error : function(xhr, status, error) {
					modalEvent.danger("등록 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
				},
				beforeSend:function(){

				},
				complete:function(){

				}
			});
		});
	},
	/*
	 * 팝업
	 * callback : 콜백함수, reqParam: 팝업파라미터
	 */
	popup:function(callback, reqParam) {
		// 초기화 후 열기
		companyInsertModal.init();
		
		//콜백함수 지정.
		companyInsertModal.callback = callback;
		companyInsertModal.reqParam = reqParam;
		companyInsertModal.dataList = null;
		
		// 초기화
		fn_insertModal_addRow();
		let parentTable = $("#companyInsertModal #modalProductList");
		fn_insertModal_companyRefreshOrderNumber(parentTable);
		
		setTimeout(function(){
			$('#companyInsertModal').modal('show')
		}, 200);
	},
	/*
	 * 팝업 닫기
	 */
	close:function() {
		$('#companyInsertModal').modal('hide');

		setTimeout(function(){
			$('#companyInsertModal').remove();
		},500);
	},
	HtmlTemplate : `
	<div id="companyInsertModal" class="modal business_partner_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">
						<ul class="first">
							<li>
								<label>사업자명</label>
								<div class="input_box">
									<input type="text" id="modalCompanyName" placeholder="사업자명을 입력해주세요." maxlength="35">
								</div>
							</li>
							<li>
								<label>사업자번호</label>
								<div class="input_box">
									<input type="text" id="modalBusinessNumber" placeholder="- 제외" maxlength="13">
								</div>
							</li>
							<li>
								<label>거래처 담당자</label>
								<div class="input_box">
									<input type="text" id="modalUserName" placeholder="담당자 성명" maxlength="35">
								</div>
							</li>
							<li>
								<label>연락처</label>
								<div class="input_box">
									<input type="text" id="modalPhoneNumber" placeholder="- 제외" maxlength="13">
								</div>
							</li>
							<li>
								<label>이메일</label>
								<div class="input_box">
									<input type="text" id="modalEmail" placeholder="이메일" maxlength="255">
								</div>
							</li>
							<li>
								<label>거래처 메모</label>
								<div class="textarea_box">
									<textarea id="modalMemo" placeholder="내용을 입력해주세요."></textarea>
								</div>
							</li>
						</ul>
						<div class="table_box">
							<label>취급 제품</label>
							<div>
								<table>
									<thead>
										<tr>
											<th>재고구분</th>
											<th>제품명</th>
											<th>용량</th>
											<th>제품단위</th>
											<th>사용량</th>
											<th>사용량 단위</th>
											<th></th>
										</tr>
									</thead>
								<tbody id="modalProductList"></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>
    `
};

/****************************************************************************
* row 추가 이벤트
****************************************************************************/
function fn_insertModal_addRow(param){
	let addRowHtml = '';
	addRowHtml += '<tr>';
	addRowHtml += '	<td>';
	addRowHtml += '		<div class="select_box first dropdown">';
	addRowHtml += '			<button class="label" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">재고구분</button>';
	addRowHtml += '			<input type="hidden" name="categoryCode" value=""/>';
	
	addRowHtml += '			<ul class="select_option_list dropdown-menu">';
	addRowHtml +='			</ul>';
	addRowHtml += '		</div>';
	addRowHtml += '	</td>';
	
	addRowHtml += '	<td>';
	addRowHtml += '		<div class="input_box">';
	addRowHtml += '			<input type="text" name="productName" placeholder="" value="" maxlength="35">';
	addRowHtml += '		</div>';
	addRowHtml += '	</td>';
	
	addRowHtml += '	<td>';
	addRowHtml += '		<div class="input_box">';
	addRowHtml += '			<input type="text" name="volume" placeholder="" value="" maxlength="255">';
	addRowHtml += '		</div>';
	addRowHtml += '	</td>';
	
	addRowHtml += '	<td>';
	addRowHtml += '		<div class="select_box dropdown">';
	addRowHtml += '			<button class="label" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">제품단위</button>';
	addRowHtml += '			<input type="hidden" name="unit" value=""/>';
	
	addRowHtml += '			<ul class="select_option_list dropdown-menu">';	
	addRowHtml +='			</ul>';
	addRowHtml += '		</div>';
	addRowHtml += '	</td>';
	
	addRowHtml += '	<td>';
	addRowHtml += '		<div class="input_box">';
	addRowHtml += '			<input type="text" name="usage_volume" placeholder="" value="" maxlength="255">';
	addRowHtml += '		</div>';
	addRowHtml += '	</td>';
	
	addRowHtml += '	<td>';
	addRowHtml += '		<div class="select_box dropdown">';
	addRowHtml += '			<button class="label" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">제품단위</button>';
	addRowHtml += '			<input type="hidden" name="usage_unit" value=""/>';
	
	addRowHtml += '			<ul class="select_option_list dropdown-menu">';	
	addRowHtml +='			</ul>';
	addRowHtml += '		</div>';
	addRowHtml += '	</td>';

	addRowHtml += '	<td>';
	addRowHtml += '		<div class="add_box"><button class="add_btn" onclick="javascript:fn_insertModal_addRow(this);"><img src="/image/web/add.svg" alt="추가"/></button></div>';
	addRowHtml += '		<div class="subtract_box" style="display:none;"><button class="add_btn" onclick="javascript:fn_insertModal_removeRow(this);"><img src="/image/web/subtract.svg" style="width:100%;" alt="삭제"/></button></div>';
	addRowHtml += '	</td>';
	addRowHtml += '</tr>';
	$('#companyInsertModal #modalProductList').append(addRowHtml).trigger("create");
	fn_insertModal_setTreatmentCombo();
	fn_insertModal_setUnitCombo();

	let parentTable = $("#companyInsertModal #modalProductList");
	fn_insertModal_companyRefreshOrderNumber(parentTable);
}

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

/****************************************************************************
* 전체 row 버튼 변경
****************************************************************************/
function fn_insertModal_companyRefreshOrderNumber(param){
	// row 추가/삭제 버튼 처리
	$(param).find(".add_box").hide();
	$(param).find('.subtract_box').show();
	$(param).children("tr:eq(0)").find(".subtract_box").hide();
	$(param).children("tr:eq(0)").find(".add_box").show();
}

/****************************************************************************
* 진료 콤보데이타 설정 (동적 추가)
****************************************************************************/
function fn_insertModal_setTreatmentCombo(){
	const target = $('#companyInsertModal #modalProductList').children('tr').find('input[name="categoryCode"]').siblings("ul.select_option_list");
	let category = fn_selectCategoryList2();
	let reservationCategory = category.find(cat => cat.categoryName === '재고구분');

	if (reservationCategory) {
		fn_selectModalOtherOption2(reservationCategory.categoryCode);
	}
	target.find("li.option_list_item").click(function () {
		let selectIdArr = $(this).prop("id").split('_');
		let selectId    = selectIdArr[1];
		let selectName  = $(this).text();

		$(this).parent().siblings("button").text(selectName);
		$(this).parent().siblings("input").val(selectId);
	});
}
/****************************************************************************
 * 제품 단위 콤보데이타 설정 (동적 추가)
 ****************************************************************************/
function fn_insertModal_setUnitCombo(){
	const target = $('#companyInsertModal #modalProductList').children('tr').find('input[name="unit"]').siblings("ul.select_option_list");

	let category = fn_selectCategoryList2();
	let reservationCategory = category.find(cat => cat.categoryName === '제품단위');

	if (reservationCategory) {
		fn_selectModalOtherOption2(reservationCategory.categoryCode);
	}
	
	const target2 = $('#companyInsertModal #modalProductList').children('tr').find('input[name="usage_unit"]').siblings("ul.select_option_list");
	let category2 = fn_selectCategoryList2();
	let reservationCategory2 = category2.find(cat => cat.categoryName === '제품단위');

	if (reservationCategory2) {
		fn_selectModalOtherOption2(reservationCategory2.categoryCode);
	}
	
	target.find("li.option_list_item").click(function () {
			let selectIdArr = $(this).prop("id").split('_');
			let selectId    = selectIdArr[1];
			let selectName  = $(this).text();

			$(this).parent().siblings("button").text(selectName);
			$(this).parent().siblings("input").val(selectId);
		});
		
	target2.find("li.option_list_item").click(function () {		
		let selectIdArr = $(this).prop("id").split('_');
		let selectId    = selectIdArr[1];
		let selectName  = $(this).text();

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

/****************************************************************************
* select box 선택 값 id, text로 셋팅
****************************************************************************/
function fn_insertModal_clickSelectValue(target){
	let selectIdArr = $(target).prop("id").split('_');
	let selectId    = selectIdArr[1];
	let selectName  = $(target).text();
	
	$(target).parent().siblings("button").text(selectName);
	$(target).parent().siblings("input").val(selectId);
}

/****************************************************************************
* select box 선택 값 셋팅
****************************************************************************/
function fn_insertModal_clickSelectTextValue(target, param, paramText){
	$(target).parent().siblings("button").text(paramText);
	$(target).parent().siblings("input").val(param);
}