// GET: Storage/AllocatedProducts/Edit/5
        public ActionResult Edit(Guid?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            AllocatedProduct allocatedProduct = db.AllocatedProducts.Find(id);

            if (allocatedProduct == null)
            {
                return(HttpNotFound());
            }

            var alProduct       = db.AllocatedProducts.Include(p => p.ImportedProduct).Include(o => o.OrderItem.Order.Customer).Where(p => p.Id == id).FirstOrDefault();
            var importedProduct = db.ImportedProducts.Include(p => p.Product).Include("AllocatedProducts.OrderItem.Order.Customer").Where(ip => ip.Id.Equals(allocatedProduct.ImportedProductId)).FirstOrDefault();
            var dto             = new AllocationDTO
            {
                Id                = alProduct.Id,
                Amount            = alProduct.Amount,
                AllocatingDate    = alProduct.Date,
                ProductionDate    = alProduct.ImportedProduct.Date,
                CustomerName      = alProduct.OrderItem.Order.Customer.Name,
                ImportedProductId = allocatedProduct.ImportedProductId,
                OrderItemId       = allocatedProduct.OrderItemId
            };

            ViewBag.OrderItemId = alProduct.OrderItemId;
            //ViewBag.ImportedProductId = new SelectList(db.ImportedProducts, "Id", "Date", allocatedProduct.ImportedProductId);
            //ViewBag.OrderItemId = new SelectList(db.OrderItems, "Id", "Comments", allocatedProduct.OrderItemId);
            return(View(dto));
        }
        public ActionResult DeleteConfirmed(Guid id)
        {
            AllocatedProduct allocatedProduct = db.AllocatedProducts.Find(id);

            db.AllocatedProducts.Remove(allocatedProduct);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
        // GET: Storage/AllocatedProducts/Delete/5
        public ActionResult Delete(Guid?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            AllocatedProduct allocatedProduct = db.AllocatedProducts.Find(id);

            if (allocatedProduct == null)
            {
                return(HttpNotFound());
            }
            return(View(allocatedProduct));
        }
        public ActionResult Create([Bind(Include = "Id,ImportedProductId,OrderItemId,Amount,Date")] AllocatedProduct allocatedProduct)
        {
            if (ModelState.IsValid)
            {
                allocatedProduct.Id = Guid.NewGuid();
                db.AllocatedProducts.Add(allocatedProduct);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.ImportedProductId = new SelectList(db.ImportedProducts, "Id", "Date", allocatedProduct.ImportedProductId);
            ViewBag.OrderItemId       = new SelectList(db.OrderItems, "Id", "Comments", allocatedProduct.OrderItemId);
            return(View(allocatedProduct));
        }
        public ActionResult Allocate(AllocatedProduct allocatedProduct)
        {
            var unAllocatedAmount = db.OrderItems.Include(o => o.AllocatedProducts).Where(p => p.Id == allocatedProduct.OrderItemId).FirstOrDefault().UnAllocatedAmount;

            if (unAllocatedAmount < allocatedProduct.Amount)
            {
                ModelState.AddModelError("Amount", "مقدار تخصیص بیشتر از مقدار سفارش است");
            }
            var availableAmount = db.ImportedProducts.Include(i => i.AllocatedProducts).Where(p => p.Id == allocatedProduct.ImportedProductId).FirstOrDefault().AmountUnAllocated;

            if (availableAmount < allocatedProduct.Amount)
            {
                ModelState.AddModelError("Amount", "مقدار تخصیص بیشتر از مقدار موجود است");
            }
            if (ModelState.IsValid)
            {
                allocatedProduct.Id = Guid.NewGuid();
                db.AllocatedProducts.Add(allocatedProduct);
                db.SaveChanges();
                return(RedirectToAction("Index", new { controller = "ImportedProducts" }));
            }

            var importedProduct             = db.ImportedProducts.Include(p => p.Product).Include("AllocatedProducts.OrderItem.Order.Customer").Where(ip => ip.Id.Equals(allocatedProduct.ImportedProductId)).FirstOrDefault();
            var relatedUnfinishedOrderItems = db.OrderItems.Include(o => o.Order.Customer).Include(or => or.Sendings).Include(or => or.AllocatedProducts).Where(o => o.ProductId.Equals(importedProduct.ProductId)).ToList();

            relatedUnfinishedOrderItems = relatedUnfinishedOrderItems.Where(p => p.IsProductionCompleted == false).ToList();
            ViewBag.RelatedAllocations  = importedProduct.AllocatedProducts
                                          .Select(p => new AllocationDTO {
                Id = p.Id, AllocatingDate = p.Date, Amount = p.Amount, CustomerName = p.OrderItem.Order.Customer.Name, ProductionDate = p.ImportedProduct.Date
            })
                                          .ToList();


            ViewBag.RelatedOrderItems = relatedUnfinishedOrderItems.Select(r => new SelectListItem
            {
                Text  = r.Order.Customer.Name + "    " + "،مقدار تخصیص یافته " + r.AllocatedAmount + "    " + "، مقدار تخصیص نیافته " + r.UnAllocatedAmount,
                Value = r.Id.ToString()
            });

            ViewBag.ImportedAmount    = importedProduct.AmountImported;
            ViewBag.AmountAllocated   = importedProduct.AmountAllocated;
            ViewBag.AmountUnAllocated = importedProduct.AmountUnAllocated;
            return(View());
        }
        public ActionResult Edit(AllocatedProduct allocatedProduct)
        {
            var    oldEntity  = db.AllocatedProducts.Where(p => p.Id == allocatedProduct.Id).FirstOrDefault();
            var    difference = oldEntity.Amount - allocatedProduct.Amount;
            double oldUnallocatedOrderAmount = db.OrderItems.Include(o => o.AllocatedProducts).Where(p => p.Id == allocatedProduct.OrderItemId).FirstOrDefault().UnAllocatedAmount;
            double unAllocatedOrderAmount;

            if (difference >= 0)
            {
                unAllocatedOrderAmount = oldUnallocatedOrderAmount + oldEntity.Amount;
            }
            else
            {
                unAllocatedOrderAmount = oldUnallocatedOrderAmount + difference;
            }

            if (unAllocatedOrderAmount < 0 || unAllocatedOrderAmount < allocatedProduct.Amount)
            {
                ModelState.AddModelError("Amount", "مقدار تخصیص بیشتر از مقدار سفارش است");
            }


            double availableAmount;

            //db.SaveChanges();
            if (difference >= 0)
            {
                availableAmount = db.ImportedProducts.Include(i => i.AllocatedProducts).Where(p => p.Id == allocatedProduct.ImportedProductId).FirstOrDefault().AmountUnAllocated + oldEntity.Amount;
            }
            else
            {
                availableAmount = db.ImportedProducts.Include(i => i.AllocatedProducts).Where(p => p.Id == allocatedProduct.ImportedProductId).FirstOrDefault().AmountUnAllocated + difference;
            }


            if (availableAmount < 0 || availableAmount < allocatedProduct.Amount)
            {
                ModelState.AddModelError("Amount", "مقدار تخصیص بیشتر از مقدار موجود است");
            }

            if (ModelState.IsValid)
            {
                oldEntity.Amount          = allocatedProduct.Amount;
                oldEntity.Date            = allocatedProduct.Date;
                db.Entry(oldEntity).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Allocate", new { controller = "AllocatedProducts", importedProductId = allocatedProduct.ImportedProductId }));
            }
            var customer = db.OrderItems.Include(o => o.Order.Customer).Where(p => p.Id == allocatedProduct.OrderItemId);

            ViewBag.ImportedProductId = new SelectList(db.ImportedProducts, "Id", "Date", allocatedProduct.ImportedProductId);
            //ViewBag.OrderItemId = new SelectList(db.OrderItems, "Id", "Comments", allocatedProduct.OrderItemId);
            var alProduct       = db.AllocatedProducts.Include(p => p.ImportedProduct).Include(o => o.OrderItem.Order.Customer).Where(p => p.Id == allocatedProduct.Id).FirstOrDefault();
            var importedProduct = db.ImportedProducts.Include(p => p.Product).Include("AllocatedProducts.OrderItem.Order.Customer").Where(ip => ip.Id.Equals(allocatedProduct.ImportedProductId)).FirstOrDefault();

            var dto = new AllocationDTO
            {
                Id                = allocatedProduct.Id,
                Amount            = allocatedProduct.Amount,
                AllocatingDate    = allocatedProduct.Date,
                ProductionDate    = importedProduct.Date,
                CustomerName      = alProduct.OrderItem.Order.Customer.Name,
                ImportedProductId = allocatedProduct.ImportedProductId,
                OrderItemId       = allocatedProduct.OrderItemId
            };

            return(View(dto));
        }