<%@ page contentType="text/html; charset=UTF-8"%>
<%@ include file="/WEB-INF/jspf/taglibs.jsp"%>

<c:set var="uiid" value="${u:uiid()}"/>

<%-- Balance lookup: invBal<uiid>['storeId_itemId'] = [qty, reserved] --%>
<script>
var invBal${uiid} = {};
<c:forEach var="b" items="${frd.balanceItems}">invBal${uiid}['${b.storeId}_${b.itemId}'] = [${b.quantity}, ${b.reserved}];
</c:forEach>
var invSelItem${uiid} = '';
function invBalShow${uiid}(itemId) {
	if (itemId !== undefined) invSelItem${uiid} = itemId;
	var sid = $('#${uiid} [name=storeId]').val();
	var d = invBal${uiid}[sid + '_' + invSelItem${uiid}];
	var $el = $('#invbal${uiid}');
	if (d && sid && invSelItem${uiid}) {
		var avail = Math.round((+d[0] - +d[1]) * 1000) / 1000;
		$el.html('<b>${l.l('На складе')}:</b> ' + d[0] + ' &nbsp;|&nbsp; <b>${l.l('Резерв')}:</b> ' + d[1] + ' &nbsp;|&nbsp; <b>${l.l('Доступно')}:</b> ' + avail).show();
	} else {
		$el.hide();
	}
}
function invAddRow${uiid}() {
	var $table = $('#tbl${uiid}');
	var form = $table.closest('form')[0];
	var itemId = form.newItemId.value;
	var itemTitle = form.newItemTitle.value;
	var itemCount = form.newItemCount.value;
	if (!itemId) { alert('${l.l('Не выбрана номенклатура')}'); return; }
	if (!itemCount) { alert('${l.l('Не указано количество')}'); return; }
	var $tr = $('<tr class="inv-new-row">' +
		'<td><input type="hidden" name="itemId" value="' + itemId + '"/>' + $('<span/>').text(itemTitle).html() + '</td>' +
		'<td><input type="text" name="itemCount" value="' + itemCount + '" size="4" onkeydown="return isNumberKey(event)" title="${l.l('Use dot as a decimal separator')}"/></td>' +
		'<td><button class="btn-white icon" type="button" onclick="$(this).closest(\'tr\').remove();"><i class="ti-trash"></i></button></td>' +
		'</tr>');
	$table.find('tr:last-child').before($tr);
	form.newItemId.value = '';
	form.newItemTitle.value = '';
	form.newItemCount.value = '';
	$(form).find('input.ui-autocomplete-input').val('');
	invSelItem${uiid} = '';
	$('#invbal${uiid}').hide();
}
</script>

<div id="${uiid}">
	<%-- Already saved reserves and their write-offs for this process (shown always) --%>
	<c:set var="hasReserves" value="false"/>
	<c:forEach var="m" items="${frd.movementList}">
		<c:if test="${m.type eq 'reserve' or m.type eq 'writeoff' or m.type eq 'receipt'}"><c:set var="hasReserves" value="true"/></c:if>
	</c:forEach>
	<c:if test="${hasReserves}">
		<table class="data mt05">
			<tr>
				<td width="100%">${l.l('Наименование')}</td>
				<td class="nowrap">${l.l('Количество')}</td>
				<td class="nowrap">${l.l('Статус')}</td>
				<td class="nowrap">${l.l('Дата')}</td>
				<c:if test="${not frd.readOnly}"><td>&nbsp;</td></c:if>
			</tr>
			<c:forEach var="m" items="${frd.movementList}">
				<c:if test="${m.type eq 'reserve' or m.type eq 'writeoff' or m.type eq 'receipt'}">
					<tr>
						<td>${m.itemTitle}</td>
						<td>${m.quantity}</td>
						<td class="nowrap">
							<c:choose>
								<c:when test="${m.type eq 'writeoff'}"><span class="color-gray">${l.l('Списано')}</span></c:when>
								<c:when test="${m.type eq 'receipt'}"><span class="color-green">${l.l('Возврат на склад')}</span></c:when>
								<c:otherwise>${l.l('В резерве')}</c:otherwise>
							</c:choose>
						</td>
						<td class="nowrap">${tu.format(m.dt, 'ymdhms')}</td>
						<c:if test="${not frd.readOnly}">
							<td>
								<c:if test="${m.type eq 'reserve'}">
									<c:url var="unreserveUrl" value="/user/plugin/inventory/movement.do">
										<c:param name="method" value="unreserve"/>
										<c:param name="movementId" value="${m.id}"/>
									</c:url>
									<ui:button type="del" onclick="$$.ajax.post('${unreserveUrl}', {control: this}).done(() => $$.ajax.load('${form.requestUrl}', $('#${uiid}').parent(), {control: this}))"/>
								</c:if>
							</td>
						</c:if>
					</tr>
				</c:if>
			</c:forEach>
		</table>
	</c:if>

	<%-- Add form: hidden when read-only (process already in writeoff status) --%>
	<c:if test="${not frd.readOnly}">
		<p:check action="/user/plugin/inventory/movement:recordMultiple">
			<form method="POST" action="/user/plugin/inventory/movement.do">
				<input type="hidden" name="method" value="recordMultiple"/>
				<input type="hidden" name="processId" value="${form.param.processId}"/>

				<%-- Store select --%>
				<div class="mt05 mb05">
					<span class="label">${l.l('Склад')} *</span>
					<ui:combo-single name="storeId" value="${frd.selectedStoreId}" style="width: 100%;"
						styleClass="mt025" showFilter="true" onSelect="invBalShow${uiid}()">
						<jsp:attribute name="valuesHtml">
							<li value=""></li>
							<c:forEach var="s" items="${frd.storeList}">
								<li value="${s.id}">${s.title}</li>
							</c:forEach>
						</jsp:attribute>
					</ui:combo-single>
				</div>

				<%-- Listcount-style add table --%>
				<table id="tbl${uiid}" class="data mt05">
					<tr>
						<td width="100%">${l.l('Наименование')}</td>
						<td>${l.l('Количество')}</td>
						<td>&nbsp;</td>
					</tr>
					<%-- add row (always last) --%>
					<tr>
						<td>
							<ui:select-single list="${frd.itemSelectList}" name="newItemId"
								onSelect="this.form.newItemTitle.value = $text.val(); invBalShow${uiid}($hidden.val())"
								styleClass="w100p"/>
							<input type="hidden" name="newItemTitle"/>
							<div id="invbal${uiid}" class="hint mt025" style="display:none;font-size:.85em"></div>
						</td>
						<td>
							<input name="newItemCount" size="4"
								onkeydown="if (enterPressed(event)) { invAddRow${uiid}() }; return isNumberKey(event)"
								title="${l.l('Use dot as a decimal separator')}. ${l.l('Press Enter to add a value')}."/>
						</td>
						<td>
							<ui:button type="add" onclick="invAddRow${uiid}()"/>
						</td>
					</tr>
				</table>

				<button type="button" class="btn-green mt05"
					onclick="var _sid=$('#${uiid} [name=storeId]').val(); $$.ajax.post(this).done((r) => {
						if (r.data.error) { alert(r.data.error); return; }
						$$.ajax.load('${form.requestUrl}&storeId='+_sid, $('#${uiid}').parent(), {control: this});
					})">
					${l.l('Сохранить')}
				</button>
			</form>
		</p:check>
	</c:if>
</div>
