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

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

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

		// 단가 수량 계산
		$('#stockHistoryOutInsertModal #modalPrice, #stockHistoryOutInsertModal #modalQuantity').change(function(){
			let price         = $("#stockHistoryOutInsertModal #modalPrice").val();
			let quantity      = $("#stockHistoryOutInsertModal #modalQuantity").val();
			
			$("#stockHistoryOutInsertModal #modalTotalAmount").text(fn_numberFormat(price*quantity));
		});
		
		// 출고구분 선택 콤보 이벤트
		const target = $("#stockHistoryOutInsertModal #modalType").siblings("ul.select_option_list");
		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);
		});
	},
	/* 데이터 선택 */
	setSelect:function(selectNumber) {
		let fileInput = document.getElementById('releaseFile');
		let uploadNameInput = document.querySelector('.release-upload-name');
		if (fileInput.files.length > 0) {
			let fileName = fileInput.files[0].name;
			uploadNameInput.value = fileName; // 파일 이름을 upload-name 입력 필드에 표시
		}
	},
	// 상세 조회 (거래처, 제품 조회)
	search:function(state) {
		let muTreatmentId = stockHistoryOutInsertModal.reqParam.muTreatmentId;
		let muProductId   = stockHistoryOutInsertModal.reqParam.muProductId;
		let muCompanyId   = stockHistoryOutInsertModal.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){
					$("#stockHistoryOutInsertModal #modalCompanyName").text(data.rows[0].companyName);
					$("#stockHistoryOutInsertModal #modalBusinessNumber").text(data.rows[0].businessNumber);
					$("#stockHistoryOutInsertModal #modalUserName").text(data.rows[0].userName);
					$("#stockHistoryOutInsertModal #modalPhoneNumber").text(fn_setFormatPhone(data.rows[0].phoneNumber));
					$("#stockHistoryOutInsertModal #modalProductTreatmentName").text(data.rows[0].treatmentName);
					$("#stockHistoryOutInsertModal #modalProductName").text(data.rows[0].productName);
					$("#stockHistoryOutInsertModal #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 = stockHistoryOutInsertModal.reqParam.muTreatmentId;
		let muProductId   = stockHistoryOutInsertModal.reqParam.muProductId;
		let muCompanyId   = stockHistoryOutInsertModal.reqParam.muCompanyId;
		
		let type          = $("#stockHistoryOutInsertModal #modalType").val();
		let outDate       = $("#stockHistoryOutInsertModal #modalOutDate").val();
		let price         = $("#stockHistoryOutInsertModal #modalPrice").val();
		let quantity      = $("#stockHistoryOutInsertModal #modalQuantity").val();
		let etc           = $("#stockHistoryOutInsertModal #modalEtc").val();
		let file      	  = $("#stockHistoryOutInsertModal #releaseFile")[0].files[0]??'';

		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(type)) {
			modalEvent.warning("등록", "출고구분 정보가 없습니다.");
			return;
		}

		if(true != fn_emptyCheck(outDate)) {
			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("muTreatmentId", muTreatmentId);
			formData.append("muProductId", muProductId);
			formData.append("muCompanyId", muCompanyId);
			formData.append("type", type);
			formData.append("inOutDate", outDate);
			formData.append("file", file);
			formData.append("price", price);
			formData.append("quantity", quantity);
			formData.append("etc", etc);
	
			$.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( stockHistoryOutInsertModal.callback )  {
								stockHistoryOutInsertModal.callback();
							}
							stockHistoryOutInsertModal.close();
						});
					}
					else{
						modalEvent.danger("등록 오류", data.msgDesc);
					}
				},
				error : function(xhr, status, error) {
					modalEvent.danger("등록 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
				},
				beforeSend:function(){
					
				},
				complete:function(){
					
				}
			});
		});
	},
	/*
	 * 팝업
	 * callback : 콜백함수, reqParam: 팝업파라미터
	 */
	popup:function(callback, reqParam) {
		// 초기화 후 열기
		stockHistoryOutInsertModal.init();
		
		//콜백함수 지정.
		stockHistoryOutInsertModal.callback = callback;
		stockHistoryOutInsertModal.reqParam = reqParam;
		stockHistoryOutInsertModal.dataList = null;
		
		setTimeout(function(){
			$('#stockHistoryOutInsertModal').modal({keyboard:false, backdrop:'static'});
		}, 200);
		
		stockHistoryOutInsertModal.search();
	},
	/*
	 * 팝업 닫기
	 */
	close:function() {
		$('#stockHistoryOutInsertModal').modal('hide');

		setTimeout(function(){
			$('#stockHistoryOutInsertModal').remove();
		},500);
	},
	HtmlTemplate : `
	<div id="stockHistoryOutInsertModal" class="modal sub_release_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="select_box dropdown">
									<button class="label" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">출고 구분</button>
									<input type="hidden" id="modalType" value="" />
									
									<ul class="select_option_list dropdown-menu">
										<li id="li_U" class="option_list_item first">사용</li>
										<li id="li_S" class="option_list_item">판매</li>
										<li id="li_R" class="option_list_item">반품</li>
										<li id="li_D" class="option_list_item">폐기</li>
										<li id="li_E" class="option_list_item">기타</li>
									</ul>
								</div>
							</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="modalOutDate">
									</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="release-upload-name" placeholder="파일 업로드">
									<label for="releaseFile" class="file_btn">업로드</label>
									<input type="file" id="releaseFile" 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>
    `
};