
/* ##############################################################
	설  명 : [Modal]재고조정 상세/수정 팝업
	작성일 : 2023. 01. 19.
	작성자 : NTsoft
	수정일 	        수정자 	 수정내용
	-------         -------- ---------------------------
	2023. 01. 19.	NTsoft 	 최초 생성
*/

let stockSumAdjustmentDetailUpdateModal = {
	callback : null,
	reqParam : null,
	dataList : null,
	/* 모달 초기화 작업 */
	init : function () {
		$('#stockSumAdjustmentDetailUpdateModal').remove();
		$('body').append( this.HtmlTemplate);
		
		//그리드 이벤트
		this.setEvent();
	},
	/* 그리드 이벤트 설정 */
	setEvent:function() {
		$('#stockSumAdjustmentDetailUpdateModal .btnCancle').on("click", function(){
			stockSumAdjustmentDetailUpdateModal.close();
		});
		
		$('#stockSumAdjustmentDetailUpdateModal .btnSave').on("click", function(){
			stockSumAdjustmentDetailUpdateModal.save("I");
		});
	},
	/* 데이터 선택 */
	setSelect:function(selectNumber) {
		let checkedData = dataList[selectNumber];
		if(dataList==null||checkedData==undefined){
			return ;
		}
		
		if( stockSumAdjustmentDetailUpdateModal.callback )  {
			stockSumAdjustmentDetailUpdateModal.callback(checkedData);
		}
		stockSumAdjustmentDetailUpdateModal.close();
	},
	// 상세 조회
	search:function(state) {
		let muTreatmentId = stockSumAdjustmentDetailUpdateModal.reqParam.muTreatmentId;
		let muProductId   = stockSumAdjustmentDetailUpdateModal.reqParam.muProductId;
		let muCompanyId   = stockSumAdjustmentDetailUpdateModal.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('/webstocksumadjustmentdetail/selectListStockSumAdjustmentDetail.do'),
			data: formData,
			dataType: "json",
			processData: false,
			contentType: false,
			type: 'POST',
			async: true,
			success: function(data){
				if('0'==data.msgCode){
					fn_addRow2(data.rows);
				}
				else{
					modalEvent.danger("조회 오류", data.msgDesc);
				}
			},
			error : function(xhr, status, error) {
				modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend:function(){
				
			},
			complete:function(){
				
			}
		});
	},
	//저장
	save:function(state) {
		if("Y"!=updateUseYn){
			modalEvent.warning("", "수정 권한이 없습니다.");
			return false;
		}
		
		let muTreatmentId = stockSumAdjustmentDetailUpdateModal.reqParam.muTreatmentId;
		let muProductId   = stockSumAdjustmentDetailUpdateModal.reqParam.muProductId;
		let muCompanyId   = stockSumAdjustmentDetailUpdateModal.reqParam.muCompanyId;
		
		// 재고조정 정보
		let detailArray = new Object();
		
		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 adjustmentRow = $('#stockSumAdjustmentDetailUpdateModal #modalStockSumAdjustmentRow tr');
		let adjustmentRowLength  = adjustmentRow.length;
		
		let tempArray = new Array();
		for(let i=0 ; i < adjustmentRowLength ; i++){
			let muStockSumId       = adjustmentRow.eq(i).find("td:eq(0)").find('input[name="muStockSumId"]').val();
			let muStockHistoryId   = adjustmentRow.eq(i).find("td:eq(0)").find('input[name="muStockHistoryId"]').val();
			let price              = adjustmentRow.eq(i).find("td:eq(3)").text().replace(/\,/g,'');
			let quantity           = adjustmentRow.eq(i).find("td:eq(7)").find('input[name="adjustmentQuantity"]').val().replace(/\,/g,'');
			let etc                = adjustmentRow.eq(i).find("td:eq(11)").find("input").val().replace(/\,/g,'');
			
			console.log(quantity);
		
			let arr_sub = new Object();
			arr_sub.muStockSumId       = muStockSumId;
			arr_sub.muStockHistoryId   = muStockHistoryId;
			arr_sub.price              = price;
			arr_sub.quantity           = quantity;
			arr_sub.etc                = etc;
			tempArray.push(arr_sub);
			
			detailArray.data = tempArray;
		}
		console.log(detailArray);
		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("detailRows",JSON.stringify(detailArray));
			
			$.ajax({
				url: encodeURI('/webstocksumadjustmentdetail/insertStockAdjustmentDetail.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( stockSumAdjustmentDetailUpdateModal.callback )  {
								stockSumAdjustmentDetailUpdateModal.callback();
							}
							stockSumAdjustmentDetailUpdateModal.close();
						});
					}
					else{
						modalEvent.danger("수정 오류", data.msgDesc);
					}
				},
				error : function(xhr, status, error) {
					modalEvent.danger("수정 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
				},
				beforeSend:function(){
					
				},
				complete:function(){
					
				}
			});
		});
	},
	/*
	 * 팝업
	 * callback : 콜백함수, reqParam: 팝업파라미터
	 */
	popup:function(callback, reqParam) {
		// 초기화 후 열기
		stockSumAdjustmentDetailUpdateModal.init();
		
		//콜백함수 지정.
		stockSumAdjustmentDetailUpdateModal.callback = callback;
		stockSumAdjustmentDetailUpdateModal.reqParam = reqParam;
		stockSumAdjustmentDetailUpdateModal.dataList = null;
		
		setTimeout(function(){
			$('#stockSumAdjustmentDetailUpdateModal').modal('show')
		}, 200);
		
		stockSumAdjustmentDetailUpdateModal.search();
	},
	/*
	 * 팝업 닫기
	 */
	close:function() {
		$('#stockSumAdjustmentDetailUpdateModal').modal('hide');

		setTimeout(function(){
			$('#stockSumAdjustmentDetailUpdateModal').remove();
		},500);
	},
	HtmlTemplate : `
	<div id="stockSumAdjustmentDetailUpdateModal" class="modal inventory_adjustment 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="table_box">
						<table>
							<thead>
								<tr>
									<th>입고 날짜</th>
									<th>제품명</th>
									<th>거래처</th>
									<th class="narrow">단가</th>
									<th>수량</th>
									<th>재고 금액</th>
									<th class="narrow">증감 선택</th>
									<th class="wide">조정 수량</th>
									<th>조정 금액</th>
									<th class="narrow">총 수량</th>
									<th>총 금액</th>
									<th class="memo">메모</th>
								</tr>
							</thead>
							<tbody id="modalStockSumAdjustmentRow"></tbody>
							<tfoot id="modalStockSumAdjustmentFootRow">
								<tr>
									<td></td>
									<td></td>
									<td></td>
									<td class="alignRight">0</td>
									<td class="alignRight">0</td>
									<td class="alignRight">0</td>
									<td></td>
									<td class="alignRight">0</td>
									<td class="alignRight">0</td>
									<td class="alignRight">0</td>
									<td class="alignRight">0</td>
									<td></td>
								</tr>
							</tfoot>
						</table>
					</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_addRow2(detailList){
	let addRowHtml = '';
	
	if(0<detailList.length){
		for(let i = 0; i < detailList.length; i++){
			let muStockSumId     = detailList[i].muStockSumId;
			let muStockHistoryId = detailList[i].muStockHistoryId;
			let inDate           = detailList[i].inDate;
			let productName      = detailList[i].productName;
			let companyName      = detailList[i].companyName;
			let price            = detailList[i].price;
			let quantity         = detailList[i].quantity;
			let amount           = detailList[i].amount;
			let etc              = detailList[i].etc;
			
			addRowHtml += '<tr>';
			addRowHtml += '	<td>';
			addRowHtml += '	<input type="hidden" name="muStockSumId" value="'+muStockSumId+'"/>';
			addRowHtml += '	<input type="hidden" name="muStockHistoryId" value="'+muStockHistoryId+'"/>';
			addRowHtml += inDate;
			addRowHtml += '	</td>';
			addRowHtml += '	<td>'+productName+'</td>';
			addRowHtml += '	<td>'+companyName+'</td>';
			addRowHtml += '	<td class="alignRight">'+price+'</td>';
			addRowHtml += '	<td class="alignRight">'+quantity+'</td>';
			addRowHtml += '	<td class="alignRight">'+amount+'</td>';
			addRowHtml += '	<td>';
			addRowHtml += '		<div class="button_box">';
			addRowHtml += '			<div class="add_box">';
			addRowHtml += '				<button onclick="javascript:fn_updateModalIncrease(this);"><img src="/image/web/add.svg" alt="추가"/></button>';
			addRowHtml += '			</div>';
			addRowHtml += '			<div class="subtract_box">';
			addRowHtml += '				<button onclick="javascript:fn_updateModalDecrease(this);"><img src="/image/web/subtract.svg" alt="삭제"></button>';
			addRowHtml += '			</div>';
			addRowHtml += '		</div>';
			addRowHtml += '	</td>';
			addRowHtml += '	<td>';
			addRowHtml += '		<div class="input_box">';
			addRowHtml += '			<input type="number" name="adjustmentQuantity" placeholder="0" readonly style="cursor:default;"/>';
			addRowHtml += '		</div>';
			addRowHtml += '	</td>';
			addRowHtml += '	<td class="alignRight">0</td>';
			addRowHtml += '	<td class="alignRight">'+quantity+'</td>';
			addRowHtml += '	<td class="alignRight">'+amount+'</td>';
			addRowHtml += '	<td>';
			addRowHtml += '		<div class="input_box">';
			addRowHtml += '			<input type="text" name="adjustmentEtc" maxlength="255"/>';
			addRowHtml += '		</div>';
			addRowHtml += '	</td>';
			addRowHtml += '</tr>';
		}
		$('#stockSumAdjustmentDetailUpdateModal #modalStockSumAdjustmentRow').empty().html(addRowHtml).trigger("create");
	}
	
	fn_updateModalFooterAmount();
}


/****************************************************************************
* 조정수량 증가
****************************************************************************/
function fn_updateModalIncrease(target){
	let adjustmentQuantity = $(target).closest("tr").find("td:eq(7)").find("input").val();
	adjustmentQuantity++;
	
	$(target).closest("tr").find("td:eq(7)").find("input").val(adjustmentQuantity);
	
	fn_updateModalAmount(target);
}

/****************************************************************************
* 조정수량 감소
****************************************************************************/
function fn_updateModalDecrease(target){
	let adjustmentQuantity = $(target).closest("tr").find("td:eq(7)").find("input").val();
	adjustmentQuantity--;
	
	$(target).closest("tr").find("td:eq(7)").find("input").val(adjustmentQuantity);
	
	fn_updateModalAmount(target);
}

/****************************************************************************
* 조정금액, 총수량, 총금액 계산
****************************************************************************/
function fn_updateModalAmount(target){
	let price    = $(target).closest("tr").find("td:eq(3)").text().replace(/\,/g,'');
	let quantity = $(target).closest("tr").find("td:eq(4)").text().replace(/\,/g,'');
	let adjustmentQuantity = $(target).closest("tr").find("td:eq(7)").find("input").val().replace(/\,/g,'');
	
	// 조정금액
	let adjustmentAmount = parseInt(price) * parseInt(adjustmentQuantity);
	$(target).closest("tr").find("td:eq(8)").text(fn_numberFormat(adjustmentAmount));
	
	// 총수량
	let totalQuantity = parseFloat(quantity) + parseFloat(adjustmentQuantity);
	$(target).closest("tr").find("td:eq(9)").text(fn_numberFormat(totalQuantity));
	
	// 총금액
	let totalAmount = parseInt(price) * parseFloat(totalQuantity);
	$(target).closest("tr").find("td:eq(10)").text(fn_numberFormat(totalAmount));
	
	fn_updateModalFooterAmount();
}

/****************************************************************************
* footer 평균 단가, 총 수량, 총 재고금액, 총 조정수량, 총 조정금액, 총 수량, 총 금액 
****************************************************************************/
function fn_updateModalFooterAmount(){
	let target = $("#stockSumAdjustmentDetailUpdateModal #modalStockSumAdjustmentRow tr");
	
	if(0<target.length){
		
		let footerPrice    = 0;
		let footerQuantity = 0;
		let footerAmount   = 0;
		
		let footerAdjustmentQuantity = 0;
		let footerAdjustmentAmount   = 0;
		let footertotalQuantity      = 0;
		let footerTotalAmount        = 0;
		
		for(let i = 0; i < target.length; i++){
			// 단가
			let price    = target.eq(i).find("td:eq(3)").text().replace(/\,/g,'');
			footerPrice = parseInt(footerPrice)+parseInt(price);
			
			// 수량
			let quantity    = target.eq(i).find("td:eq(4)").text().replace(/\,/g,'');
			footerQuantity = parseFloat(footerQuantity)+parseFloat(quantity);
			
			// 재고금액
			let amount    = target.eq(i).find("td:eq(5)").text().replace(/\,/g,'');
			footerAmount = parseInt(footerAmount)+parseInt(amount);
			
			// 조정수량
			let adjustmentQuantity   = target.eq(i).find("td:eq(7)").find("input").val().replace(/\,/g,'');
			if(true != fn_emptyCheck(adjustmentQuantity)){
			}
			else{
				footerAdjustmentQuantity = parseFloat(footerAdjustmentQuantity)+parseFloat(adjustmentQuantity);
			}
			
			// 조정금액
			let adjustmentAmount    = target.eq(i).find("td:eq(8)").text().replace(/\,/g,'');
			footerAdjustmentAmount = parseInt(footerAdjustmentAmount)+parseInt(adjustmentAmount);
			
			// 총수량
			let totalQuantity    = target.eq(i).find("td:eq(9)").text().replace(/\,/g,'');
			footertotalQuantity = parseFloat(footertotalQuantity)+parseFloat(totalQuantity);
			
			// 총금액
			let totalAmount    = target.eq(i).find("td:eq(10)").text().replace(/\,/g,'');
			footerTotalAmount = parseInt(footerTotalAmount)+parseInt(totalAmount);
			
		}
		
		let footerTarget = $("#stockSumAdjustmentDetailUpdateModal #modalStockSumAdjustmentFootRow tr");
		
		// 단가
		footerPrice = footerPrice / target.length;
		footerTarget.find("td:eq(3)").text(fn_numberFormat(Math.round(footerPrice)));
		
		// 수량
		footerTarget.find("td:eq(4)").text(fn_numberFormat(footerQuantity));
		
		// 재고금액
		footerTarget.find("td:eq(5)").text(fn_numberFormat(Math.round(footerAmount)));
		
		// 조정수량
		footerTarget.find("td:eq(7)").text(fn_numberFormat(footerAdjustmentQuantity));
		
		// 조정금액
		footerTarget.find("td:eq(8)").text(fn_numberFormat(Math.round(footerAdjustmentAmount)));
		
		// 총수량
		footerTarget.find("td:eq(9)").text(fn_numberFormat(footertotalQuantity));
		
		// 총금액
		footerTarget.find("td:eq(10)").text(fn_numberFormat(Math.round(footerTotalAmount)));
	}
}
