public List<AssessEmailViewModels> GetAssessEmailStatus(int PageIndex, int PageCount, out int TotalCount)
 {
     try
     {
         using (var ctx = new EvaluationSysEntities())
         {
             var query = (from c in ctx.UserInfo
                          where c.PID == ProjectId && c.ProjectMng.Status >= 0
                          && c.AssessObj.Any()
                          orderby c.UserNum
                          select new AssessEmailViewModels
                          {
                              UserId = c.Id,
                              UserName = c.UserName,
                              PID = c.PID,
                              ProjectName = c.ProjectMng.PjName,
                              CompleteQuestion = c.AssessObj.Count(w => w.Status == 1),
                              TotalQuestion = c.AssessObj.Count(),
                              EmailStatus = c.AssessObj.All(a => a.Status >= 0) ? "发送成功" : c.AssessObj.All(a => a.Status == -10) ? "发送失败" : "未发送",
                              EStatusColor = c.AssessObj.All(a => a.Status >= 0) ? "green" : c.AssessObj.All(a => a.Status == -10) ? "red" : "",
                              QuestionStatus = !c.AssessObj.Any(a => new int[2] { 1, 0 }.Contains(a.Status)) ? "未开始" : c.AssessObj.Count() == c.AssessObj.Count(w => w.Status == 1) ? "已完成" : "进行中",
                              OperateTime = c.AssessObj.FirstOrDefault().EndTime ?? defaultTime
                          }).Paging(PageIndex, PageCount, out TotalCount).ToList();
             int i = (PageIndex - 1) * PageCount;
             query.ForEach(r => { r.RecordNum = ++i; });
             return query;
         }
     }
     catch (Exception ex)
     {
         TotalCount = 0;
         errmsg = ex.GetBaseException().Message;
         throw ex;
     }
 }
 public IEnumerable<PaperViewModels> GetPaperList(int PageIndex,int PageCount,out int TotalCount)
 {
     try
     {
         using (var ctx = new EvaluationSysEntities())
         {
             var paper = (from c in ctx.TestPage
                          where c.PID == ProjectId && c.ProjectMng.Status >= 0
                          orderby c.CreateTime descending
                          select new PaperViewModels
                          {
                              PaperId = c.Id,
                              CreateTime = c.CreateTime,
                              PaperName = c.Name,
                              PID = c.PID,
                              TopicArrs = c.TopicArr
                          }).Paging(PageIndex, PageCount, out TotalCount).ToList();
             int i = (PageIndex - 1) * PageCount;
             paper.ForEach(p => { p.RecordNum = ++i; });
             return paper;
         }
     }
     catch (Exception ex)
     {
         TotalCount = 0;
         errmsg = ex.GetBaseException().Message;
         throw ex;
     }
 }
 public IEnumerable<SelectListItem> GetAllNames(Guid? UserId = null)
 {
     try
     {
         using (var ctx = new EvaluationSysEntities())
         {
             var query = (from c in ctx.UserInfo
                          where c.PID == ProjectId && c.ProjectMng.Status >= 0
                          select new
                          {
                              n = c.UserName,
                              v = c.Id
                          }).ToList();
             var users = query.Select(s => new SelectListItem { Text = s.n, Value = s.v.ToString("N") }).ToList();
             if (UserId.HasValue)
             {
                 var user = users.FirstOrDefault(f => f.Value == UserId.Value.ToString("N"));
                 if (user != null) user.Selected = true;
             }
             return users;
         }
     }
     catch (Exception ex)
     {
         errmsg = ex.GetBaseException().Message;
         throw ex;
     }
 }
 public IEnumerable<UserViewModels> GetUserList(int PageIndex, int PageCount, out int TotalCount, string SearchStr = null)
 {
     try
     {
         TotalCount = 0;
         using (var ctx = new EvaluationSysEntities())
         {
             var query = ctx.UserInfo.Where(w => w.PID == ProjectId && w.ProjectMng.Status >= 0);
             if (!string.IsNullOrEmpty(SearchStr))
             {
                 query = query.Where(w => w.UserNum.Contains(SearchStr) || w.UserName.Contains(SearchStr));
             }
             var user = (from c in query
                         orderby c.OperatrTime descending
                         select new UserViewModels
                         {
                             UserId = c.Id,
                             UserName = c.UserName,
                             UserNo = c.UserNum,
                             Department = c.BM,
                             Position = c.ZW,
                             EmailAddr = c.Email
                         }).Paging(PageIndex, PageCount, out TotalCount).ToList();
             int i = (PageIndex - 1) * PageCount;
             user.ForEach(u => { u.RecordNum = ++i; });
             return user;
         }
     }
     catch (Exception ex)
     {
         errmsg = ex.GetBaseException().Message;
         throw ex;
     }
 }
 public bool AddUpdateObjectiveQuestion(IEnumerable<QuestionViewModels> models, out string ErrMsg)
 {
     using (var ctx = new EvaluationSysEntities())
     {
         try
         {
             ErrMsg = null;
             if (models == null) throw new ArgumentNullException("models");
             if (models.Any(a => string.IsNullOrEmpty(a.Topic)))
                 throw new Exception("题目不能为空");
             var ids = models.Where(w => w.Id != default(int)).Select(s => s.Id).ToList();
             var ups = (from c in ctx.TopicRecord
                        where ids.Contains(c.Id) && c.PID == ProjectId
                        && c.Type == "A"
                        select c).ToList();
             ups.ForEach(e =>
             {
                 var model = models.FirstOrDefault(f => f.Id == e.Id);
                 e.Heading = model.Topic ?? ""; e.Aspect = model.Aspect ?? "";
                 e.KeyA = model.a ?? ""; e.KeyB = model.b ?? "";
                 e.KeyC = model.c ?? ""; e.KeyD = model.d ?? "";
                 e.KeyE = model.e ?? ""; e.KeyF = model.f ?? "";
                 e.Weight = model.Weight; e.Competency = e.Competency ?? "";
             });
             List<TopicRecord> tr = new List<TopicRecord>();
             foreach (var model in models.Where(w => w.Id == default(int)).ToList())
             {
                 TopicRecord topic= new TopicRecord
                 {
                     Type = model.type ?? "A",
                     Heading = model.Topic ?? "",
                     KeyA = model.a ?? "",
                     KeyB = model.b ?? "",
                     KeyC = model.c ?? "",
                     KeyD = model.d ?? "",
                     KeyE = model.e ?? "",
                     KeyF = model.f ?? "",
                     Aspect = model.Aspect ?? "",
                     Competency = model.Competency ?? "",
                     Weight = model.Weight,
                     PID = ProjectId,
                     CreateTime = DateTime.Now,
                 };
                 ctx.Entry(topic).State = System.Data.Entity.EntityState.Added;
                 ctx.TopicRecord.Add(topic);
             }
             var dels = (from c in ctx.TopicRecord
                         where !ids.Contains(c.Id) && c.PID == ProjectId
                         && c.Type == "A"
                         select c).ToList();
             dels.ForEach(e => { ctx.Entry(e).State = System.Data.Entity.EntityState.Deleted; });
             ctx.TopicRecord.RemoveRange(dels);
             return ctx.SaveChanges() >= 0;
         }
         catch (Exception ex) { ErrMsg = ex.GetBaseException().Message; return false; }
     }
 }
 public List<int> GetQuestionIds()
 {
     using(var ctx = new EvaluationSysEntities())
     {
         return ctx.Database.SqlQuery<int>("SELECT [A].[Id] AS [Id] FROM"
             + " (SELECT [Id] AS [Id], [Type] AS [Type] FROM [dbo].[TopicRecord] WHERE [PID] = @p0) AS [A]"
             + " ORDER BY [A].[Type] ASC, [A].[Id] ASC", ProjectId).ToList();
     }
 }
 public Task<QuestionnaireViewModels> GetQuestionnaireTopic(int AssessId, Guid UserId, int offset = 1)
 {
     return Task.Factory.StartNew(() =>
     {
         try
         {
             QuestionnaireViewModels result = new QuestionnaireViewModels { AssessId = AssessId, UserId = UserId, Offset = offset };
             using (var ctx = new EvaluationSysEntities())
             {
                 int pagecount = 6, totalcount = 0;
                 var pagesetting = ctx.SettingConfig.FirstOrDefault(f => f.Name == "PageCount" && f.ConfigStatus >= 0)?.Value;
                 int.TryParse(pagesetting ?? "6", out pagecount);
                 var assess = ctx.AssessObj.FirstOrDefault(f => f.Id == AssessId && f.PID == ProjectId && f.UserID == UserId && f.Status >= -1);
                 if (assess == null)
                     throw new ArgumentException("Invaild Parameter", nameof(AssessId));
                 var page = new List<string>(assess.TestPage.TopicArr.Split(',')).ConvertAll(int.Parse);
                 result.Answers = (from c in ctx.TopicRecord
                                   where page.Contains(c.Id) && c.PID == ProjectId
                                   orderby c.Id ascending
                                   select new QuestionnaireViewModels.AnswerKeyArr
                                   {
                                       TopicHead = c.Heading,
                                       TopicId = c.Id,
                                       TopicType = c.Type,
                                       topic = c,
                                       subject = c.SubjectiveItems.FirstOrDefault(f => f.AssessId == AssessId),
                                   }).Paging(offset, pagecount, out totalcount).ToList();
                 result.IsUserName = assess.UserInfo1.UserName;
                 result.IsUserDepartment = assess.UserInfo1.BM;
                 result.IsUserPosition = assess.UserInfo1.ZW;
                 result.TotalCount = totalcount;
                 result.TotalPage = totalcount / pagecount + (totalcount % pagecount > 0 ? 1 : 0);
                 int i = (offset - 1) * pagecount;
                 foreach (var ans in result.Answers)
                 {
                     ans.RecordNum = ++i;
                     if (ans.TopicType == "A")
                     {
                         ans.Answer = assess.KeyArr?.Split(',').FirstOrDefault(f => int.Parse(f.Split('-')[0]) == ans.TopicId)?.Split('-')[1];
                         ans.Options = new List<string>() { ans.topic?.KeyA, ans.topic?.KeyB, ans.topic?.KeyC, ans.topic?.KeyD, ans.topic?.KeyE, ans.topic?.KeyF };
                     }
                     else
                     {
                         ans.Answer = ans.subject?.Answers;
                     }
                 }
             }
             return result;
         }
         catch (Exception ex)
         {
             errmsg = ex.GetBaseException().Message;
             throw ex;
         }
     });
 }
 public bool CheckExpireTime(Guid UserId, out DateTime deadline)
 {
     deadline = DateTime.Now;
     using (var ctx = new EvaluationSysEntities())
     {
         DateTime dt = new DateTime();
         if (DateTime.TryParse(ctx.SettingConfig.Where(f => f.Name == "DeadLine").Select(s => s.Value).FirstOrDefault(), out dt))
             deadline = dt;
         string sql = "SELECT CAST(COUNT(1) AS BIT) FROM [dbo].[ASSESSOBJ] WHERE [USERID]=@p0 AND [PID]=@p1 AND [SYSENDTIME]<@p2 AND [Status]>=-1";
         return !ctx.Database.SqlQuery<bool>(sql, UserId, ProjectId, DateTime.Now).FirstOrDefault();
     }
 }
 public IEnumerable<QuestionViewModels> GetQuestionByPaper(int? PaperId, string sorter, out string PaperName)
 {
     try
     {
         using (var ctx = new EvaluationSysEntities())
         {
             PaperName = "";
             string sql = "SELECT * FROM [dbo].[TopicRecord] WHERE PID=@p0 ";
             //var query = ctx.TopicRecord.OrderBy(o => o.Type).AsQueryable();
             if (PaperId != null)
             {
                 var paper = ctx.TestPage.SqlQuery("SELECT TOP 1 * FROM [dbo].[TestPage] WHERE Id=@p0 AND PID=@p1", PaperId, ProjectId).FirstOrDefault();
                 if (paper == null) throw new Exception("不存在的试卷");
                 PaperName = paper.Name;
                 sql += string.Format("AND Id IN ({0}) ", paper.TopicArr);
                 //var qids = new List<string>(paper.TopicArr.Split(',')).ConvertAll(int.Parse);
                 //query = query.WhereIn(w => w.Id, qids);
             }
             string orderstr = "ORDER BY Type ASC";
             if (!string.IsNullOrEmpty(sorter.Trim()) && sorter.Split(' ').Length > 1)
             {
                 orderstr = string.Format("ORDER BY {0}", sorter);
                 //query = query.Sorting(sorter.Split(' ')[0], (OrderType)Enum.Parse(typeof(OrderType), sorter.Split(' ')[1], true));
             }
             sql += orderstr;
             var query = ctx.TopicRecord.SqlQuery(sql, ProjectId).ToList();
             var question = query.Select((c, x) => new QuestionViewModels
             {
                 RecordNum = ++x,
                 a = c.KeyA,
                 b = c.KeyB,
                 c = c.KeyC,
                 d = c.KeyD,
                 e = c.KeyE,
                 f = c.KeyF,
                 Aspect = c.Aspect,
                 Competency = c.Competency,
                 Id = c.Id,
                 PID = c.PID,
                 type = c.Type,
                 Topic = c.Heading,
                 Weight = c.Weight ?? 0
             }).ToList();
             return question;
         }
     }
     catch (Exception ex)
     {
         errmsg = ex.GetBaseException().Message;
         throw ex;
     }
 }
 public List<AssessResultViewModels> GetResultList()
 {
     try
     {
         using (var ctx = new EvaluationSysEntities())
         {
             var query = (from c in ctx.AssessObj
                          where c.PID == ProjectId && c.Status == 1
                          select new AssessResultViewModels
                          {
                              AssessId = c.Id,
                              IsCompleted = c.Status == 1 ? "完成" : "未完成",
                              PageName = c.TestPage.Name,
                              IsUserEmail = c.UserInfo1.Email,
                              IsUserNo = c.UserInfo1.UserNum,
                              IsUserName = c.UserInfo1.UserName,
                              IsUserDepartment = c.UserInfo1.BM,
                              IsUserPosition = c.UserInfo1.ZW,
                              UserNo = c.UserInfo.UserNum,
                              UserName = c.UserInfo.UserName,
                              UserEmail = c.UserInfo.Email,
                              UserDepartment = c.UserInfo.BM,
                              UserPosition = c.UserInfo.ZW,
                              UserRelation = c.Bind,
                              Frequence = c.Frequency,
                              objective = c.KeyArr,
                              subjective = c.SubjectArr
                          }).ToList();
             
             const string sql = "SELECT s.[Id],s.[TopicId],s.[AssessId],s.[Answers],s.[CreateTime],s.[PID] FROM [AssessObj] A"
                 +" INNER JOIN [SubjectiveItems] S ON EXISTS (SELECT 1 FROM [DBO].[F_split](A.[SubjectArr],',') A WHERE A.COL=S.[TopicId])"
                 +" AND A.ID=S.[AssessId] WHERE A.[Status] = 1 AND A.[PID] = @P0 AND S.[PID]=@P0";
             var subs = ctx.SubjectiveItems.SqlQuery(sql, ProjectId).ToList();
             int i = 0;
             query.ForEach(q =>
             {
                 q.RecordNum = ++i;
                 q.ObjectiveAnswer = !string.IsNullOrEmpty(q.objective) ? q.objective.Split(',').ToDictionary(k => int.Parse(k.Split('-')[0]), v => v.Split('-')[1]) : new Dictionary<int, string>();
                 List<int> sub = !string.IsNullOrEmpty(q.subjective) ? q.subjective.Split(',').ToList().ConvertAll(int.Parse) : new List<int>();
                 q.SubjectiveAnswer = (from c in subs where c.AssessId == q.AssessId select c).ToDictionary(k => k.TopicId, v => v.Answers);
             });
             return query;
         }
     }
     catch (Exception ex)
     {
         errmsg = ex.GetBaseException().Message;
         throw ex;
     }
 }
 private Dictionary<string, string> GetSettings()
 {
     try
     {
         using (var ctx = new EvaluationSysEntities())
         {
             return (from c in ctx.SettingConfig
                     where c.ConfigStatus >= 0
                     select new
                     {
                         Name = c.Name,
                         Value = c.Value,
                     }).ToDictionary(k => k.Name, v => v.Value);
         }
     }
     catch (Exception ex)
     {
         errmsg = ex.GetBaseException().Message;
         throw ex;
     }
 }
 public bool SetConfigs(SettingsViewModels settings, out string ErrorMsg)
 {
     ErrorMsg = null;
     try
     {
         using(var ctx = new EvaluationSysEntities())
         {
             var query = (from c in ctx.SettingConfig where c.ConfigStatus >= 0 select c).ToList();
             foreach(PropertyInfo p in typeof(SettingsViewModels).GetProperties())
             {
                 var setting = query.FirstOrDefault(f => f.Name == p.Name);
                 if(setting == null)
                 {
                     ctx.SettingConfig.Add(new SettingConfig
                     {
                         Id = Guid.NewGuid(),
                         ConfigStatus = 1,
                         CreateTime = DateTime.Now,
                         Name = p.Name,
                         Value = Convert.ToString(p.GetValue(settings)),
                         OperateTime = DateTime.Now
                     });
                 }
                 else
                 {
                     setting.Value = Convert.ToString(p.GetValue(settings));
                     setting.OperateTime = DateTime.Now;
                 }
             }
             return ctx.SaveChanges() >= 0;
         }
     }
     catch(Exception ex)
     {
         ErrorMsg = ex.GetBaseException().Message;
         return false;
     }
 }
 public List<EmailTempletViewModels> GetEmailTemplate()
 {
     try
     {
         using (var ctx = new EvaluationSysEntities())
         {
             var email = (from c in ctx.EmailTemplate
                          select new EmailTempletViewModels
                          {
                              TID = c.Id,
                              EmailHead = c.EmailHead,
                              EmailTemplet = c.EmailContent,
                              CreateTime = c.CreateTime,
                          });
             return email.ToList();
         }
     }
     catch (Exception ex)
     {
         errmsg = ex.GetBaseException().Message;
         throw ex;
     }
 }
 public bool SendEmail(Guid UserId, out string ErrMsg)
 {
     ErrMsg = null; DateTime deadline = DateTime.Now.AddDays(30);
     try
     {
         using (var ctx = new EvaluationSysEntities())
         {
             var setting = (from c in ctx.SettingConfig
                            where c.Name == "DeadLine"
                            select c.Value).FirstOrDefault();
             DateTime.TryParse(setting, out deadline);
             var user = (from c in ctx.UserInfo
                         where c.Id == UserId && c.PID == ProjectId
                         select c).FirstOrDefault();
             if (user == null) { ErrMsg = "不合法的用户"; return false; }
             var assess = (from c in ctx.AssessObj
                           where c.UserID == UserId && c.PID == ProjectId
                           select c).ToList();
             string address = user.Email;
             string cc = ctx.SettingConfig.FirstOrDefault(f => f.Name == "CCAddress")?.Value;
             if (string.IsNullOrEmpty(address))
             {
                 ErrMsg = "未配置或错误的用户邮箱";
                 return false;
             }
             Guid id = Guid.Parse("843A5405-41B8-4F3C-A0B6-2AF5F953F851");
             var template = (from c in ctx.EmailTemplate
                             where c.Id == id
                             select c).FirstOrDefault();
             if (template == null)
             {
                 ErrMsg = "未配置或找不到邮件模板";
                 return false;
             }
             string html = template.EmailContent.Replace("{userId}", user.Id.ToString("N")).Replace("{userName}", user.UserName);
             html = html.Replace("{deadLine}", deadline.ToString("yyyy年MM月dd日"));
             if (!emailUtils.SendEmail(address, template.EmailHead, html, out ErrMsg, cc))
             {
                 assess.ForEach(a => { a.EndTime = DateTime.Now; a.Status = -10; });
                 ctx.SaveChanges();
                 return false;
             }
             assess.ForEach(a => { a.EndTime = DateTime.Now; a.Status = 10; });
             ctx.SaveChanges();
         }
         return true;
     }
     catch (Exception ex)
     {
         ErrMsg = ex.GetBaseException().Message;
         return false;
     }
 }
 public bool SaveImportModel(AssessImportModels models, out string ErrMsg)
 {
     ErrMsg = null;
     try
     {
         DateTime deadline = DateTime.Now;
         using (var ctx = new EvaluationSysEntities())
         {
             if(string.IsNullOrEmpty(models.UserNo)|| string.IsNullOrEmpty(models.IsUserNo))
             {
                 ErrMsg = "用户编号不能为空";
                 return false;
             }
             var setting = (from c in ctx.SettingConfig where c.Name == "DeadLine" select c.Value).FirstOrDefault();
             DateTime.TryParse(setting, out deadline);
             var user = (from c in ctx.UserInfo
                         where c.PID == ProjectId && c.UserNum == models.UserNo
                         select c).FirstOrDefault();
             var isuser = (from c in ctx.UserInfo
                           where c.PID == ProjectId && c.UserNum == models.IsUserNo
                           select c).FirstOrDefault();
             if (user == null || isuser == null)
             {
                 ErrMsg = "错误用户编号"; return false;
             }
             var paper = (from c in ctx.TestPage where c.PID == ProjectId && c.Name == models.PaperName select c.Id).FirstOrDefault();
             if (paper == default(int))
             {
                 ErrMsg = "不正确的试卷名称"; return false;
             }
             ctx.AssessObj.Add(new AssessObj
             {
                 IsUserID = isuser.Id,
                 UserID = user.Id,
                 SysEndTime = deadline,
                 Bind = models.UserRelation,
                 TestPageID = paper,
                 Status = -1,
                 PID = ProjectId,
                 LastName = user.LastName,
                 FirstName = user.FirstName,
                 Frequency = "",
                 BindPageSave = ""
             });
             return ctx.SaveChanges() > 0;
         }
     }
     catch (Exception ex)
     {
         ErrMsg = ex.GetBaseException().Message; return false;
     }
 }
 public bool AddUpdateRelation(IEnumerable<string> relations, out string ErrMsg)
 {
     ErrMsg = null;
     try
     {
         using (var ctx = new EvaluationSysEntities())
         {
             var dels = ctx.Typedefs.Where(w => w.PID == ProjectId && w.Type == "relation").ToList();
             dels.ForEach(e => ctx.Entry(e).State = System.Data.Entity.EntityState.Deleted);
             ctx.Typedefs.RemoveRange(dels);
             foreach (string r in relations)
             {
                 if (string.IsNullOrEmpty(r)) continue;
                 ctx.Typedefs.Add(new Typedefs
                 {
                     Id = Guid.NewGuid(),
                     Code = "",
                     CreateTime = DateTime.Now,
                     Name = r ?? "",
                     PID = ProjectId,
                     Type = "relation"
                 });
             }
             return ctx.SaveChanges() >= 0;
         }
     }
     catch (Exception ex)
     {
         ErrMsg = ex.GetBaseException().Message;
         return false;
     }
 }
 public IEnumerable<SelectListItem> GetAllFrequency(int AssessId)
 {
     try
     {
         using (var ctx = new EvaluationSysEntities())
         {
             string Frequency = ctx.AssessObj.FirstOrDefault(f => f.Id == AssessId && ProjectId == f.PID)?.Frequency;
             var query = (from c in ctx.Typedefs
                          where c.PID == ProjectId
                          && c.ProjectMng.Status >= 0
                          && c.Type == "freq"
                          orderby c.Code ascending
                          select new SelectListItem
                          {
                              Text = c.Name,
                              Value = c.Code
                          }).ToList();
             query.Insert(0, new SelectListItem { Text = "请选择", Value = "-1" });
             if (!string.IsNullOrEmpty(Frequency))
             {
                 var freq = query.FirstOrDefault(f => f.Text == Frequency);
                 if (freq != null) freq.Selected = true;
             }
             else
             {
                 query.FirstOrDefault(f => f.Value == "-1").Selected = true;
             }
             return query;
         }
     }
     catch (Exception ex)
     {
         errmsg = ex.GetBaseException().Message;
         throw ex;
     }
 }
 public IEnumerable<SelectListItem> GetAllRelation(string Relation = null)
 {
     try
     {
         using (var ctx = new EvaluationSysEntities())
         {
             var query = (from c in ctx.Typedefs
                          where c.PID == ProjectId
                          && c.ProjectMng.Status >= 0
                          && c.Type == "relation"
                          select new SelectListItem
                          {
                              Text = c.Name,
                              Value = c.Name
                          }).ToList();
             if (!string.IsNullOrEmpty(Relation))
             {
                 var r = query.FirstOrDefault(f => f.Value == Relation);
                 if (r != null) r.Selected = true;
             }
             return query;
         }
     }
     catch (Exception ex)
     {
         errmsg = ex.GetBaseException().Message;
         throw ex;
     }
 }
 public IEnumerable<AssessViewModels> GetAssessList(Guid UserId)
 {
     try
     {
         using (var ctx = new EvaluationSysEntities())
         {
             var query = ctx.AssessObj.Where(w => w.PID == ProjectId && w.UserID == UserId && w.ProjectMng.Status >= 0 && w.Status >= -1);
             var assess = query.OrderByDescending(o => o.SysEndTime).Select(c => new AssessViewModels
             {
                 AssessId = c.Id,
                 IsUserId = c.IsUserID.Value,
                 UserId = c.UserID.Value,
                 UserName = c.UserInfo.UserName,
                 IsUserName = c.UserInfo1.UserName,
                 Relation = c.Bind,
                 SysEndTime = c.SysEndTime ?? defaultTime,
                 Status = c.Status,
                 CompleteQuestion = (c.SubjectArr == null ? 0 : ctx.F_split(c.SubjectArr, ",").Count()) + (c.KeyArr == null ? 0 : ctx.F_split(c.KeyArr, ",").Count()),
                 TotalQuestion = c.TestPage.TopicArr == null || c.TestPage.TopicArr == "" ? 0 : ctx.F_split(c.TestPage.TopicArr, ",").Count(),
                 OperateTime = c.EndTime ?? defaultTime
             });
             return assess.ToList();
         }
     }
     catch (Exception ex)
     {
         errmsg = ex.GetBaseException().Message;
         throw ex;
     }
 }
 public AssessViewModels GetAssessDetails(int? AssessId = null, Guid? UserId = null)
 {
     try
     {
         using (var ctx = new EvaluationSysEntities())
         {
             if (AssessId.HasValue)
             {
                 var query = ctx.AssessObj.AsQueryable();
                 if (UserId.HasValue)
                     query = query.Where(w => w.UserID == UserId.Value);
                 var assess = (from c in query
                               where c.Id == AssessId && c.PID == ProjectId
                               select new AssessViewModels
                               {
                                   AssessId = c.Id,
                                   IsUserId = c.IsUserID.Value,
                                   UserId = c.UserID.Value,
                                   UserName = c.UserInfo.UserName,
                                   IsUserName = c.UserInfo1.UserName,
                                   PaperId = c.TestPageID.Value,
                                   PaperName = c.TestPage.Name,
                                   Relation = c.Bind
                               }).FirstOrDefault();
                 if (assess == null) assess = defaultModel;
                 return assess;
             }
             else return defaultModel;
         }
     }
     catch (Exception ex)
     {
         errmsg = ex.GetBaseException().Message;
         throw ex;
     }
 }
 public Dictionary<string,string> GetTypedefs(string Type)
 {
     try
     {
         using(var ctx = new EvaluationSysEntities())
         {
             var dic = (from c in ctx.Typedefs
                        where c.PID == ProjectId 
                        && c.Type == Type
                        select new
                        {
                            k = c.Code,
                            v = c.Name
                        }).ToDictionary(k => k.k, v => v.v);
             return dic;
         }
     }
     catch(Exception ex)
     {
         errmsg = ex.GetBaseException().Message;
         throw ex;
     }
 }
 public bool AnswersSave(QuestionnaireViewModels models, out string ErrMsg)
 {
     ErrMsg = null;
     try
     {
         using (var ctx = new EvaluationSysEntities())
         {
             var assess = ctx.AssessObj.FirstOrDefault(f => f.Id == models.AssessId && f.PID == ProjectId && f.UserID == models.UserId && f.Status >= -1);
             if (assess == null)
                 throw new ArgumentException("Invaild Parameter", nameof(models.AssessId));
             List<string> tmpans = new List<string>();
             List<int> tmpsub = new List<int>();
             if (!string.IsNullOrEmpty(assess.KeyArr))
                 tmpans.AddRange(assess.KeyArr.Split(','));
             if (!string.IsNullOrEmpty(assess.SubjectArr))
                 tmpsub.AddRange(assess.SubjectArr.Split(',').ToList().ConvertAll(int.Parse));
             if (models.Answers == null) return true;
             foreach (var ans in models.Answers)
             {
                 if (ans.TopicType == "A")
                 {
                     var objcet = tmpans.FirstOrDefault(w => int.Parse(w.Split('-')[0]) == ans.TopicId);
                     if (objcet != null) tmpans.Remove(objcet);
                     tmpans.Add(ans.Answer);
                 }
                 else
                 {
                     if (!tmpsub.Contains(ans.TopicId)) tmpsub.Add(ans.TopicId);
                     var subject = ctx.TopicRecord.FirstOrDefault(f => f.Id == ans.TopicId && f.PID == ProjectId)?.SubjectiveItems.FirstOrDefault(f => f.AssessId == assess.Id);
                     if (subject == null)
                     {
                         ctx.SubjectiveItems.Add(new SubjectiveItems
                         {
                             TopicId = ans.TopicId,
                             PID = ProjectId,
                             AssessId = assess.Id,
                             CreateTime = DateTime.Now,
                             Answers = ans.Answer,
                         });
                     }
                     else
                     {
                         subject.Answers = ans.Answer;
                     }
                 }
             }
             if (models.TotalPage == models.Offset) assess.Status = 1;
             assess.EndTime = DateTime.Now;
             tmpans = tmpans.OrderBy(o => int.Parse(o.Split('-')[0])).ToList();
             assess.KeyArr = string.Join(",", tmpans);
             assess.SubjectArr = string.Join(",", tmpsub);
             return ctx.SaveChanges() >= 0;
         }
     }
     catch (Exception ex)
     {
         ErrMsg = errmsg = ex.GetBaseException().Message;
         return false;
     }
 }
 public bool UpdateAssessAttr(AssessViewModels model, IEnumerable<string> PropertyNames, out string ErrMsg)
 {
     ErrMsg = null;
     try
     {
         using(var ctx = new EvaluationSysEntities())
         {
             var query = (from c in ctx.AssessObj where c.Id == model.AssessId select c).FirstOrDefault();
             if(query == null)
             {
                 ErrMsg = "不正确的参数";
                 return false;
             }
             foreach(string name in PropertyNames)
             {
                 var p = typeof(AssessViewModels).GetProperty(name);
                 if (p == null) continue;
                 var pi = typeof(AssessObj).GetProperty(name);
                 if (pi != null)
                     pi.SetValue(query, p.GetValue(model).ConvertObject(pi.PropertyType));
             }
             return ctx.SaveChanges() >= 0;
         }
     }
     catch (Exception ex)
     {
         ErrMsg = ex.GetBaseException().Message;
         return false;
     }
 }
 public bool ResetAssessStatus(IEnumerable<int> AssessIds, out string ErrMsg)
 {
     ErrMsg = null;
     try
     {
         using(var ctx = new EvaluationSysEntities())
         {
             var assess = (from c in ctx.AssessObj
                           where AssessIds.Contains(c.Id) && c.PID == ProjectId
                           && c.Status != 0
                           select c).ToList();
             if(assess.Count == 0)
             {
                 ErrMsg = "不存在有效的评估对象(正在进行的评估不能被重置)";
                 return false;
             }
             assess.ForEach(e => {
                 e.Status = -1;
                 e.EndTime = DateTime.Now;
             });
             return ctx.SaveChanges() >= 0;
         }
     }
     catch (Exception ex)
     {
         ErrMsg = ex.GetBaseException().Message;
         return false;
     }
 }
 public bool AddUpdateAssess(AssessViewModels model, out int AssessId, out string ErrMsg)
 {
     ErrMsg = null; AssessId = model.AssessId ?? 0;
     try
     {
         AssessObj obj = null;
         DateTime deadline = DateTime.Parse("1900-1-1");
         using (var ctx = new EvaluationSysEntities())
         {
             var setting = (from c in ctx.SettingConfig where c.Name == "DeadLine" select c.Value).FirstOrDefault();
             var userinfo = ctx.UserInfo.FirstOrDefault(f => f.Id == model.UserId && f.PID == ProjectId);
             if (userinfo == null) throw new Exception("不正确的用户ID");
             DateTime.TryParse(setting, out deadline);
             if (!model.AssessId.HasValue)
             {
                 obj = new AssessObj
                 {
                     IsUserID = model.IsUserId,
                     UserID = model.UserId,
                     SysEndTime = deadline,
                     Bind = model.Relation,
                     TestPageID = model.PaperId,
                     Status = -1,
                     PID = ProjectId,
                     LastName = userinfo.LastName,
                     FirstName = userinfo.FirstName,
                     Frequency = "",
                     BindPageSave = ""
                 };
                 ctx.AssessObj.Add(obj);
             }
             else
             {
                 var update = (from c in ctx.AssessObj
                               where c.Id == model.AssessId && c.PID == ProjectId
                               select c).FirstOrDefault();
                 if (update != null)
                 {
                     update.IsUserID = model.IsUserId;
                     update.UserID = model.UserId;
                     update.Bind = model.Relation;
                     update.SysEndTime = deadline;
                     update.TestPageID = model.PaperId;
                 }
             }
             int ret = ctx.SaveChanges();
             if (!model.AssessId.HasValue) AssessId = obj.Id;
             return ret >= 0;
         }
     }
     catch (Exception ex)
     {
         ErrMsg = ex.GetBaseException().Message;
         return false;
     }
 }
 public string GetTopicArr(int AssessId, Guid? UserId = null)
 {
     try
     {
         using (var ctx = new EvaluationSysEntities())
         {
             var query = ctx.AssessObj.Where(w => w.Id == AssessId && w.PID == ProjectId);
             if (UserId.HasValue)
             {
                 query = query.Where(w => w.UserID == UserId);
             }
             return query.Select(s => s.TestPage.TopicArr).FirstOrDefault();
         }
     }
     catch (Exception ex)
     {
         errmsg = ex.GetBaseException().Message;
         throw ex;
     }
 }
 public bool AddUpdateEmailTemplate(EmailTempletViewModels model, out Guid TID, out string ErrMsg)
 {
     if (model == null)
         throw new ArgumentNullException("model");
     try
     {
         ErrMsg = null; TID = Guid.NewGuid();
         using (var ctx = new EvaluationSysEntities())
         {
             if (model.TID == Guid.Empty)
             {
                 ctx.EmailTemplate.Add(new EmailTemplate
                 {
                     Id = TID,
                     EmailHead = model.EmailHead,
                     EmailContent = model.EmailTemplet,
                     CreateTime = DateTime.Now
                 });
             }
             else
             {
                 var query = ctx.EmailTemplate.FirstOrDefault(f => f.Id == model.TID);
                 if (query == null) throw new Exception("不正确的模板ID");
                 query.EmailHead = model.EmailHead ?? "";
                 query.EmailContent = model.EmailTemplet ?? "";
                 query.CreateTime = DateTime.Now;
             }
             return ctx.SaveChanges() >= 0;
         }
     }
     catch (Exception ex)
     {
         TID = Guid.Empty;
         ErrMsg = ex.GetBaseException().Message;
         return false;
     }
 }
 public AssessViewModels GetRelationList()
 {
     try
     {
         using (var ctx = new EvaluationSysEntities())
         {
             var query = (from c in ctx.Typedefs
                          where c.PID == ProjectId
                          && c.ProjectMng.Status >= 0
                          && c.Type == "relation"
                          orderby c.CreateTime ascending
                          select c.Name).ToList();
             defaultModel.RelationList = query;
             return defaultModel;
         }
     }
     catch (Exception ex)
     {
         errmsg = ex.GetBaseException().Message;
         throw ex;
     }
 }
 public bool DeleteAssess(IEnumerable<int> Ids, out string ErrMsg)
 {
     ErrMsg = null;
     try
     {
         using (var ctx = new EvaluationSysEntities())
         {
             var dels = (from c in ctx.AssessObj
                         where Ids.Contains(c.Id) && c.PID == ProjectId
                         select c).ToList();
             var subs = (from c in ctx.SubjectiveItems
                         where Ids.Contains(c.AssessId) && c.PID == ProjectId
                         select c).ToList();
             subs.ForEach(e => ctx.Entry(e).State = System.Data.Entity.EntityState.Deleted);
             dels.ForEach(e => ctx.Entry(e).State = System.Data.Entity.EntityState.Deleted);
             ctx.SubjectiveItems.RemoveRange(subs);
             ctx.AssessObj.RemoveRange(dels);
             return ctx.SaveChanges() >= 0;
         }
     }
     catch (Exception ex)
     {
         ErrMsg = ex.GetBaseException().Message;
         return false;
     }
 }
 public IEnumerable<AssessViewModels> GetAssessList(int PageIndex, int PageCount, out int TotalCount, string SearchStr = "")
 {
     TotalCount = 0;
     try
     {
         using (var ctx = new EvaluationSysEntities())
         {
             var query = ctx.AssessObj.Where(w => w.PID == ProjectId && w.ProjectMng.Status >= 0 && w.Status >= -1);
             if (!string.IsNullOrEmpty(SearchStr))
             {
                 query = query.Where(w => w.UserInfo.UserName.Contains(SearchStr) || w.UserInfo1.UserName.Contains(SearchStr));
             }
             var assess = query.OrderByDescending(o => o.SysEndTime).Select(c => new AssessViewModels
             {
                 AssessId = c.Id,
                 IsUserId = c.IsUserID ?? Guid.Empty,
                 UserId = c.UserID ?? Guid.Empty,
                 UserName = c.UserInfo.UserName,
                 IsUserName = c.UserInfo1.UserName,
                 PaperId = c.TestPageID ?? 0,
                 PaperName = c.TestPage.Name,
                 Relation = c.Bind,
                 SysEndTime = c.SysEndTime ?? defaultTime,
                 Status = c.Status
             }).Paging(PageIndex, PageCount, out TotalCount).ToList();
             int i = (PageIndex - 1) * PageCount;
             assess.ForEach(a => { a.RecordNum = ++i; });
             return assess;
         }
     }
     catch (Exception ex)
     {
         errmsg = ex.GetBaseException().Message;
         throw ex;
     }
 }