public ActionResult SwitchChecked(List <int> ids, int electiveId, int electiveOrgId, bool isChecked)
        {
            using (var db = new XkSystem.Models.DbContext())
            {
                var tb = (from p in db.Table <Entity.tbElectiveOrgStudent>()
                          .Include(d => d.tbElectiveOrg)
                          .Include(d => d.tbStudent)
                          where ids.Contains(p.Id)
                          select p).ToList();

                foreach (var a in tb)
                {
                    a.IsChecked = isChecked;

                    if (isChecked)
                    {
                        if (db.Table <Entity.tbElectiveData>().Where(d => d.tbElectiveOrg.Id == a.tbElectiveOrg.Id && d.tbStudent.Id == a.tbStudent.Id).Count() == 0)
                        {
                            var tbElectiveData = new Entity.tbElectiveData()
                            {
                                tbElectiveOrg = a.tbElectiveOrg,
                                tbStudent     = a.tbStudent,
                                IsPreElective = true,
                                IsFixed       = a.IsFixed,
                                InputDate     = DateTime.Now
                            };
                            db.Set <Entity.tbElectiveData>().Add(tbElectiveData);
                            a.tbElectiveOrg.RemainCount--;
                        }
                    }
                    else
                    {
                        var dataList = db.Table <Entity.tbElectiveData>().Where(d => d.tbElectiveOrg.Id == a.tbElectiveOrg.Id && d.tbStudent.Id == a.tbStudent.Id).ToList();
                        foreach (var data in dataList)
                        {
                            data.IsDeleted = true;
                            a.tbElectiveOrg.RemainCount++;
                        }
                    }
                }

                if (db.SaveChanges() > 0)
                {
                    XkSystem.Areas.Sys.Controllers.SysUserLogController.Insert("切换了预选学生是否选中!");
                }

                return(Code.MvcHelper.Post(null, Url.Action("List", new { electiveId = electiveId, electiveOrgId = electiveOrgId }), "操作成功!"));
            }
        }
        public ActionResult Edit(Models.ElectiveData.Edit vm)
        {
            using (var db = new XkSystem.Models.DbContext())
            {
                var error = new List <string>();
                if (error.Count == decimal.Zero)
                {
                    if (vm.ElectiveDataEdit.Id == 0)
                    {
                        var tb = new Entity.tbElectiveData()
                        {
                            IsFixed       = vm.ElectiveDataEdit.IsFixed,
                            IsPreElective = vm.ElectiveDataEdit.IsPreElective,
                            tbElectiveOrg = db.Set <Entity.tbElectiveOrg>().Find(vm.ElectiveDataEdit.ElectiveOrgId),
                            tbStudent     = db.Set <Student.Entity.tbStudent>().Find(Code.Common.UserId),
                        };
                        db.Set <Entity.tbElectiveData>().Add(tb);
                        if (db.SaveChanges() > 0)
                        {
                            XkSystem.Areas.Sys.Controllers.SysUserLogController.Insert("添加了选课数据");
                        }
                    }
                    else
                    {
                        //var tb = (from p in db.Table<Entity.tbElectiveData>()
                        //          where p.Id == vm.ElectiveDataEdit.Id
                        //          select p).FirstOrDefault();
                        //if (tb != null)
                        //{
                        //    if (db.SaveChanges() > 0)
                        //    {
                        //        XkSystem.Areas.Sys.Controllers.SysUserLogController.Insert("修改了选课数据");
                        //    }
                        //}
                        //else
                        //{
                        //    error.AddError(Resources.LocalizedText.MsgNotFound);
                        //}
                    }
                }

                return(Code.MvcHelper.Post(error));
            }
        }
Exemple #3
0
        public ActionResult Select(Models.ElectiveOrg.Select vm)
        {
            using (var db = new XkSystem.Models.DbContext())
            {
                var error = new List <string>();
                var ids   = Request.Form["rdoId"];
                if (string.IsNullOrWhiteSpace(ids))
                {
                    error.AddError("请选择一项再提交!");
                    return(Code.MvcHelper.Post(error));
                }
                var success   = false;
                var idArray   = ids.Split(',').Select(int.Parse).ToArray();
                var newOrgId  = idArray[0];
                var oldOrgId  = idArray[1];
                var studentId = idArray[2];
                do
                {
                    try
                    {
                        //var newElectiveOrg = (from p in db.Table<Entity.tbElectiveOrg>().Include(p=>p.tbElective.tbElectiveType) where p.Id==newOrgId select p).FirstOrDefault();

                        var newElectiveOrg = db.Set <Entity.tbElectiveOrg>().Find(newOrgId);
                        if (newElectiveOrg == null || newElectiveOrg.RemainCount == 0)
                        {
                            error.AddError("班级人数已满");
                            return(Code.MvcHelper.Post(error));
                        }

                        var electiveOrgCourseId = (from p in db.Table <Entity.tbElectiveOrg>()
                                                   where p.Id == newOrgId
                                                   select p.tbCourse.Id).FirstOrDefault();
                        var checkCourse = (from p in db.Table <Entity.tbElectiveData>()
                                           where p.tbElectiveOrg.Id != newOrgId &&
                                           p.tbElectiveOrg.IsDeleted == false &&
                                           p.tbStudent.tbSysUser.Id == Code.Common.UserId &&
                                           p.tbElectiveOrg.tbCourse.Id == electiveOrgCourseId &&
                                           p.tbElectiveOrg.tbElective.Id == vm.ElectiveId
                                           select 1).Count();
                        if (checkCourse > 0)
                        {
                            error.AddError("已选择该课程的另外节次,同一课程无法重复选择!");
                            return(Code.MvcHelper.Post(error));
                        }


                        #region 判断新课程的人数限制

                        //当前选择的课程所属分段
                        var electiveOrgInfo = (from p in db.Table <Entity.tbElectiveOrg>() where p.Id == newOrgId
                                               select new
                        {
                            tbElectiveSection = p.tbElectiveSection,
                            tbElectiveGroup = p.tbElectiveGroup
                        }).FirstOrDefault();

                        var electiveSection = electiveOrgInfo.tbElectiveSection;
                        //当前选择课程所属分段下已选课程数
                        var exNum = (from p in db.Table <Entity.tbElectiveData>()
                                     where p.tbElectiveOrg.tbElectiveSection.Id == electiveSection.Id && p.tbStudent.tbSysUser.Id == Code.Common.UserId
                                     select p).Count();

                        if (exNum + 1 > electiveSection.MaxElective)
                        {
                            error.AddError($"已选人数[{exNum + 1}]超出分段[{electiveSection.ElectiveSectionName}]的最大人数[{electiveSection.MaxElective}]");
                            return(Code.MvcHelper.Post(error));
                        }

                        //当前选择的课程所属分组
                        var electiveGroup = electiveOrgInfo.tbElectiveGroup;
                        //当前选择课程所属分组下已选课程数
                        var existsGroupNum = (from p in db.Table <Entity.tbElectiveData>()
                                              where p.tbElectiveOrg.tbElectiveGroup.Id == electiveGroup.Id && p.tbStudent.tbSysUser.Id == Code.Common.UserId
                                              select p).Count();

                        if (exNum + 1 > electiveGroup.MaxElective)
                        {
                            error.AddError($"已选人数[{exNum + 1}]超出分组[{electiveGroup.ElectiveGroupName}]的最大人数[{electiveGroup.MaxElective}]");
                            return(Code.MvcHelper.Post(error));
                        }

                        #endregion


                        //删除旧数据
                        var oldElectiveData = (from p in db.Set <Entity.tbElectiveData>()
                                               where p.IsDeleted == false && p.tbElectiveOrg.Id == oldOrgId && p.tbStudent.Id == studentId
                                               select new
                        {
                            p,
                            p.tbStudent,
                            p.tbElectiveOrg
                        }).FirstOrDefault();
                        oldElectiveData.p.IsDeleted = true;
                        oldElectiveData.tbElectiveOrg.RemainCount++;

                        if (oldElectiveData.p.IsPreElective)
                        {
                            var tbElectiveOrgStudent = (from p in db.Set <Entity.tbElectiveOrgStudent>()
                                                        where p.tbElectiveOrg.Id == oldElectiveData.p.Id && p.tbStudent.Id == oldElectiveData.tbStudent.Id && p.IsDeleted == false
                                                        select p).FirstOrDefault();
                            if (tbElectiveOrgStudent != null)
                            {
                                tbElectiveOrgStudent.IsDeleted = true;
                            }
                        }

                        var electiveData = new Entity.tbElectiveData()
                        {
                            //IsPreElective = true,
                            tbElectiveOrg = newElectiveOrg,
                            tbStudent     = db.Set <Student.Entity.tbStudent>().Find(oldElectiveData.tbStudent.Id),
                            InputDate     = DateTime.Now
                        };
                        //添加新数据
                        db.Set <Entity.tbElectiveData>().Add(electiveData);

                        db.Set <Entity.tbElectiveOrgStudent>().Add(new Entity.tbElectiveOrgStudent()
                        {
                            tbElectiveOrg = newElectiveOrg,
                            tbStudent     = electiveData.tbStudent,
                        });
                        newElectiveOrg.RemainCount--;
                        db.SaveChanges();
                        success = true;
                    }
                    catch (DbUpdateConcurrencyException exception)
                    {
                        exception.Entries.Single().Reload();
                    }
                } while (!success);
                return(Code.MvcHelper.Post());
            }
        }
        public static string SaveToElectiveData(XkSystem.Models.DbContext db, int electiveId)
        {
            //预选记录
            var dataList = (from p in db.Table <Entity.tbElectiveData>()
                            .Include(d => d.tbElectiveOrg)
                            .Include(d => d.tbStudent)
                            where p.tbElectiveOrg.tbElective.Id == electiveId &&
                            p.IsPreElective == true
                            select p).ToList();

            var orgStudent = (from p in db.Table <Entity.tbElectiveOrgStudent>()
                              .Include(d => d.tbElectiveOrg)
                              .Include(d => d.tbStudent)
                              where p.tbElectiveOrg.tbElective.Id == electiveId && p.IsDeleted == false
                              select p).ToList();

            //删除已经不在此次导入预选学生列表的选课记录
            foreach (var a in dataList.Where(d => orgStudent.Where(o => o.tbElectiveOrg.Id == d.tbElectiveOrg.Id && o.tbStudent.Id == d.tbStudent.Id).Count() == 0))
            {
                a.IsDeleted = true;
            }

            //修改在预选学生名单的选课记录
            foreach (var a in dataList.Where(d => orgStudent.Where(o => o.tbElectiveOrg.Id == d.tbElectiveOrg.Id && o.tbStudent.Id == d.tbStudent.Id).Count() > 0))
            {
                a.IsPreElective = a.IsPreElective;
                a.IsFixed       = orgStudent.Where(d => d.tbElectiveOrg.Id == a.tbElectiveOrg.Id && d.tbStudent.Id == d.tbStudent.Id).FirstOrDefault().IsFixed;
            }

            //增加没有添加记录的预选学生名单
            var list = new List <Entity.tbElectiveData>();

            foreach (var a in orgStudent.Where(d => dataList.Where(o => o.tbElectiveOrg.Id == d.tbElectiveOrg.Id && o.tbStudent.Id == d.tbStudent.Id).Count() == 0))
            {
                var data = new Entity.tbElectiveData();
                data.tbElectiveOrg = a.tbElectiveOrg;
                data.tbStudent     = a.tbStudent;
                data.IsPreElective = true;
                data.IsFixed       = a.IsFixed;
                data.InputDate     = DateTime.Now;
                list.Add(data);
            }
            db.Set <Entity.tbElectiveData>().AddRange(list);

            db.SaveChanges();

            //重新计算剩余名额
            var dataCountList = (from p in db.Table <Entity.tbElectiveData>()
                                 where p.tbElectiveOrg.tbElective.Id == electiveId &&
                                 p.tbStudent.IsDeleted == false
                                 group p by p.tbElectiveOrg.Id into g
                                 select new
            {
                OrgId = g.Key,
                iCount = g.Count()
            }).ToList();

            var tb = (from p in db.Table <Entity.tbElectiveOrg>()
                      where p.tbElective.Id == electiveId
                      select p).ToList();

            foreach (var a in tb)
            {
                a.RemainCount = a.MaxCount - dataCountList.Where(d => d.OrgId == a.Id).Select(d => d.iCount).DefaultIfEmpty().FirstOrDefault();
            }

            db.SaveChanges();

            return(string.Empty);
        }
        public ActionResult Import(Models.ElectiveOrgStudent.Import vm)
        {
            using (var db = new XkSystem.Models.DbContext())
            {
                var file     = Request.Files[nameof(vm.UploadFile)];
                var fileSave = System.IO.Path.GetTempFileName();
                file.SaveAs(fileSave);

                var ExList = new List <string>()
                {
                    ".xlsx"
                };
                if (!ExList.Contains(System.IO.Path.GetExtension(file.FileName)))
                {
                    ModelState.AddModelError(string.Empty, "上传的文件不是正确的excel文件!");
                    return(View(vm));
                }
                else
                {
                    var dt = Code.NpoiHelper.ExcelToDataTable(fileSave, System.IO.Path.GetExtension(file.FileName), string.Empty);
                    if (dt == null)
                    {
                        ModelState.AddModelError(string.Empty, "无法读取上传的文件,请检查文件格式是否正确!");
                        return(View(vm));
                    }
                    else
                    {
                        var tbList = new List <string>()
                        {
                            "选课班级", "学号", "姓名", "允许学生修改", "默认选中"
                        };
                        foreach (var name in tbList)
                        {
                            var text = string.Empty;
                            text += !dt.Columns.Contains(name) ? name + "," : "";
                            if (!string.IsNullOrWhiteSpace(text))
                            {
                                ModelState.AddModelError(string.Empty, "上传的excel文件内容与预期不一致!错误详细:" + text);
                                return(View(vm));
                            }
                        }

                        var electiveOrgList = (from p in db.Table <Entity.tbElectiveOrg>()
                                               .Include(d => d.tbElective)
                                               where p.tbElective.Id == vm.ElectiveId &&
                                               p.tbCourse.IsDeleted == false &&
                                               p.tbElectiveGroup.IsDeleted == false &&
                                               p.tbElectiveSection.IsDeleted == false
                                               select p).ToList();

                        var studentList = (from p in db.Table <Student.Entity.tbStudent>()
                                           join s in db.Table <Basis.Entity.tbClassStudent>()
                                           on p.Id equals s.tbStudent.Id
                                           select new
                        {
                            p.StudentCode,
                            p.StudentName,
                            StudentId = p.Id,
                            ClassId = s.tbClass.Id
                        }).ToList();

                        var electiveClassIds = db.Set <Entity.tbElectiveClass>().Where(p => p.tbElective.Id == vm.ElectiveId && p.IsDeleted == false).Select(p => p.tbClass.Id).ToList();

                        for (var i = 0; i < dt.Rows.Count; i++)
                        {
                            var dr     = dt.Rows[i];
                            var import = new Dto.ElectiveOrgStudent.Import()
                            {
                                OrgName     = dr["选课班级"].ToString().Trim(),
                                StudentCode = dr["学号"].ToString().Trim(),
                                StudentName = dr["姓名"].ToString().Trim(),
                                IsFixed     = dr["允许学生修改"].ToString().Trim(),
                                IsChecked   = dr["默认选中"].ToString().Trim()
                            };

                            if (string.IsNullOrEmpty(import.OrgName))
                            {
                                import.Error += "选课班级不能为空!";
                            }

                            if (string.IsNullOrEmpty(import.StudentCode))
                            {
                                import.Error += "学号不能为空!";
                            }

                            if (string.IsNullOrEmpty(import.StudentName))
                            {
                                import.Error += "姓名不能为空!";
                            }

                            var student = studentList.Where(p => p.StudentCode == import.StudentCode).FirstOrDefault();
                            if (student == null)
                            {
                                import.Error += "学号不存在,或者学生尚未加入班级!";
                            }
                            else if (student.StudentName != import.StudentName)
                            {
                                import.Error += "学号与姓名不匹配!";
                            }

                            if (string.IsNullOrEmpty(import.IsFixed))
                            {
                                import.Error += "允许学生修改不能为空!";
                            }
                            else
                            {
                                if ((new string[] { "是", "否" }).Contains(import.IsFixed) == false)
                                {
                                    import.Error += "允许学生修改只能填写是或否!";
                                }
                            }

                            if (string.IsNullOrEmpty(import.IsChecked))
                            {
                                import.Error += "默认选中不能为空!";
                            }
                            else
                            {
                                if ((new string[] { "是", "否" }).Contains(import.IsChecked) == false)
                                {
                                    import.Error += "默认选中只能填写是或否!";
                                }
                            }

                            if (!electiveOrgList.Any(p => p.OrgName == import.OrgName))
                            {
                                import.Error += "找不到对应的选课班级!";
                            }

                            if (student != null)
                            {
                                var count = db.Table <Entity.tbElectiveData>().Where(p => p.tbElectiveOrg.OrgName == import.OrgName && p.tbElectiveOrg.IsDeleted == false && p.tbElectiveOrg.tbElective.Id == vm.ElectiveId && p.tbStudent.Id == student.StudentId).Count();
                                if (count > 0)
                                {
                                    import.Error += "系统已存在该学生的选课记录!";
                                }


                                var classLimit = db.Table <Entity.tbElectiveOrgClass>().Where(p => p.tbElectiveOrg.OrgName == import.OrgName && p.tbElectiveOrg.IsDeleted == false && p.tbElectiveOrg.tbElective.Id == vm.ElectiveId).Select(p => p.tbClass.Id).ToList();
                                if (classLimit != null && !classLimit.Contains(student.ClassId))
                                {
                                    import.Error += "学生所在班级被限制预选该课程!";
                                }

                                if (electiveClassIds != null && !electiveClassIds.Contains(student.ClassId))
                                {
                                    import.Error += "学生所在班级不能预选该课程!";
                                }
                            }
                            vm.ImportList.Add(import);
                        }

                        vm.ImportList.RemoveAll(p => string.IsNullOrEmpty(p.OrgName + p.StudentCode + p.StudentName + p.IsFixed));


                        if (vm.ImportList.GroupBy(p => new { p.StudentCode, p.OrgName }).Select(p => p.Count()).First() > 1)
                        {
                            vm.ImportList.ForEach(p =>
                            {
                                vm.ImportList.ForEach(p1 => p1.Error += p1.StudentCode + "|" + p1.OrgName == p.StudentCode + "|" + p.OrgName ? "该条数据重复!" : "");
                            });
                        }

                        if (vm.ImportList.Count(p => string.IsNullOrEmpty(p.Error) == false) > 0)
                        {
                            vm.ImportList.RemoveAll(p => string.IsNullOrEmpty(p.Error));
                            return(View(vm));
                        }



                        var limitElectiveOrgList = (from p in db.Table <Entity.tbElectiveOrgClass>().Include(p => p.tbClass).Include(p => p.tbElectiveOrg)
                                                    where p.tbElectiveOrg.tbElective.Id == vm.ElectiveId &&
                                                    p.tbElectiveOrg.IsDeleted == false
                                                    select p).ToList();

                        /*
                         * foreach (var item in studentCountByClass)
                         * {
                         *  if (limitOrgList.Exists(p => p.tbClass.Id == item.ClassId && p.RemainCount < item.StudentCount))
                         *  {
                         *      error.AddError($"针对当前行政班级{item.ClassName}的人数限制不足!");
                         *      return Code.MvcHelper.Post(error);
                         *  }
                         * }
                         */

                        vm.ImportList.ForEach(p => {
                            p.ClassId = studentList.Where(s => s.StudentCode.Equals(p.StudentCode)).Select(s => s.ClassId).FirstOrDefault();
                        });

                        foreach (var org in vm.ImportList)
                        {
                            var electiveOrg = electiveOrgList.Where(p => p.OrgName.Equals(org.OrgName) && p.tbElective.Id == vm.ElectiveId && p.IsDeleted == false)
                                              .Select(p => new
                            {
                                p.MaxCount,
                                p.RemainCount
                            }).FirstOrDefault();

                            //本次excel导入数据中选择同一班级的人数
                            var studentCount = vm.ImportList.Count(p => p.OrgName.Equals(org.OrgName) && p.IsChecked == "是");
                            if (studentCount > electiveOrg.RemainCount)
                            {
                                org.Error += "课程剩余人数不足!";
                            }

                            //判断选课班级对学生当前班级有没有限制
                            var limitInfo = (from p in limitElectiveOrgList where p.tbElectiveOrg.OrgName.Equals(org.OrgName) && p.tbClass.Id == org.ClassId select p).FirstOrDefault();
                            if (limitInfo != null)
                            {
                                var classStudentCount = vm.ImportList.Count(p => p.ClassId == org.ClassId);
                                //判断选课班级对当前学生所在班级的限制人数
                                if (classStudentCount > limitInfo.RemainCount)
                                {
                                    org.Error += "针对当前行政班级的人数限制不足!";
                                }
                            }
                        }

                        if (vm.ImportList.Count(p => string.IsNullOrEmpty(p.Error) == false) > 0)
                        {
                            vm.ImportList.RemoveAll(p => string.IsNullOrEmpty(p.Error));
                            return(View(vm));
                        }

                        //分组分段

                        foreach (var item in vm.ImportList)
                        {
                            var tbElectiveOrg = electiveOrgList.Where(d => d.OrgName == item.OrgName).FirstOrDefault();
                            var tb            = new Entity.tbElectiveOrgStudent
                            {
                                tbElectiveOrg = tbElectiveOrg,
                                tbStudent     = db.Set <Student.Entity.tbStudent>().Find(studentList.Where(p => p.StudentCode == item.StudentCode && p.StudentName == item.StudentName).First().StudentId),
                                IsFixed       = item.IsFixed == "是" ? false : true,
                                IsChecked     = item.IsChecked == "是" ? true : false
                            };

                            db.Set <Entity.tbElectiveOrgStudent>().Add(tb);

                            if (item.IsChecked == "是")
                            {
                                var tbElectiveData = new Entity.tbElectiveData()
                                {
                                    tbElectiveOrg = tb.tbElectiveOrg,
                                    tbStudent     = tb.tbStudent,
                                    IsPreElective = true,
                                    IsFixed       = tb.IsFixed,
                                    InputDate     = DateTime.Now
                                };
                                db.Set <Entity.tbElectiveData>().Add(tbElectiveData);
                                tbElectiveOrg.RemainCount--;

                                //更新行政班剩余人数
                                var limit = (from p in limitElectiveOrgList where p.tbElectiveOrg.Id == tbElectiveOrg.Id && p.tbClass.Id == item.ClassId select p).FirstOrDefault();
                                if (limit != null)
                                {
                                    limit.RemainCount--;
                                }
                            }
                        }

                        if (db.SaveChanges() > 0)
                        {
                            XkSystem.Areas.Sys.Controllers.SysUserLogController.Insert("导入了预选学生!");
                            vm.ImportList.RemoveAll(p => string.IsNullOrEmpty(p.Error));
                            vm.Status = true;
                        }
                    }
                }
            }

            return(View(vm));
        }
        public ActionResult Insert(List <int> ids, int orgId, int electiveId)
        {
            using (var db = new XkSystem.Models.DbContext())
            {
                var error = new List <string>();
                var electiveClassIdList = db.Table <Entity.tbElectiveClass>().Where(p => p.tbElective.Id == electiveId && p.IsDeleted == false).Select(p => p.tbClass.Id).ToList();

                if (electiveClassIdList != null && !electiveClassIdList.Any())
                {
                    error.AddError("当前选课设置不完整,尚未设置适用班级!");
                    return(Code.MvcHelper.Post(error));
                }

                //已预选学生列表
                var orgStudentList = (from p in db.Table <Entity.tbElectiveOrgStudent>()
                                      where p.tbElectiveOrg.Id == orgId
                                      select p.tbStudent.Id).ToList();

                var studentList = (from p in db.Table <Student.Entity.tbStudent>()
                                   join c in db.Table <Basis.Entity.tbClassStudent>() on p.Id equals c.tbStudent.Id
                                   where ids.Contains(p.Id) && orgStudentList.Contains(p.Id) == false
                                   select new {
                    tbStudent = p,
                    tbClass = c.tbClass
                }).ToList();

                //移除班级不符合条件的学生
                //studentList.RemoveAll(p => !db.Table<Basis.Entity.tbClassStudent>().Where(c => c.IsDeleted == false && electiveClassIdList.Contains(c.tbClass.Id)).Select(c => c.tbStudent.Id).Contains(p.tbStudent.Id));
                studentList.RemoveAll(p => !electiveClassIdList.Contains(p.tbClass.Id));

                //移除已经选过该课程的学生
                studentList.RemoveAll(p => db.Table <Entity.tbElectiveData>().Any(e => e.tbStudent.Id == p.tbStudent.Id && e.tbElectiveOrg.Id == orgId && e.IsDeleted == false));

                if (!studentList.Any())
                {
                    error.AddError("所选学生列表中有数据不符合当前选课的要求!");
                    return(Code.MvcHelper.Post(error));
                }

                var electiveOrg = db.Set <Entity.tbElectiveOrg>().Where(p => p.Id == orgId && p.IsDeleted == false).FirstOrDefault();
                if (electiveOrg.RemainCount < studentList.Count)
                {
                    error.AddError("课程剩余人数不足!");
                    return(Code.MvcHelper.Post(error));
                }


                var studentCountByClass = (from p in studentList
                                           group p by new { p.tbClass.Id, p.tbClass.ClassName } into g
                                           select new
                {
                    ClassId = g.Key.Id,
                    ClassName = g.Key.ClassName,
                    StudentCount = g.Count()
                });

                var limitOrgList = (from p in db.Table <Entity.tbElectiveOrgClass>().Include(p => p.tbClass).Include(p => p.tbElectiveOrg)
                                    where p.tbElectiveOrg.Id == orgId &&
                                    p.tbElectiveOrg.IsDeleted == false
                                    select p).ToList();

                foreach (var item in studentCountByClass)
                {
                    if (limitOrgList.Exists(p => p.tbClass.Id == item.ClassId && p.RemainCount < item.StudentCount))
                    {
                        error.AddError($"针对当前行政班级{item.ClassName}的人数限制不足!");
                        return(Code.MvcHelper.Post(error));
                    }
                }


                foreach (var student in studentList)
                {
                    var tb = new Entity.tbElectiveOrgStudent()
                    {
                        tbElectiveOrg = db.Set <Entity.tbElectiveOrg>().Find(orgId),
                        tbStudent     = student.tbStudent,
                        IsFixed       = true,
                        IsChecked     = true,
                    };
                    db.Set <Entity.tbElectiveOrgStudent>().Add(tb);

                    var tbElectiveData = new Entity.tbElectiveData()
                    {
                        tbElectiveOrg = tb.tbElectiveOrg,
                        tbStudent     = tb.tbStudent,
                        IsPreElective = true,
                        IsFixed       = tb.IsFixed,
                        InputDate     = DateTime.Now
                    };
                    db.Set <Entity.tbElectiveData>().Add(tbElectiveData);

                    //预选,减少对应的选课行政班人数
                    var limitClass = limitOrgList.Where(p => p.tbElectiveOrg.Id == orgId && p.tbClass.Id == student.tbClass.Id).FirstOrDefault();
                    if (limitClass != null)
                    {
                        limitClass.RemainCount--;
                    }
                }
                electiveOrg.RemainCount -= studentList.Count;

                if (db.SaveChanges() > 0)
                {
                    XkSystem.Areas.Sys.Controllers.SysUserLogController.Insert("添加了选课预选学生!");
                }
                return(Code.MvcHelper.Post(error));
            }
        }
        private static string Save(XkSystem.Models.DbContext db, int electiveId, List <int> orgIds)
        {
            try
            {
                var elective = (from p in db.Table <Entity.tbElective>()
                                where p.Id == electiveId
                                select new
                {
                    p.FromDate,
                    p.ToDate,
                    p.tbElectiveType.ElectiveTypeCode
                }).FirstOrDefault();
                if (elective != null)
                {
                    var isOpen = elective.FromDate < DateTime.Now;
                    var isEnd  = elective.ToDate < DateTime.Now;

                    if (isOpen == false || isEnd)
                    {
                        return("选课未开放!");
                    }
                }

                //var limitOrgList = (from p in db.Table<Entity.tbElectiveOrgClass>()
                //                    join q in db.Table<Basis.Entity.tbClassStudent>() on p.tbClass.Id equals q.tbClass.Id
                //                    where p.tbElectiveOrg.tbElective.Id == electiveId
                //                      && p.tbElectiveOrg.IsDeleted == false
                //                      && q.tbStudent.tbSysUser.Id == Code.Common.UserId
                //                    select p.tbElectiveOrg.Id).ToList();

                var limitOrgList = (from p in db.Table <Entity.tbElectiveOrgClass>()
                                    join q in db.Table <Basis.Entity.tbClassStudent>() on p.tbClass.Id equals q.tbClass.Id
                                    where orgIds.Contains(p.tbElectiveOrg.Id) &&
                                    p.tbElectiveOrg.IsDeleted == false &&
                                    q.tbStudent.tbSysUser.Id == Code.Common.UserId
                                    select new { p.tbElectiveOrg, tbElectiveOrgClass = p }).ToList();

                foreach (var item in limitOrgList)
                {
                    if (item.tbElectiveOrgClass.RemainCount <= 0)
                    {
                        return($"选课{item.tbElectiveOrg.OrgName}针对当前行政班级的人数限制已满!");
                    }
                }


                var litmitOrgIds = limitOrgList.Select(p => p.tbElectiveOrg.Id).ToList();

                var tb = (from p in db.Table <Entity.tbElectiveOrg>()
                          where p.tbElective.Id == electiveId &&
                          p.tbCourse.IsDeleted == false &&
                          p.tbElectiveGroup.IsDeleted == false &&
                          p.tbElectiveSection.IsDeleted == false &&
                          (p.IsPermitClass == false || litmitOrgIds.Contains(p.Id))
                          orderby p.tbElectiveGroup.Id
                          select new
                {
                    p,
                    SectionId = p.tbElectiveSection.Id,
                    SectionNo = p.tbElectiveSection.No,
                    SectionName = p.tbElectiveSection.ElectiveSectionName,
                    SectionMin = p.tbElectiveSection.MinElective,
                    SectionMax = p.tbElectiveSection.MaxElective,
                    GroupId = p.tbElectiveGroup.Id,
                    GroupNo = p.tbElectiveGroup.No,
                    GroupName = p.tbElectiveGroup.ElectiveGroupName,
                    GroupMin = p.tbElectiveGroup.MinElective,
                    GroupMax = p.tbElectiveGroup.MaxElective,
                }).ToList();

                var sectionList = (from p in tb
                                   group p by new { p.SectionId, p.SectionNo, p.SectionName, p.SectionMax, p.SectionMin } into g
                                   select new
                {
                    g.Key.SectionId,
                    g.Key.SectionNo,
                    g.Key.SectionName,
                    g.Key.SectionMax,
                    g.Key.SectionMin
                }).OrderBy(d => d.SectionNo).ToList();

                var groupList = (from p in tb
                                 group p by new { p.GroupId, p.GroupNo, p.GroupName, p.GroupMax, p.GroupMin } into g
                                 select new
                {
                    g.Key.GroupId,
                    g.Key.GroupNo,
                    g.Key.GroupName,
                    g.Key.GroupMax,
                    g.Key.GroupMin
                }).OrderBy(d => d.GroupNo).ToList();

                var orgList = (from p in tb
                               where orgIds.Contains(p.p.Id)
                               select new
                {
                    p,
                    SectionId = p.SectionId,
                    GroupId = p.GroupId
                }).ToList();

                foreach (var group in groupList)
                {
                    if (orgList.Where(d => d.GroupId == group.GroupId).Count() < group.GroupMin)
                    {
                        return("分组[" + group.GroupName + "]要求最少选择 " + group.GroupMin + " 门!");
                    }
                    else if (orgList.Where(d => d.GroupId == group.GroupId).Count() > group.GroupMax)
                    {
                        return("超出分组[" + group.GroupName + "]的最大选课数要求,最多只能选择 " + group.GroupMax + " 门!");
                    }
                }

                foreach (var sec in sectionList)
                {
                    if (orgList.Where(d => d.SectionId == sec.SectionId).Count() < sec.SectionMin)
                    {
                        return("分段[" + sec.SectionName + "]要求最少选择 " + sec.SectionMin + " 门!");
                    }
                    else if (orgList.Where(d => d.SectionId == sec.SectionId).Count() > sec.SectionMax)
                    {
                        return("超出分段[" + sec.SectionName + "]的最大选课数要求,最多只能选择 " + sec.SectionMax + " 门!");
                    }
                }

                //已选课程
                var electiveDataList = (from p in db.Table <Entity.tbElectiveData>()
                                        .Include(d => d.tbElectiveOrg)
                                        where p.tbElectiveOrg.IsDeleted == false &&
                                        p.tbElectiveOrg.tbElective.Id == electiveId &&
                                        p.tbStudent.tbSysUser.Id == Code.Common.UserId
                                        select p).ToList();

                //判断课程剩余名额
                foreach (var orgId in orgIds.Where(d => electiveDataList.Select(p => p.tbElectiveOrg.Id).Contains(d) == false))
                {
                    var tbOrg = orgList.Where(d => d.p.p.Id == orgId).FirstOrDefault();
                    if (tbOrg.p.p.RemainCount <= 0)
                    {
                        return("[" + tbOrg.p.p.OrgName + "]的选课人数已满");
                    }
                    else if ((tbOrg.p.p.MaxCount - ElectiveDataController.GetCount(db, tbOrg.p.p.Id)) <= 0)
                    {
                        tbOrg.p.p.RemainCount = tbOrg.p.p.MaxCount - ElectiveDataController.GetCount(db, tbOrg.p.p.Id);
                        db.SaveChanges();
                        return("[" + tbOrg.p.p.OrgName + "]的选课人数已满");
                    }
                }

                //删除已选
                var mydataIdList = electiveDataList.Select(d => d.Id).ToList();
                foreach (var electiveData in electiveDataList.Where(d => orgIds.Contains(d.tbElectiveOrg.Id) == false))
                {
                    electiveData.IsDeleted = true;
                    electiveData.tbElectiveOrg.RemainCount++;
                    var limitClass = limitOrgList.Where(p => p.tbElectiveOrgClass.tbElectiveOrg.Id == electiveData.tbElectiveOrg.Id).Select(p => p.tbElectiveOrgClass).FirstOrDefault();
                    if (limitClass != null)
                    {
                        limitClass.RemainCount++;
                    }
                    mydataIdList.Remove(electiveData.Id);
                }

                db.SaveChanges();

                var student = db.Table <Student.Entity.tbStudent>().FirstOrDefault(p => p.tbSysUser.Id == Code.Common.UserId);
                foreach (var orgId in orgIds.Where(d => electiveDataList.Select(p => p.tbElectiveOrg.Id).Contains(d) == false))
                {
                    //更新ElectiveOrg
                    var electiveOrg = orgList.Where(d => d.p.p.Id == orgId).FirstOrDefault();
                    if (electiveOrg.p.p.RemainCount > 0)
                    {
                        electiveOrg.p.p.RemainCount--;

                        var limitClass = limitOrgList.Where(p => p.tbElectiveOrgClass.tbElectiveOrg.Id == orgId).Select(p => p.tbElectiveOrgClass).FirstOrDefault();
                        if (limitClass != null)
                        {
                            limitClass.RemainCount--;
                        }

                        var data = new Entity.tbElectiveData();
                        data.tbStudent     = student;
                        data.tbElectiveOrg = electiveOrg.p.p;
                        data.InputDate     = DateTime.Now;
                        db.Set <Entity.tbElectiveData>().Add(data);

                        db.SaveChanges();
                        mydataIdList.Add(data.Id);
                    }
                    else
                    {
                        return("[" + electiveOrg.p.p.OrgName + "]的选课人数已满");
                    }
                }

                //db.SaveChanges();


                //删除重复的数据,防止同一节次添加多条记录(主要是解决高并发下会重复插入数据的问题)
                var invalidDataList = (from p in db.Table <Entity.tbElectiveData>()
                                       join q in db.Table <Entity.tbElectiveOrgSchedule>() on p.tbElectiveOrg.Id equals q.tbElectiveOrg.Id
                                       where p.tbElectiveOrg.IsDeleted == false &&
                                       p.tbElectiveOrg.tbElective.Id == electiveId &&
                                       p.tbStudent.tbSysUser.Id == Code.Common.UserId &&
                                       mydataIdList.Contains(p.Id) == false
                                       select p).Include(d => d.tbElectiveOrg).ToList();
                foreach (var a in invalidDataList)
                {
                    a.tbElectiveOrg.RemainCount++;

                    a.IsDeleted = true;
                }

                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException exception)
            {
                exception.Entries.Single().Reload();
                Save(db, electiveId, orgIds);
            }

            return(string.Empty);
        }