//форма заявки, если передан параметр idClaim, то загружается инфа по заявки с этим id
        public ActionResult Index(int? claimId, int? cv)
        {
            var user = GetUser();
            if (!UserHelper.IsController(user) && UserHelper.IsProductManager(user))
                return RedirectToAction("Index", "Calc", new {claimId = claimId, cv = cv});
            if (user == null || !UserHelper.IsUserAccess(user))
            {
                var dict = new RouteValueDictionary();
                dict.Add("message", "У Вас нет доступа к приложению");
                return RedirectToAction("ErrorPage", "Auth", dict);
            }

            if (claimId.HasValue && !cv.HasValue)
            {
                var verList = DbEngine.GetCalcVersionList(claimId.Value);
                if (verList.Any())
                {
                    int lastVersion = verList.Last();
                    return RedirectToAction("Index", new {claimId = claimId, cv = lastVersion});
                }
                else
                {
                    cv = 0;
                }
            }

            //получения текущего юзера и проверка наличия у него доступа к странице
            ViewBag.Error = false.ToString().ToLower();
            TempData["tenderClaimFileFormats"] = WebConfigurationManager.AppSettings["FileFormat4TenderClaimFile"];

            ViewBag.UserName = user.Name;
            var isController = UserHelper.IsController(user);
            var isManager = UserHelper.IsManager(user);
            var isOperator = UserHelper.IsOperator(user);
            if (!isController && !isManager && !isOperator)
            {
                var dict = new RouteValueDictionary();
                dict.Add("message", "У Вас нет доступа к этой странице");
                return RedirectToAction("ErrorPage", "Auth", dict);
            }
            try
            {
                //получение необходимой инфы из БД и ActiveDirectory
                var managers = UserHelper.GetManagers();
                ViewBag.Managers = managers;
                ViewBag.DateStart = DateTime.Now.ToString("dd.MM.yyyy");
                var db = new DbEngine();
                ViewBag.NextDateMin = DateTime.Now.DayOfWeek == DayOfWeek.Friday
                    ? DateTime.Now.AddDays(4).ToShortDateString()
                    : DateTime.Now.AddDays(2).ToShortDateString();
                ViewBag.DealTypes = db.LoadDealTypes();
                ViewBag.ClaimStatus = db.LoadClaimStatus();
                var adProductManagers = UserHelper.GetProductManagers();
                ViewBag.ProductManagers = adProductManagers;
                ViewBag.StatusHistory = new List<ClaimStatusHistory>();
                ViewBag.Facts = db.LoadProtectFacts();
                ViewBag.DeliveryTimes = db.LoadDeliveryTimes();
                ViewBag.HasTransmissedPosition = false.ToString().ToLower();
                ViewBag.Currencies = db.LoadCurrencies();
                TenderClaim claim = null;
                var dealTypeString = String.Empty;
                var tenderStatus = String.Empty;
                if (claimId.HasValue && cv.HasValue)
                {
                    claim = db.LoadTenderClaimById(claimId.Value);
                    if (claim != null)
                    {
                        var allPositions = db.LoadSpecificationPositionsForTenderClaim(claimId.Value, cv.Value);
                        var editablePosIds = new List<int>();
                        foreach (var position in allPositions)
                        {
                           if (position.State == 5) editablePosIds.Add(position.Id);
                        }
                        ViewBag.EditablePositions = editablePosIds;
                        ViewBag.HasTransmissedPosition = db.HasTenderClaimTransmissedPosition(claimId.Value, cv.Value).ToString().ToLower();
                        //проверка наличия доступа к данной заявке
                        if (!isController)
                        {
                            if (claim.Manager.Id == user.Id || claim.Author.Id == user.Id)
                            {

                            }
                            else if (isManager)
                            {
                                var subs = Employee.GetSubordinates(user.Id).ToList();
                                if (!Employee.UserIsSubordinate(subs, claim.Manager.Id) && !Employee.UserIsSubordinate(subs, claim.Author.Id))
                                {
                                    var dict = new RouteValueDictionary();
                                    dict.Add("message", "У Вас нет доступа к этой странице");
                                    return RedirectToAction("ErrorPage", "Auth", dict);
                                }
                            }
                        }

                        var managerFromAd = managers.FirstOrDefault(x => x.Id == claim.Manager.Id);
                        if (managerFromAd != null)
                        {
                            claim.Manager.Name = managerFromAd.Name;
                            claim.Manager.ShortName = managerFromAd.ShortName;
                            claim.Manager.ChiefShortName = managerFromAd.ChiefShortName;
                        }

                        var dealTypes = db.LoadDealTypes();
                        var dealType = dealTypes.FirstOrDefault(x => x.Id == claim.DealType);
                        if (dealType != null)
                        {
                            dealTypeString = dealType.Value;
                        }
                        var tenderStatusList = db.LoadTenderStatus();
                        var status = tenderStatusList.FirstOrDefault(x => x.Id == claim.TenderStatus);
                        if (status != null)
                        {
                            tenderStatus = status.Value;
                        }
                        //получение позиций по заявке и расчета к ним
                        claim.Certs = db.LoadClaimCerts(claimId.Value);
                        claim.Files = db.LoadTenderClaimFiles(claimId.Value);
                        claim.Positions = db.LoadSpecificationPositionsForTenderClaim(claimId.Value, cv.Value);
                        if (claim.Positions != null && claim.Positions.Any())
                        {
                            var productManagers = claim.Positions.Select(x => x.ProductManager).ToList();
                            foreach (var productManager in productManagers)
                            {
                                var productManagerFromAd =
                                    adProductManagers.FirstOrDefault(x => x.Id == productManager.Id);
                                if (productManagerFromAd != null)
                                {
                                    productManager.Name = productManagerFromAd.Name;
                                }
                            }
                            var calculations = db.LoadCalculateSpecificationPositionsForTenderClaim(claimId.Value, cv.Value);
                            if (calculations != null && calculations.Any())
                            {
                                foreach (var position in claim.Positions)
                                {
                                    if (position.State == 1) continue;
                                    position.Calculations =
                                        calculations.Where(x => x.IdSpecificationPosition == position.Id).ToList();
                                    position.Calculations.Reverse();
                                }
                            }
                        }
                        ViewBag.StatusHistory = db.LoadStatusHistoryForClaim(claimId.Value);
                    }
                }
                ViewBag.Claim = claim;
                ViewBag.DealType = dealTypeString;
                ViewBag.status = tenderStatus;
            }
            catch (Exception)
            {
                ViewBag.Error = true.ToString().ToLower();
            }
            return View();
        }
        //Страница расчета позиций по заявке
        public ActionResult Index(int? claimId, int? cv)
        {
            var user = GetUser();
            if (!UserHelper.IsController(user) && (UserHelper.IsManager(user) || UserHelper.IsOperator(user)))
                return RedirectToAction("Index", "Claim", new { claimId = claimId, cv = cv });

            //проверка наличия доступа к странице
            if (user == null || !UserHelper.IsUserAccess(user))
            {
                var dict = new RouteValueDictionary();
                dict.Add("message", "У Вас нет доступа к приложению");
                return RedirectToAction("ErrorPage", "Auth", dict);
            }

            if (claimId.HasValue && !cv.HasValue)
            {
                int lastVersion = DbEngine.GetCalcVersionList(claimId.Value).Last();
                return RedirectToAction("Index", new { claimId = claimId, cv = lastVersion });
            }

            ViewBag.UserName = user.Name;
            var isController = UserHelper.IsController(user);
            var isProduct = UserHelper.IsProductManager(user);
            if (!isController && !isProduct)
            {
                var dict = new RouteValueDictionary();
                dict.Add("message", "У Вас нет доступа к этой странице");
                return RedirectToAction("ErrorPage", "Auth", dict);
            }
            ViewBag.Error = false.ToString().ToLower();
            ViewBag.DealType = string.Empty;
            ViewBag.Status = string.Empty;
            ViewBag.StatusHistory = new List<ClaimStatusHistory>();
            var newClaim = true;
            if (!isController) newClaim = false;
            ViewBag.NewClaim = newClaim.ToString().ToLower();
            try
            {
                //получение инфы по заявке и сопутствующих справочников
                var db = new DbEngine();
                TenderClaim claim = null;
                var dealTypeString = string.Empty;
                var tenderStatus = string.Empty;
                ViewBag.ClaimStatus = db.LoadClaimStatus();
                ViewBag.Currencies = db.LoadCurrencies();
                ViewBag.DeliveryTimes = db.LoadDeliveryTimes();
                if (claimId.HasValue)
                {
                    claim = db.LoadTenderClaimById(claimId.Value);
                    claim.Certs = db.LoadClaimCerts(claimId.Value);
                    claim.Files = db.LoadTenderClaimFiles(claimId.Value);
                    var adProductsManager = UserHelper.GetProductManagers();
                    if (claim != null)
                    {
                        //if (claim.ClaimStatus == 1)
                        //{
                        //    var dict = new RouteValueDictionary();
                        //    dict.Add("message", "Статус заявки не позволяет производить расчет позиций");
                        //    return RedirectToAction("ErrorPage", "Auth", dict);
                        //}
                        //позиции заявки, в зависимости от роли юзера
                        if (!isController)
                        {
                            claim.Positions = db.LoadSpecificationPositionsForTenderClaimForProduct(claimId.Value,
                                user.Id, cv.Value);
                        }
                        else
                        {
                            claim.Positions = db.LoadSpecificationPositionsForTenderClaim(claimId.Value, cv.Value);
                        }
                        if (claim.Positions != null && claim.Positions.Any())
                        {
                            //изменение статуса  в Работе если это первая загрузка для расчета по данной заявке
                            if (claim.ClaimStatus == 2)
                            {
                                claim.ClaimStatus = 3;
                                DbEngine.ChangeTenderClaimClaimStatus(claim);
                                var statusHistory = new ClaimStatusHistory()
                                {
                                    IdClaim = claim.Id,
                                    Date = DateTime.Now,
                                    Comment = string.Empty,
                                    Status = new ClaimStatus() { Id = claim.ClaimStatus },
                                    IdUser = user.Id
                                };
                                db.SaveClaimStatusHistory(statusHistory);
                            }
                            //менеджеры и снабженцы из ActiveDirectory
                            var managerFromAd = UserHelper.GetUserById(claim.Manager.Id);
                            claim.Manager.Name = managerFromAd.Name;
                            claim.Manager.ShortName = managerFromAd.ShortName;
                            claim.Manager.ChiefShortName = managerFromAd.ManagerName;
                            //var managers = UserHelper.GetManagers();
                            //var managerFromAd = managers.FirstOrDefault(x => x.Id == claim.Manager.Id);
                            //if (managerFromAd != null)
                            //{
                            //    claim.Manager.Name = managerFromAd.Name;
                            //    claim.Manager.ShortName = managerFromAd.ShortName;
                            //    claim.Manager.ChiefShortName = managerFromAd.ChiefShortName;
                            //}

                            var subordinateList = Employee.GetSubordinates(user.Id);

                            var productManagers = claim.Positions.Select(x => x.ProductManager).ToList();
                            var prodManSelList = UserHelper.GetProductManagersSelectionList();
                            bool hasAccess = isController || claim.Positions.Any(x => x.ProductManager.Id == user.Id);

                            foreach (var productManager in productManagers)
                            {
                                hasAccess = hasAccess || (subordinateList.Any() && Employee.UserIsSubordinate(subordinateList, productManager.Id));// subordinateList.ToList().Contains(productManager.Id);
                                productManager.ShortName = prodManSelList.FirstOrDefault(x => x.Id == productManager.Id)?.ShortName;
                                //var productUser = UserHelper.GetUserById(productManager.Id);
                                //if (productUser != null)
                                //{
                                //    productManager.Name = productUser.Name;
                                //    productManager.ShortName = productUser.ShortName;
                                //}
                                //var productManagerFromAd = adProductsManager.First(x => x.Id == productManager.Id);
                                //if (productManagerFromAd != null)
                                //{
                                //    productManager.Name = productManagerFromAd.Name;
                                //    productManager.ShortName = productManagerFromAd.ShortName;
                                //}
                            }
                            if (!hasAccess)
                            {
                                var dict = new RouteValueDictionary();
                                dict.Add("message", "У Вас нет доступа к этой заявке, Вам не назначены позиции для расчета");
                                return RedirectToAction("ErrorPage", "Auth", dict);
                            }
                            //Расчет по позициям
                            var calculations = db.LoadCalculateSpecificationPositionsForTenderClaim(claimId.Value, cv.Value);
                            if (calculations != null && calculations.Any())
                            {
                                foreach (var position in claim.Positions)
                                {
                                    position.Calculations =
                                        calculations.Where(x => x.IdSpecificationPosition == position.Id).ToList();
                                    position.Calculations.Reverse();
                                }
                            }
                        }
                        else
                        {
                            if (isController)
                            {
                                var dict = new RouteValueDictionary();
                                dict.Add("message", "У заявки нет позиций");
                                return RedirectToAction("ErrorPage", "Auth", dict);
                            }
                            else
                            {
                                var dict = new RouteValueDictionary();
                                dict.Add("message", "У Вас нет доступа к этой заявке, Вам не назначены позиции для расчета");
                                return RedirectToAction("ErrorPage", "Auth", dict);
                            }
                        }
                        var dealTypes = db.LoadDealTypes();
                        var dealType = dealTypes.FirstOrDefault(x => x.Id == claim.DealType);
                        if (dealType != null)
                        {
                            dealTypeString = dealType.Value;
                        }
                        var tenderStatusList = db.LoadTenderStatus();
                        var status = tenderStatusList.FirstOrDefault(x => x.Id == claim.TenderStatus);
                        if (status != null)
                        {
                            tenderStatus = status.Value;
                        }
                        ViewBag.StatusHistory = db.LoadStatusHistoryForClaim(claimId.Value);
                        ViewBag.ProductManagers = adProductsManager;
                    }
                }
                ViewBag.Claim = claim;
                ViewBag.DealType = dealTypeString;
                ViewBag.Status = tenderStatus;
                ViewBag.ProtectFacts = db.LoadProtectFacts();
            }
            catch (Exception ex)
            {
                ViewBag.Error = true.ToString().ToLower();
            }
            return View();
        }