
/* ##############################################################
	설  명 : [Modal]입출고 내역 입고 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/
let stockHistoryInInsertModal = {
	callback : null,
	reqParam : null,
	dataList : null,
	/* 모달 초기화 작업 */
	init : function () {
		$('#stockHistoryInInsertModal').remove();
		$('body').append( this.HtmlTemplate);
		//그리드 이벤트
		this.setEvent();
	},
	/* 그리드 이벤트 설정 */
	setEvent:function() {
		$('#stockHistoryInInsertModal .btnCancle').on("click", function(){
			stockHistoryInInsertModal.close();
		});
		
		$('#stockHistoryInInsertModal .btnSave').on("click", function(){
			stockHistoryInInsertModal.save("I");
		});
		
		$("#stockHistoryInInsertModal #modalInDate").datetimepicker({
			allowInputToggle: true,
			format: 'YYYY-MM-DD',
			defaultDate: moment()
		});
		$("#stockHistoryInInsertModal #ibgoFile").on("change",function(){
			stockHistoryInInsertModal.setSelect();
		});

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

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

		// 단가 수량 계산
		$('#stockHistoryInInsertModal #modalPrice, #stockHistoryInInsertModal #modalQuantity').change(function(){
			let price         = $("#stockHistoryInInsertModal #modalPrice").val();
			let quantity      = $("#stockHistoryInInsertModal #modalQuantity").val();
			
			$("#stockHistoryInInsertModal #modalTotalAmount").text(fn_numberFormat(price*quantity));
		});
	},
	/* 데이터 선택 */
	setSelect:function(selectNumber) {
		let fileInput = document.getElementById('ibgoFile');
		let uploadNameInput = document.querySelector('.ibgo-upload-name');
		if (fileInput.files.length > 0) {
			let fileName = fileInput.files[0].name;
			uploadNameInput.value = fileName; // 파일 이름을 upload-name 입력 필드에 표시
		}
	},
	// 상세 조회 (거래처, 제품 조회)
	search:function(state) {
		let muTreatmentId = stockHistoryInInsertModal.reqParam.muTreatmentId;
		let muProductId   = stockHistoryInInsertModal.reqParam.muProductId;
		let muCompanyId   = stockHistoryInInsertModal.reqParam.muCompanyId;
		
		if(true != fn_emptyCheck(muTreatmentId)){
			modalEvent.warning("조회", "구분 정보가 없습니다.");	
			return;
		}
		
		if(true != fn_emptyCheck(muProductId)){
			modalEvent.warning("조회", "제품 정보가 없습니다.");	
			return;
		}
		
		if(true != fn_emptyCheck(muCompanyId)){
			modalEvent.warning("조회", "거래처 정보가 없습니다.");	
			return;
		}
		
		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("muTreatmentId", muTreatmentId);
		formData.append("muProductId", muProductId);
		formData.append("muCompanyId", muCompanyId);

		$.ajax({
			url: encodeURI('/webcompany/selectCompanyProduct.do'),
			data: formData,
			dataType: "json",
			processData: false,
			contentType: false,
			type: 'POST',
			async: true,
			success: function(data){
				if('0'==data.msgCode){
					$("#stockHistoryInInsertModal #modalCompanyName").text(data.rows[0].companyName);
					$("#stockHistoryInInsertModal #modalBusinessNumber").text(data.rows[0].businessNumber);
					$("#stockHistoryInInsertModal #modalUserName").text(data.rows[0].userName);
					$("#stockHistoryInInsertModal #modalPhoneNumber").text(fn_setFormatPhone(data.rows[0].phoneNumber));
					$("#stockHistoryInInsertModal #modalProductTreatmentName").text(data.rows[0].treatmentName);
					$("#stockHistoryInInsertModal #modalProductName").text(data.rows[0].productName);
					$("#stockHistoryInInsertModal #modalMemberName").text(data.rows[0].memberName);
				}
				else{
					modalEvent.danger("조회 오류", data.msgDesc);
				}
			},
			error : function(xhr, status, error) {
				modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend:function(){
				
			},
			complete:function(){
				
			}
		});
	},
	//저장
	save:function(state) {
		let muTreatmentId = stockHistoryInInsertModal.reqParam.muTreatmentId;
		let muProductId   = stockHistoryInInsertModal.reqParam.muProductId;
		let muCompanyId   = stockHistoryInInsertModal.reqParam.muCompanyId;
		
		let inDate        = $("#stockHistoryInInsertModal #modalInDate").val();
		let price         = $("#stockHistoryInInsertModal #modalPrice").val();
		let quantity      = $("#stockHistoryInInsertModal #modalQuantity").val();
		let file      	  = $("#stockHistoryInInsertModal #ibgoFile")[0].files[0]??'';
		let etc           = $("#stockHistoryInInsertModal #modalEtc").val();
		
		if(true != fn_emptyCheck(muTreatmentId)){
			modalEvent.warning("등록", "구분 정보가 없습니다.");	
			return;
		}
		
		if(true != fn_emptyCheck(muProductId)) {
			modalEvent.warning("등록", "제품 정보가 업습니다.");
			return;
		}
		
		if(true != fn_emptyCheck(muCompanyId)) {
			modalEvent.warning("등록", "거래처 정보가 업습니다.");
			return;
		}

		if(true != fn_emptyCheck(inDate)) {
			modalEvent.warning("등록", "입고일자 정보가 없습니다.");
			return;
		}

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

		if(true != fn_emptyCheck(quantity)) {
			modalEvent.warning("등록", "수량 정보가 없습니다.");
			return;
		}
		
		modalEvent.info("등록", "입고 정보를 등록하시겠습니까?", function(){
			let formData = new FormData();
			formData.append("menuClass", menuClass);
			formData.append("type", "I");
			formData.append("muTreatmentId", muTreatmentId);
			formData.append("muProductId", muProductId);
			formData.append("muCompanyId", muCompanyId);
			formData.append("inOutDate", inDate);
			formData.append("price", price);
			formData.append("quantity", quantity);
			formData.append("etc", etc);
			formData.append("file", file);

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

				},
				complete:function(){

				}
			});
		});
	},
	/*
	 * 팝업
	 * callback : 콜백함수, reqParam: 팝업파라미터
	 */
	popup:function(callback, reqParam) {
		// 초기화 후 열기
		stockHistoryInInsertModal.init();
		
		//콜백함수 지정.
		stockHistoryInInsertModal.callback = callback;
		stockHistoryInInsertModal.reqParam = reqParam;
		stockHistoryInInsertModal.dataList = null;
		
		setTimeout(function(){
			$('#stockHistoryInInsertModal').modal({keyboard:false, backdrop:'static'});
		}, 200);
		
		stockHistoryInInsertModal.search();
	},
	/*
	 * 팝업 닫기
	 */
	close:function() {
		$('#stockHistoryInInsertModal').modal('hide');

		setTimeout(function(){
			$('#stockHistoryInInsertModal').remove();
		},500);
	},
	HtmlTemplate : `
	<div id="stockHistoryInInsertModal" class="modal sub_ibgo_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>
								<p id="modalCompanyName"></p>
							</li>
							<li>
								<label>사업자번호</label>
								<p id="modalBusinessNumber"></p>
							</li>
							<li>
								<label>거래처 담당자</label>
								<p id="modalUserName"></p>
							</li>
							<li>
								<label>연락처</label>
								<p id="modalPhoneNumber"></p>
							</li>
						</ul>

						<ul>
							<li>
								<label>재고구분</label>
								<p id="modalProductTreatmentName"></p>
							</li>
							<li>
								<label>제품명</label>
								<p id="modalProductName"></p>
							</li>
							<li>
								<label>입고일</label>
								<div class="calendar_box">
									<div class="date_box">
										<img src="/image/web/calendar.svg">
										<input type="date" class="date_picker" id="modalInDate">
									</div>
								</div>
							</li>
							<li>
								<label>단가</label>
								<div class="input_box">
									<input type="text" id="modalPrice" placeholder="0">
								</div>
								<p>원</p>
							</li>
							<li>
								<label>수량</label>
								<div class="input_box">
									<input type="text" id="modalQuantity" placeholder="0">
								</div>
							</li>
							<li>
								<label>파일 업로드</label>
								<div class="file_box">
									<input class="ibgo-upload-name" placeholder="파일 업로드">
									<label for="ibgoFile" class="file_btn">업로드</label>
									<input type="file" id="ibgoFile" accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.pdf,application/pdf,.hwp,application/x-hwp,.xls,.xlsx,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"">
                            	</div>
							</li>
							<li>
								<label>총액</label>
								<p id="modalTotalAmount">0</p>
							</li>
						</ul>
						
						<ul>
							<li>
								<label>담당자</label>
								<p id="modalMemberName"></p>
							</li>
							<li>
								<label>메모</label>
								<div class="textarea_box">
									<textarea id="modalEtc" placeholder="내용을 입력해주세요."></textarea>
								</div>
							</li>
						</ul>
					</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>
    `
};