@using VetClinicContracts.ViewModels;

@{
	ViewData["Title"] = "MedicineAnimals";
}

<div class="text-center">
	<h2 class="display-4">Связывание медикамента и животного</h2>
</div>
<form method="post">
	<div class="row">
		<div class="col-4">Медикамент:</div>
		<div class="col-8">
			<select id="medicine" name="medicine" class="form-control" asp-items="@(new SelectList(@ViewBag.Medicines, "Id", "MedicineName"))"></select>
		</div>
	</div>
	<input style = "visibility: hidden" type="text" name="name" id="name" class="form-control" />
	<input style = "visibility: hidden" type="text" id="price" name="price" class="form-control" />
	<div class="row">
		<div class="col-4">Животные:</div>
		<div class="col-8">
			<select name="animals" class="form-control" multiple size="5" id="animals">
				@foreach (var animal in ViewBag.Animals)
				{
					<option value="@animal.Id" data-name="@animal.Id">@animal.AnimalName</option>
				}
			</select>
		</div>
	</div>
	<div class="row">
		<div class="col-8"></div>
		<div class="col-4"><input type="submit" value="Сохранить" class="btn btn-primary" /></div>
	</div>
</form>

@section Scripts
{
	<script>
		function check() {
			var medicine = $('#medicine').val();
			$("#animals option:selected").removeAttr("selected");
			if (medicine) {
				$.ajax({
					method: "GET",
					url: "/Home/GetMedicine",
					data: { medicineId: medicine },
					success: function (result) {
						console.log(result.item2);
						$('#name').val(result.item1.medicineName);
						$('#price').val(result.item1.price);
						$.map(result.item2, function (n) {
							console.log("#" + n);
							$(`option[data-name=${n.item2}]`).attr("selected", "selected")
						});
					}

				});
			};
		}
		check();
		$('#medicine').on('change', function () {
			check();
		});
	</script>
}