public List <StudentScore> Read()
        {
            #region 讀取成績計算規則。
            IStatusReporter Rep = Reporter;
            Rep.Feedback("讀取成績計算規則...", 0);

            UniqueSet <string> ruleids = new UniqueSet <string>();
            foreach (StudentScore each in Students)
            {
                if (!string.IsNullOrEmpty(each.RefCalculationRuleID))
                {
                    if (!ruleids.Contains(each.RefCalculationRuleID))
                    {
                        ruleids.Add(each.RefCalculationRuleID);
                    }
                }

                JHClassRecord cr = each.Class;
                if (cr != null)
                {
                    if (string.IsNullOrEmpty(cr.RefScoreCalcRuleID))
                    {
                        continue;
                    }

                    if (!ruleids.Contains(cr.RefScoreCalcRuleID))
                    {
                        ruleids.Add(cr.RefScoreCalcRuleID);
                    }
                }
            }

            FunctionSpliter <string, JHScoreCalcRuleRecord> spliter = new FunctionSpliter <string, JHScoreCalcRuleRecord>(10, Util.MaxThread);
            spliter.Function = delegate(List <string> idsPart)
            {
                return(JHScoreCalcRule.SelectByIDs(idsPart));
            };
            spliter.ProgressChange = delegate(int progress)
            {
                Rep.Feedback("讀取成績計算規則...", Util.CalculatePercentage(ruleids.Count, progress));
            };
            StudentScore.SetRuleMapping(spliter.Execute(ruleids.ToList()));

            List <StudentScore> noRule = new List <StudentScore>();
            foreach (StudentScore each in Students)
            {
                if (each.CalculationRule == null)
                {
                    noRule.Add(each);
                }
            }
            return(noRule);

            #endregion
        }
示例#2
0
        /// <summary>
        /// 取得成績計算規則轉成計算器
        /// </summary>
        public static void LoadtmpScoreCalculatorDict()
        {
            tmpScoreCalculatorDict.Clear();

            foreach (JHScoreCalcRuleRecord rec in JHScoreCalcRule.SelectAll())
            {
                ScoreCalculator sc = new ScoreCalculator(rec);
                if (sc != null)
                {
                    tmpScoreCalculatorDict.Add(rec.ID, sc);
                }
            }
        }
示例#3
0
 public Report()
 {
     Template = new Workbook();
     //Template.Open(new MemoryStream(Prc.班級評量成績單B4));
     DefaultCalc = new JHSchool.Evaluation.Calculation.ScoreCalculator(null);
     Calcs       = new Dictionary <string, JHSchool.Evaluation.Calculation.ScoreCalculator>();
     foreach (var record in JHScoreCalcRule.SelectAll())
     {
         if (!Calcs.ContainsKey(record.ID))
         {
             Calcs.Add(record.ID, new JHSchool.Evaluation.Calculation.ScoreCalculator(record));
         }
     }
 }
        public static void Calculate(List <StudentRecord> students)
        {
            const string LearnDomain = "學習領域";
            const string CourseLearn = "課程學習";

            ScoreCalcRule.Instance.SyncAllBackground();
            //SemesterScore.Instance.SyncAllBackground();
            Dictionary <string, List <JHSemesterScoreRecord> > studentSemesterScoreRecordCache = new Dictionary <string, List <JHSchool.Data.JHSemesterScoreRecord> >();

            foreach (JHSemesterScoreRecord record in JHSemesterScore.SelectByStudentIDs(students.AsKeyList()))
            {
                if (!studentSemesterScoreRecordCache.ContainsKey(record.RefStudentID))
                {
                    studentSemesterScoreRecordCache.Add(record.RefStudentID, new List <JHSchool.Data.JHSemesterScoreRecord>());
                }
                studentSemesterScoreRecordCache[record.RefStudentID].Add(record);
            }

            List <GradScoreRecordEditor> editors = new List <GradScoreRecordEditor>();

            BackgroundWorker worker = new BackgroundWorker();

            worker.WorkerReportsProgress = true;

            MultiThreadBackgroundWorker <GradScoreRecordEditor> multiWorker = new MultiThreadBackgroundWorker <GradScoreRecordEditor>();

            multiWorker.WorkerReportsProgress = true;
            multiWorker.AutoReportsProgress   = true;
            multiWorker.PackageSize           = 50;
            multiWorker.Loading = MultiThreadLoading.Light;

            worker.DoWork += delegate
            {
                Dictionary <string, ScoreCalculator> calc = new Dictionary <string, ScoreCalculator>();

                double studentTotal = students.Count;
                double studentCount = 0;

                foreach (StudentRecord student in students)
                {
                    studentCount++;

                    #region 取得成績計算規則
                    string calcID = string.Empty;
                    ScoreCalcRuleRecord calcRecord = student.GetScoreCalcRuleRecord();
                    if (calcRecord != null)
                    {
                        calcID = calcRecord.ID;
                        if (!calc.ContainsKey(calcID))
                        {
                            JHScoreCalcRuleRecord        record = null;
                            List <JHScoreCalcRuleRecord> list   = JHScoreCalcRule.SelectByIDs(new string[] { calcRecord.ID });
                            if (list.Count > 0)
                            {
                                record = list[0];
                            }
                            calc.Add(calcID, new ScoreCalculator(record));
                        }
                    }
                    else
                    {
                        if (!calc.ContainsKey(string.Empty))
                        {
                            calc.Add(string.Empty, new ScoreCalculator(null));
                        }
                    }
                    #endregion

                    #region 取得各學期成績
                    List <JHSemesterScoreRecord> semesterScoreRecordList;
                    if (studentSemesterScoreRecordCache.ContainsKey(student.ID))
                    {
                        semesterScoreRecordList = studentSemesterScoreRecordCache[student.ID];
                    }
                    else
                    {
                        semesterScoreRecordList = new List <JHSemesterScoreRecord>();
                    }
                    Dictionary <string, List <decimal> > domainScores = new Dictionary <string, List <decimal> >();

                    foreach (JHSemesterScoreRecord record in semesterScoreRecordList)
                    {
                        foreach (K12.Data.DomainScore domain in record.Domains.Values)
                        {
                            if (!domainScores.ContainsKey(domain.Domain))
                            {
                                domainScores.Add(domain.Domain, new List <decimal>());
                            }

                            if (domain.Score.HasValue)
                            {
                                domainScores[domain.Domain].Add(domain.Score.Value);
                            }
                        }

                        if (!domainScores.ContainsKey(LearnDomain))
                        {
                            domainScores.Add(LearnDomain, new List <decimal>());
                        }
                        if (record.LearnDomainScore.HasValue)
                        {
                            domainScores[LearnDomain].Add(record.LearnDomainScore.Value);
                        }

                        if (!domainScores.ContainsKey(CourseLearn))
                        {
                            domainScores.Add(CourseLearn, new List <decimal>());
                        }
                        if (record.CourseLearnScore.HasValue)
                        {
                            domainScores[CourseLearn].Add(record.CourseLearnScore.Value);
                        }
                    }
                    #endregion

                    #region 產生畢業成績資料
                    GradScoreRecordEditor editor;
                    GradScoreRecord       gradScoreRecord = GradScore.Instance.Items[student.ID];
                    if (gradScoreRecord != null)
                    {
                        editor = gradScoreRecord.GetEditor();
                    }
                    else
                    {
                        editor = new GradScoreRecordEditor(student);
                    }

                    editor.LearnDomainScore = null;
                    editor.CourseLearnScore = null;
                    editor.Domains.Clear();

                    foreach (string domain in domainScores.Keys)
                    {
                        decimal total = 0;
                        decimal count = domainScores[domain].Count;

                        if (count <= 0)
                        {
                            continue;
                        }

                        foreach (decimal score in domainScores[domain])
                        {
                            total += score;
                        }

                        total = total / count;
                        total = calc[calcID].ParseGraduateScore(total);


                        if (domain == LearnDomain)
                        {
                            editor.LearnDomainScore = total;
                        }
                        else if (domain == CourseLearn)
                        {
                            editor.CourseLearnScore = total;
                        }
                        else
                        {
                            if (!editor.Domains.ContainsKey(domain))
                            {
                                editor.Domains.Add(domain, new GradDomainScore(domain));
                            }
                            editor.Domains[domain].Score = total;
                        }
                    }

                    editors.Add(editor);
                    #endregion

                    worker.ReportProgress((int)(studentCount * 100 / studentTotal));
                }
            };
            worker.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e)
            {
                FISCA.Presentation.MotherForm.SetStatusBarMessage("計算畢業成績中", e.ProgressPercentage);
            };
            worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
            {
                if (e.Error != null)
                {
                    MsgBox.Show("計算畢業成績時發生錯誤。" + e.Error.Message);
                    editors.Clear();
                }
                else
                {
                    multiWorker.RunWorkerAsync(editors);
                }
            };

            multiWorker.DoWork += delegate(object sender, PackageDoWorkEventArgs <GradScoreRecordEditor> e)
            {
                IEnumerable <GradScoreRecordEditor> list = e.Items;
                list.SaveAllEditors();
            };
            multiWorker.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e)
            {
                FISCA.Presentation.MotherForm.SetStatusBarMessage("上傳畢業成績中", e.ProgressPercentage);
            };
            multiWorker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
            {
                if (e.Error != null)
                {
                    MsgBox.Show("上傳畢業成績時發生錯誤。" + e.Error.Message);
                }
                else
                {
                    FISCA.Presentation.MotherForm.SetStatusBarMessage("上傳畢業成績完成");
                }
            };

            worker.RunWorkerAsync();
        }
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            double total = _config.Students.Count;
            double count = 0;

            _worker.ReportProgress(0);

            List <string> student_ids = new List <string>();

            foreach (JHStudentRecord item in _config.Students)
            {
                student_ids.Add(item.ID);
            }

            #region 快取資料
            //獎勵
            Dictionary <string, List <JHMeritRecord> > meritCache = new Dictionary <string, List <JHMeritRecord> >();
            foreach (JHMeritRecord record in JHMerit.SelectByStudentIDs(student_ids))
            {
                if (record.OccurDate < _config.StartDate)
                {
                    continue;
                }
                if (record.OccurDate > _config.EndDate)
                {
                    continue;
                }

                if (!meritCache.ContainsKey(record.RefStudentID))
                {
                    meritCache.Add(record.RefStudentID, new List <JHMeritRecord>());
                }
                meritCache[record.RefStudentID].Add(record);
            }

            //懲戒
            Dictionary <string, List <JHDemeritRecord> > demeritCache = new Dictionary <string, List <JHDemeritRecord> >();
            foreach (JHDemeritRecord record in JHDemerit.SelectByStudentIDs(student_ids))
            {
                if (record.OccurDate < _config.StartDate)
                {
                    continue;
                }
                if (record.OccurDate > _config.EndDate)
                {
                    continue;
                }

                if (!demeritCache.ContainsKey(record.RefStudentID))
                {
                    demeritCache.Add(record.RefStudentID, new List <JHDemeritRecord>());
                }
                demeritCache[record.RefStudentID].Add(record);
            }

            //缺曠
            Dictionary <string, List <JHAttendanceRecord> > attendanceCache = new Dictionary <string, List <JHAttendanceRecord> >();
            foreach (JHAttendanceRecord record in JHAttendance.SelectByStudentIDs(student_ids))
            {
                if (record.OccurDate < _config.StartDate)
                {
                    continue;
                }
                if (record.OccurDate > _config.EndDate)
                {
                    continue;
                }

                if (!attendanceCache.ContainsKey(record.RefStudentID))
                {
                    attendanceCache.Add(record.RefStudentID, new List <JHAttendanceRecord>());
                }
                attendanceCache[record.RefStudentID].Add(record);
            }

            List <string> course_ids = new List <string>();
            foreach (JHSCAttendRecord record in JHSCAttend.SelectByStudentIDs(student_ids))
            {
                if (!course_ids.Contains(record.RefCourseID))
                {
                    course_ids.Add(record.RefCourseID);
                }
            }

            //課程
            JHCourse.RemoveAll();
            int schoolYear = _config.SchoolYear;
            int semester   = _config.Semester;
            Dictionary <string, JHCourseRecord> courseCache = new Dictionary <string, JHCourseRecord>();
            foreach (JHCourseRecord record in JHCourse.SelectByIDs(course_ids))
            {
                if ("" + record.SchoolYear != "" + schoolYear)
                {
                    continue;
                }
                if ("" + record.Semester != "" + semester)
                {
                    continue;
                }

                // 過濾使用者所選課程才放入
                if (Global._selectCourseIDList.Contains(record.ID))
                {
                    if (!courseCache.ContainsKey(record.ID))
                    {
                        courseCache.Add(record.ID, record);
                    }
                }
            }

            //修課記錄
            Dictionary <string, List <string> > scCache = new Dictionary <string, List <string> >();
            //foreach (JHSCAttendRecord sc in JHSCAttend.Select(student_ids, course_ids, new string[] { }, "" + _config.SchoolYear, "" + _config.Semester))
            foreach (JHSCAttendRecord sc in JHSCAttend.SelectByStudentIDAndCourseID(student_ids, course_ids))
            {
                if (!courseCache.ContainsKey(sc.RefCourseID))
                {
                    continue;
                }

                if (!scCache.ContainsKey(sc.RefStudentID))
                {
                    scCache.Add(sc.RefStudentID, new List <string>());
                }

                // 過濾使用者不選
                if (Global._selectCourseIDList.Contains(sc.RefCourseID))
                {
                    scCache[sc.RefStudentID].Add(sc.RefCourseID);
                }
            }

            //評量成績
            Dictionary <string, List <HC.JHSCETakeRecord> > sceScoreCache = new Dictionary <string, List <HC.JHSCETakeRecord> >();
            foreach (JHSCETakeRecord record in JHSCETake.SelectByStudentAndCourse(student_ids, course_ids))
            {
                if (record.RefExamID != _config.Exam.ID)
                {
                    continue;
                }

                if (!sceScoreCache.ContainsKey(record.RefStudentID))
                {
                    sceScoreCache.Add(record.RefStudentID, new List <HC.JHSCETakeRecord>());
                }
                sceScoreCache[record.RefStudentID].Add(new HC.JHSCETakeRecord(record));
            }

            //學期歷程
            Dictionary <string, K12.Data.SemesterHistoryItem> historyCache = new Dictionary <string, K12.Data.SemesterHistoryItem>();
            foreach (JHSemesterHistoryRecord record in JHSemesterHistory.SelectByStudentIDs(student_ids))
            {
                foreach (K12.Data.SemesterHistoryItem item in record.SemesterHistoryItems)
                {
                    if ("" + item.SchoolYear != K12.Data.School.DefaultSchoolYear)
                    {
                        continue;
                    }
                    if ("" + item.Semester != K12.Data.School.DefaultSemester)
                    {
                        continue;
                    }

                    if (!historyCache.ContainsKey(record.RefStudentID))
                    {
                        historyCache.Add(record.RefStudentID, item);
                    }
                }
            }

            //取得所有教師,為了Cache下來
            JHTeacher.SelectAll();
            #endregion

            #region 建立節次對照及假別列表
            Dictionary <string, string> periodMapping = new Dictionary <string, string>();
            foreach (JHPeriodMappingInfo info in JHPeriodMapping.SelectAll())
            {
                if (!periodMapping.ContainsKey(info.Name))
                {
                    periodMapping.Add(info.Name, info.Type);
                }
            }

            List <string> absenceList = new List <string>();
            foreach (JHAbsenceMappingInfo info in JHAbsenceMapping.SelectAll())
            {
                absenceList.Add(info.Name);
            }
            #endregion

            #region 判斷要列印的領域科目
            Dictionary <string, bool>           domains  = new Dictionary <string, bool>();
            Dictionary <string, List <string> > subjects = new Dictionary <string, List <string> >();

            List <JHCourseRecord> courseList = new List <JHCourseRecord>(courseCache.Values);
            courseList.Sort(delegate(JHCourseRecord x, JHCourseRecord y)
            {
                return(JHSchool.Evaluation.Subject.CompareSubjectOrdinal(x.Subject, y.Subject));
                //List<string> list = new List<string>(new string[] { "國語文", "國文", "英文", "英語", "數學", "歷史", "地理", "公民", "理化", "生物" });
                //int ix = list.IndexOf(x.Subject);
                //int iy = list.IndexOf(y.Subject);

                //if (ix >= 0 && iy >= 0)
                //    return ix.CompareTo(iy);
                //else if (ix >= 0)
                //    return -1;
                //else if (iy >= 0)
                //    return 1;
                //else
                //    return x.Subject.CompareTo(y.Subject);
            });

            string domainSubjectSetup = _rc.GetString("領域科目設定", "Domain");
            _config.DomainSubjectSetup = domainSubjectSetup;

            if (domainSubjectSetup == "Domain")
            {
                foreach (var domain in JHSchool.Evaluation.Subject.Domains)
                {
                    domains.Add(domain, true);
                }
                //domains.Add("彈性課程", false);

                if (domains.ContainsKey("語文"))
                {
                    domains["語文"] = false;
                }
                if (!domains.ContainsKey(""))
                {
                    domains.Add("", false);
                }
            }
            else if (domainSubjectSetup == "Subject")
            {
                foreach (var domain in JHSchool.Evaluation.Subject.Domains)
                {
                    domains.Add(domain, false);
                }
                //domains.Add("彈性課程", false);
                if (!domains.ContainsKey(""))
                {
                    domains.Add("", false);
                }
            }
            else
            {
                throw new Exception("請重新儲存一次列印設定");
            }

            foreach (var domain in JHSchool.Evaluation.Subject.Domains)
            {
                subjects.Add(domain, new List <string>());
            }
            //subjects.Add("彈性課程", new List<string>());
            subjects.Add("", new List <string>());

            //foreach (JHCourseRecord course in courseList)
            //{
            //    if (!domains.ContainsKey(course.Domain)) continue;

            //    if (!subjects.ContainsKey(course.Domain))
            //        subjects.Add(course.Domain, new List<string>());

            //    //很怪
            //    if (domains[course.Domain] == true) continue;

            //    if (!subjects[course.Domain].Contains(course.Subject))
            //        subjects[course.Domain].Add(course.Subject);
            //}

            _config.SetPrintDomains(domains);
            _config.SetPrintSubjects(subjects);
            #endregion

            DocumentBuilder templateBuilder = new DocumentBuilder(_template);

            #region 判斷是否列印文字評語

            templateBuilder.MoveToMergeField("文字評語");
            if (_rc.GetBoolean("列印文字評語", true))
            {
                templateBuilder.Write("文字評語");
            }
            else
            {
                Cell   first = templateBuilder.CurrentParagraph.ParentNode as Cell;
                double width = first.CellFormat.Width;
                Table  table = first.ParentRow.ParentTable;
                foreach (Row row in table.Rows)
                {
                    if (row.ChildNodes.Count == 1)
                    {
                        break;
                    }
                    row.RemoveChild(row.LastCell);
                    int lastIndex = row.ChildNodes.Count - 1;
                    row.Cells[lastIndex--].CellFormat.Width += (width / 3f);
                    row.Cells[lastIndex--].CellFormat.Width += (width / 3f);
                    row.Cells[lastIndex].CellFormat.Width   += (width / 3f);
                }
            }
            #endregion

            #region 依節權數設定,在畫面上顯示
            string pcDisplay = string.Empty;
            bool   p         = _rc.GetBoolean("列印節數", false);
            bool   c         = _rc.GetBoolean("列印權數", false);
            if (p && c)
            {
                pcDisplay = "節/權數";
            }
            else if (p)
            {
                pcDisplay = "節數";
            }
            else if (c)
            {
                pcDisplay = "權數";
            }

            while (templateBuilder.MoveToMergeField("節權數"))
            {
                templateBuilder.Write(pcDisplay);
            }
            #endregion

            #region 如果使用者不印定期評量,從畫面上將欄位拿掉
            templateBuilder.MoveToMergeField("定期評量");

            if (_rc.GetBoolean("列印定期評量", false) == false)
            {
                Cell   assignmentCell = templateBuilder.CurrentParagraph.ParentNode as Cell;
                double width          = assignmentCell.CellFormat.Width;
                bool   hasText        = false;
                if (assignmentCell.NextSibling != null)
                {
                    hasText = true;
                }
                Table scoreTable = assignmentCell.ParentRow.ParentTable;
                foreach (Row eachRow in scoreTable.Rows)
                {
                    if (eachRow.Cells.Count == 1)
                    {
                        break;
                    }

                    int lastIndex = 0;
                    if (hasText)
                    {
                        eachRow.RemoveChild(eachRow.Cells[eachRow.Count - 3]);
                        lastIndex = eachRow.ChildNodes.Count - 3;
                    }
                    else
                    {
                        eachRow.RemoveChild(eachRow.LastCell);
                        lastIndex = eachRow.ChildNodes.Count - 1;
                    }
                    eachRow.Cells[lastIndex--].CellFormat.Width += (width / 2f);
                    eachRow.Cells[lastIndex].CellFormat.Width   += (width / 2f);
                }
            }
            else
            {
                templateBuilder.Write("定期評量");
            }
            #endregion


            #region 如果使用者不印平時評量,從畫面上將欄位拿掉
            templateBuilder.MoveToMergeField("平時評量");

            if (_rc.GetBoolean("列印平時評量", false) == false)
            {
                Cell   assignmentCell = templateBuilder.CurrentParagraph.ParentNode as Cell;
                double width          = assignmentCell.CellFormat.Width;
                bool   hasText        = false;
                if (assignmentCell.NextSibling != null)
                {
                    hasText = true;
                }
                Table scoreTable = assignmentCell.ParentRow.ParentTable;
                foreach (Row eachRow in scoreTable.Rows)
                {
                    if (eachRow.Cells.Count == 1)
                    {
                        break;
                    }

                    int lastIndex = 0;
                    if (hasText)
                    {
                        eachRow.RemoveChild(eachRow.Cells[eachRow.Count - 2]);
                        lastIndex = eachRow.ChildNodes.Count - 2;
                    }
                    else
                    {
                        eachRow.RemoveChild(eachRow.LastCell);
                        lastIndex = eachRow.ChildNodes.Count - 1;
                    }
                    eachRow.Cells[lastIndex--].CellFormat.Width += (width / 2f);
                    eachRow.Cells[lastIndex].CellFormat.Width   += (width / 2f);
                }
            }
            else
            {
                templateBuilder.Write("平時評量");
            }
            #endregion

            #region 如果使用者不印定期學習評量總成績,從畫面上將欄位拿掉
            templateBuilder.MoveToMergeField("定期學習評量總成績");

            if (_rc.GetBoolean("列印定期學習評量總成績", false) == false)
            {
                Cell   assignmentCell = templateBuilder.CurrentParagraph.ParentNode as Cell;
                double width          = assignmentCell.CellFormat.Width;
                bool   hasText        = false;
                if (assignmentCell.NextSibling != null)
                {
                    hasText = true;
                }
                Table scoreTable = assignmentCell.ParentRow.ParentTable;
                foreach (Row eachRow in scoreTable.Rows)
                {
                    if (eachRow.Cells.Count == 1)
                    {
                        break;
                    }

                    int lastIndex = 0;
                    if (hasText)
                    {
                        eachRow.RemoveChild(eachRow.Cells[eachRow.Count - 2]);
                        lastIndex = eachRow.ChildNodes.Count - 2;
                    }
                    else
                    {
                        eachRow.RemoveChild(eachRow.LastCell);
                        lastIndex = eachRow.ChildNodes.Count - 1;
                    }
                    eachRow.Cells[lastIndex--].CellFormat.Width += (width / 2f);
                    eachRow.Cells[lastIndex].CellFormat.Width   += (width / 2f);
                }
            }
            else
            {
                templateBuilder.Write("定期學習評量總成績");
            }
            #endregion


            #region 取得學生成績計算規則
            ScoreCalculator defaultScoreCalculator = new ScoreCalculator(null);

            //key: ScoreCalcRuleID
            Dictionary <string, ScoreCalculator> calcCache = new Dictionary <string, ScoreCalculator>();
            //key: StudentID, val: ScoreCalcRuleID
            Dictionary <string, string> calcIDCache = new Dictionary <string, string>();
            List <string> scoreCalcRuleIDList       = new List <string>();
            foreach (JHStudentRecord student in _config.Students)
            {
                //calcCache.Add(student.ID, new ScoreCalculator(student.ScoreCalcRule));
                string calcID = string.Empty;
                if (!string.IsNullOrEmpty(student.OverrideScoreCalcRuleID))
                {
                    calcID = student.OverrideScoreCalcRuleID;
                }
                else if (student.Class != null && !string.IsNullOrEmpty(student.Class.RefScoreCalcRuleID))
                {
                    calcID = student.Class.RefScoreCalcRuleID;
                }

                if (!string.IsNullOrEmpty(calcID))
                {
                    calcIDCache.Add(student.ID, calcID);
                }
            }
            foreach (JHScoreCalcRuleRecord record in JHScoreCalcRule.SelectByIDs(calcIDCache.Values))
            {
                if (!calcCache.ContainsKey(record.ID))
                {
                    calcCache.Add(record.ID, new ScoreCalculator(record));
                }
            }
            //MsgBox.Show("" + (Environment.TickCount - t));
            #endregion

            #region 檢查學生成績是否超出可列印行數

            foreach (JHStudentRecord student in _config.Students)
            {
                if (scCache.ContainsKey(student.ID))
                {
                    int checkCount = 0;
                    if (_config.DomainSubjectSetup == "Subject")
                    {
                        checkCount = scCache[student.ID].Count;
                    }
                    else
                    {
                        List <string> checkDomains = new List <string>();
                        foreach (string courseID in scCache[student.ID])
                        {
                            JHCourseRecord course = courseCache[courseID];
                            if (string.IsNullOrEmpty(course.Domain))
                            {
                                checkCount++;
                            }
                            else if (!checkDomains.Contains(course.Domain))
                            {
                                checkDomains.Add(course.Domain);
                            }
                        }
                        checkCount += checkDomains.Count;
                    }

                    if (checkCount > _rowCount)
                    {
                        _overStudentList.Add(student.ID);
                    }
                }
            }

            //有學生資料超出範圍
            if (_overStudentList.Count > 0)
            {
                //K12.Presentation.NLDPanels.Student.AddToTemp(overStudentList);
                System.Windows.Forms.DialogResult result = MsgBox.Show("有 " + _overStudentList.Count + " 位學生評量成績資料超出範本可列印範圍,已將學生加入待處理。\n是否繼續列印?", System.Windows.Forms.MessageBoxButtons.YesNo);
                if (result == System.Windows.Forms.DialogResult.No)
                {
                    e.Result = "Cancel";
                }
            }
            #endregion

            // 取得學生課程ID對照
            Dictionary <string, List <string> > studCourseID = new Dictionary <string, List <string> >();
            List <string> sid = (from stud in _config.Students select stud.ID).ToList();
            foreach (JHSCAttendRecord attend in JHSCAttend.SelectByStudentIDs(sid))
            {
                if (attend.Course.SchoolYear.HasValue && attend.Course.Semester.HasValue)
                {
                    if (attend.Course.SchoolYear == _config.SchoolYear && attend.Course.Semester == _config.Semester)
                    {
                        if (studCourseID.ContainsKey(attend.RefStudentID))
                        {
                            studCourseID[attend.RefStudentID].Add(attend.RefCourseID);
                        }
                        else
                        {
                            List <string> coid = new List <string>();
                            coid.Add(attend.RefCourseID);
                            studCourseID.Add(attend.RefStudentID, coid);
                        }
                    }
                }
            }

            // 取得學期歷程
            Config._StudSemesterHistoryItemDict.Clear();

            List <JHSemesterHistoryRecord> semHisRec = JHSemesterHistory.SelectByStudents(_config.Students);
            // 當畫面學期歷程內的學年度學期與畫面上設定相同,加入
            foreach (JHSemesterHistoryRecord rec in semHisRec)
            {
                foreach (K12.Data.SemesterHistoryItem shi in rec.SemesterHistoryItems)
                {
                    if (shi.SchoolYear == _config.SchoolYear && shi.Semester == _config.Semester)
                    {
                        if (!Config._StudSemesterHistoryItemDict.ContainsKey(shi.RefStudentID))
                        {
                            Config._StudSemesterHistoryItemDict.Add(shi.RefStudentID, shi);
                        }
                    }
                }
            }

            // 取得評量比例
            Utility.ScorePercentageHSDict.Clear();
            Utility.ScorePercentageHSDict = Utility.GetScorePercentageHS();


            #region 產生
            foreach (JHStudentRecord student in _config.Students)
            {
                count++;
                if (_overStudentList.Contains(student.ID))
                {
                    continue;
                }
                Document        each    = (Document)_template.Clone(true);
                DocumentBuilder builder = new DocumentBuilder(each);

                #region 學生基本資料
                StudentBasicInfo basicInfo = new StudentBasicInfo(builder);
                basicInfo.SetStudent(student);
                #endregion

                #region 班導師
                builder.MoveToMergeField("班導師");
                if (historyCache.ContainsKey(student.ID))
                {
                    builder.Write(historyCache[student.ID].Teacher);
                }
                else
                {
                    builder.Write(string.Empty);
                }
                #endregion

                #region 成績
                List <HC.JHSCETakeRecord> sceScoreList = null;
                if (sceScoreCache.ContainsKey(student.ID))
                {
                    sceScoreList = sceScoreCache[student.ID];
                }
                else
                {
                    sceScoreList = new List <HC.JHSCETakeRecord>();
                }
                ScoreCalculator studentCalculator = defaultScoreCalculator;
                if (calcIDCache.ContainsKey(student.ID) && calcCache.ContainsKey(calcIDCache[student.ID]))
                {
                    studentCalculator = calcCache[calcIDCache[student.ID]];
                }

                // 過濾 courseCache studid
                Dictionary <string, JHCourseRecord> courseCache1 = new Dictionary <string, JHCourseRecord>();

                foreach (KeyValuePair <string, JHCourseRecord> val in courseCache)
                {
                    // 從學生修課來對應到課程
                    if (studCourseID.ContainsKey(student.ID))
                    {
                        if (studCourseID[student.ID].Contains(val.Value.ID))
                        {
                            courseCache1.Add(val.Key, val.Value);
                        }
                    }
                }

                StudentExamScore examScore = new StudentExamScore(builder, _config, courseCache1);
                examScore.PrintPeriod     = _rc.GetBoolean("列印節數", false);
                examScore.PrintCredit     = _rc.GetBoolean("列印權數", false);
                examScore.PrintText       = _rc.GetBoolean("列印文字評語", true);
                examScore.PrintScore      = _rc.GetBoolean("列印定期評量", true);
                examScore.PrintAssScore   = _rc.GetBoolean("列印平時評量", true);
                examScore.PrintTotalScore = _rc.GetBoolean("列印定期學習評量總成績", true);

                examScore.SetScoreCalculator(studentCalculator);
                if (scCache.ContainsKey(student.ID))
                {
                    examScore.SetSubjects(scCache[student.ID]);
                }
                examScore.SetData(sceScoreList);

                #endregion

                if (_config.DomainSubjectSetup == "Subject")
                {
                    // 科目定期評量加權平均
                    if (builder.MoveToMergeField("加權平均") || builder.MoveToMergeField("定期評量加權平均"))
                    {
                        if (examScore.SubjAvgScore > 0)
                        {
                            builder.Write(examScore.SubjAvgScore.ToString());
                        }
                        else
                        {
                            builder.Write("");
                        }
                    }

                    // 科目平時評量加權平均
                    if (builder.MoveToMergeField("平時評量加權平均"))
                    {
                        if (examScore.SubjAvgAssignmentScore > 0)
                        {
                            builder.Write(examScore.SubjAvgAssignmentScore.ToString());
                        }
                        else
                        {
                            builder.Write("");
                        }
                    }

                    // 科目學習總分加權平均
                    if (builder.MoveToMergeField("定期學習評量總成績加權平均"))
                    {
                        if (examScore.SubjAvgFinalScore > 0)
                        {
                            builder.Write(examScore.SubjAvgFinalScore.ToString());
                        }
                        else
                        {
                            builder.Write("");
                        }
                    }
                }
                else
                {
                    // 領域定期評量加權平均
                    if (builder.MoveToMergeField("加權平均") || builder.MoveToMergeField("定期評量加權平均"))
                    {
                        if (examScore.DomainAvgScore > 0)
                        {
                            builder.Write(examScore.DomainAvgScore.ToString());
                        }
                        else
                        {
                            builder.Write("");
                        }
                    }

                    // 領域平時評量加權平均
                    if (builder.MoveToMergeField("平時評量加權平均"))
                    {
                        if (examScore.DomainAvgAssignmentScore > 0)
                        {
                            builder.Write(examScore.DomainAvgAssignmentScore.ToString());
                        }
                        else
                        {
                            builder.Write("");
                        }
                    }

                    // 領域學習總分加權平均
                    if (builder.MoveToMergeField("定期學習評量總成績加權平均"))
                    {
                        if (examScore.DomainAvgFinalScore > 0)
                        {
                            builder.Write(examScore.DomainAvgFinalScore.ToString());
                        }
                        else
                        {
                            builder.Write("");
                        }
                    }
                }

                #region 日常表現
                List <JHMeritRecord>      meritList      = null;
                List <JHDemeritRecord>    demeritList    = null;
                List <JHAttendanceRecord> attendanceList = null;

                meritList      = (meritCache.ContainsKey(student.ID)) ? meritCache[student.ID] : new List <JHMeritRecord>();
                demeritList    = (demeritCache.ContainsKey(student.ID)) ? demeritCache[student.ID] : new List <JHDemeritRecord>();
                attendanceList = (attendanceCache.ContainsKey(student.ID)) ? attendanceCache[student.ID] : new List <JHAttendanceRecord>();

                StudentMoralScore moral = new StudentMoralScore(builder, _config, periodMapping, absenceList);
                moral.SetData(meritList, demeritList, attendanceList);
                #endregion

                foreach (Section sec in each.Sections)
                {
                    _doc.Sections.Add(_doc.ImportNode(sec, true));
                }

                //回報進度
                _worker.ReportProgress((int)(count * 100.0 / total));
            }

            List <string> globalFieldName  = new List <string>();
            List <object> globalFieldValue = new List <object>();

            globalFieldName.Add("學校名稱");
            globalFieldValue.Add(K12.Data.School.ChineseName);

            globalFieldName.Add("學年度");
            globalFieldValue.Add(_config.SchoolYear);

            globalFieldName.Add("學期");
            globalFieldValue.Add(_config.Semester);

            globalFieldName.Add("評量名稱");
            globalFieldValue.Add(_config.Exam.Name);

            globalFieldName.Add("統計期間");
            globalFieldValue.Add(_config.StartDate.ToShortDateString() + " ~ " + _config.EndDate.ToShortDateString());

            globalFieldName.Add("列印日期");
            globalFieldValue.Add(DateConvert.CDate(DateTime.Now.ToString("yyyy/MM/dd")) + " " + DateTime.Now.ToString("HH:mm:ss"));

            string chancellor, eduDirector, stuDirector;
            chancellor = eduDirector = stuDirector = string.Empty;

            XmlElement schoolInfo         = K12.Data.School.Configuration["學校資訊"].PreviousData;
            XmlElement chancellorElement  = (XmlElement)schoolInfo.SelectSingleNode("ChancellorChineseName");
            XmlElement eduDirectorElement = (XmlElement)schoolInfo.SelectSingleNode("EduDirectorName");

            if (chancellorElement != null)
            {
                chancellor = chancellorElement.InnerText;
            }
            if (eduDirectorElement != null)
            {
                eduDirector = eduDirectorElement.InnerText;
            }

            globalFieldName.Add("教務主任");
            globalFieldValue.Add(eduDirector);

            globalFieldName.Add("校長");
            globalFieldValue.Add(chancellor);

            globalFieldName.Add("成績校正日期");
            globalFieldValue.Add(_rc.GetString("成績校正日期", string.Empty));

            if (_config.Students.Count > _overStudentList.Count)
            {
                _doc.MailMerge.Execute(globalFieldName.ToArray(), globalFieldValue.ToArray());
            }

            #endregion
        }
示例#6
0
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            double total = Students.Count;
            double count = 0;

            _worker.ReportProgress(0);

            List <string> studentIDs = Students.Select(x => x.ID).ToList();

            #region 快取資料

            //獎勵
            // 1.依學生編號、開始日期、結束日期,取得學生獎勵紀錄
            // 2.依學生編號進行分群
            Dictionary <string, List <JHMeritRecord> > meritCache = new Dictionary <string, List <JHMeritRecord> >();
            foreach (JHMeritRecord record in JHMerit.Select(studentIDs, _config.StartDate, _config.EndDate, null, null, null, null))
            {
                if (!meritCache.ContainsKey(record.RefStudentID))
                {
                    meritCache.Add(record.RefStudentID, new List <JHMeritRecord>());
                }
                meritCache[record.RefStudentID].Add(record);
            }

            //懲戒
            // 1.依學生編號、開始日期、結束日期,取得學生懲戒紀錄
            // 2.依學生編號進行分群
            Dictionary <string, List <JHDemeritRecord> > demeritCache = new Dictionary <string, List <JHDemeritRecord> >();
            foreach (JHDemeritRecord record in JHDemerit.Select(studentIDs, _config.StartDate, _config.EndDate, null, null, null, null))
            {
                if (!demeritCache.ContainsKey(record.RefStudentID))
                {
                    demeritCache.Add(record.RefStudentID, new List <JHDemeritRecord>());
                }
                demeritCache[record.RefStudentID].Add(record);
            }

            //缺曠
            // 1.依學生編號、開始日期、結束日期,取得學生缺曠紀錄
            // 2.依學生編號進行分群
            Dictionary <string, List <JHAttendanceRecord> > attendanceCache = new Dictionary <string, List <JHAttendanceRecord> >();
            foreach (JHAttendanceRecord record in JHAttendance.Select(studentIDs, _config.StartDate, _config.EndDate, null, null, null))
            {
                if (!attendanceCache.ContainsKey(record.RefStudentID))
                {
                    attendanceCache.Add(record.RefStudentID, new List <JHAttendanceRecord>());
                }
                attendanceCache[record.RefStudentID].Add(record);
            }

            // 建立平時評量與修課成績Idx Key studentID
            Dictionary <string, List <JHSCAttendRecord> > _studAttendRecDict = new Dictionary <string, List <JHSCAttendRecord> >();


            //修課紀錄
            // 1.依學生編號、學年度、學期,取得修課紀錄
            // 2.
            List <string> courseIDs = new List <string>();
            List <string> attendIDs = new List <string>();
            Dictionary <string, List <string> > scCache = new Dictionary <string, List <string> >();
            foreach (var attend in JHSCAttend.Select(studentIDs, null, null, "" + _config.SchoolYear, "" + _config.Semester))
            {
                attendIDs.Add(attend.ID);
                if (!scCache.ContainsKey(attend.RefStudentID))
                {
                    scCache.Add(attend.RefStudentID, new List <string>());
                }
                scCache[attend.RefStudentID].Add(attend.RefCourseID);
                if (!courseIDs.Contains(attend.RefCourseID))
                {
                    courseIDs.Add(attend.RefCourseID);
                }

                // 建立評量與修課成績
                if (_studAttendRecDict.ContainsKey(attend.RefStudentID))
                {
                    _studAttendRecDict[attend.RefStudentID].Add(attend);
                }
                else
                {
                    List <JHSCAttendRecord> atten = new List <JHSCAttendRecord>();
                    atten.Add(attend);
                    _studAttendRecDict.Add(attend.RefStudentID, atten);
                }
            }

            //課程
            // 1.依課程編號取得課程紀錄
            // 2.略過不列入成績計算的課程
            JHCourse.RemoveByIDs(courseIDs);
            Dictionary <string, JHCourseRecord> courseCache = JHCourse.SelectByIDs(courseIDs).Where(x => x.CalculationFlag != "2").ToDictionary(x => x.ID);

            //試別資訊: 取得所有試別
            Dictionary <string, JHExamRecord> examCache = JHExam.SelectAll().ToDictionary(x => x.ID);

            // 取得社團ExamID
            List <string> NExamIDList = new List <string> ();
            foreach (JHExamRecord rec in JHExam.SelectAll())
            {
                if (rec.Name.IndexOf("社團") > -1)
                {
                    NExamIDList.Add(rec.ID);
                }
            }

            //評量成績
            // 1.依修課記錄及所有試別取得評量成績
            // 2.依第1點的評量成績取得試別編號 (實際學生評量成績中的試別編號)
            // 3.依學生編號進行分群
            Dictionary <string, List <KH.JHSCETakeRecord> > sceScoreCache = new Dictionary <string, List <KH.JHSCETakeRecord> >();
            List <string> validExamIDs = new List <string>();

            // 檢查有修課才讀取成績
            if (attendIDs.Count > 0 && examCache.Count > 0)
            {
                foreach (JHSCETakeRecord record in JHSCETake.Select(null, null, examCache.Keys, null, attendIDs))
                {
                    if (!NExamIDList.Contains(record.RefExamID))
                    {
                        if (!validExamIDs.Contains(record.RefExamID))
                        {
                            validExamIDs.Add(record.RefExamID);
                        }
                    }

                    if (!sceScoreCache.ContainsKey(record.RefStudentID))
                    {
                        sceScoreCache.Add(record.RefStudentID, new List <KH.JHSCETakeRecord>());
                    }
                    sceScoreCache[record.RefStudentID].Add(new KH.JHSCETakeRecord(record));
                }
            }

            //將『所有試別編號』與『實際學生評量成績中的試別編號』做交集,以取得使用管理的試別次序
            //假設『所有試別編號』為1,4,3,5
            //假設『實際學生評量成績中的試別編號』為3,4,1
            //交集後的結果為1,4,3
            validExamIDs = examCache.Keys.Intersect(validExamIDs).ToList();

            validExamIDs.Add("平時評量");
            //validExamIDs.Add("課程總成績");

            // 取得學生成績計算規則
            // 如果學生沒有計算規則一律用預設,預設進位方式取到小數點第2位
            ScoreCalculator defaultScoreCalculator = new ScoreCalculator(null);
            //key: ScoreCalcRuleID
            Dictionary <string, ScoreCalculator> calcCache = new Dictionary <string, ScoreCalculator>();
            //key: StudentID, val: ScoreCalcRuleID
            Dictionary <string, string> calcIDCache = new Dictionary <string, string>();

            List <string> scoreCalcRuleIDList = new List <string>();

            // 取得學生計算規則的ID,建立對照表
            // 如果學生身上有指定成績計算規則,就以學生身上成績計算規則為主
            // 如果學生身上沒有指定成績計算規則,就以學生所屬班級成績計算規則為主
            foreach (JHStudentRecord student in _config.Students)
            {
                string calcID = string.Empty;
                if (!string.IsNullOrEmpty(student.OverrideScoreCalcRuleID))
                {
                    calcID = student.OverrideScoreCalcRuleID;
                }
                else if (student.Class != null && !string.IsNullOrEmpty(student.Class.RefScoreCalcRuleID))
                {
                    calcID = student.Class.RefScoreCalcRuleID;
                }

                if (!string.IsNullOrEmpty(calcID))
                {
                    calcIDCache.Add(student.ID, calcID);
                }
            }
            // 取得計算規則建立成績進位器
            foreach (JHScoreCalcRuleRecord record in JHScoreCalcRule.SelectByIDs(calcIDCache.Values))
            {
                if (!calcCache.ContainsKey(record.ID))
                {
                    calcCache.Add(record.ID, new ScoreCalculator(record));
                }
            }

            #endregion


            #region 判斷領域是否需要展開
            //判斷領域是否展開對照表
            //Key:領域名稱
            //Value:false=展開,true=不展開
            //展開: 詳列該領域下所有科目成績
            //不展開: 只列該領域成績
            Dictionary <string, bool> domains = new Dictionary <string, bool>();

            DomainSubjectSetup domainSubjectSetup = _config.DomainSubjectSetup;
            //使用者設定"只列印領域"
            if (domainSubjectSetup == DomainSubjectSetup.Domain)
            {
                //預設從領域資料管理來的領域名稱皆不展開
                foreach (var domain in JHSchool.Evaluation.Subject.Domains)
                {
                    domains.Add(domain, DomainSubjectExpand.展開);
                }
                //彈性課程一定展開
                if (!domains.ContainsKey(""))
                {
                    domains.Add("", DomainSubjectExpand.展開);
                }
            }
            //使用者設定"只列印科目"
            else if (domainSubjectSetup == DomainSubjectSetup.Subject)
            {
                //預設從領域資料管理來的領域名稱皆展開
                foreach (var domain in JHSchool.Evaluation.Subject.Domains)
                {
                    domains.Add(domain, DomainSubjectExpand.展開);
                }
                //彈性課程一定展開
                if (!domains.ContainsKey(""))
                {
                    domains.Add("", DomainSubjectExpand.展開);
                }
            }
            else
            {
                throw new Exception("請重新儲存一次列印設定");
            }

            _config.PrintDomains = domains;
            #endregion

            #region 建立節次對照
            Dictionary <string, string> periodMapping = JHPeriodMapping.SelectAll().ToDictionary(x => x.Name, y => y.Type);
            #endregion

            #region 假別列表
            List <string> absenceList = JHAbsenceMapping.SelectAll().Select(x => x.Name).ToList();
            #endregion

            #region 依評量試別重新劃分範本
            //如有不懂自求多福
            int             rowCount        = 0;
            DocumentBuilder templateBuilder = new DocumentBuilder(_template);
            templateBuilder.MoveToMergeField("各次評量");
            Font   font       = templateBuilder.Font;
            Cell   examsCell  = templateBuilder.CurrentParagraph.ParentNode as Cell;
            Table  table      = examsCell.ParentRow.ParentTable;
            double width      = examsCell.CellFormat.Width;
            double examWidth  = width / (double)validExamIDs.Count;
            double scoreWidth = width / (double)validExamIDs.Count / 2.0;

            //計算有幾個 Score Row
            foreach (Row row in table.Rows)
            {
                if (row.Cells.Count > 3)
                {
                    rowCount++;
                }
            }

            #region Header Cell
            //建立評量欄位對照表
            Dictionary <string, int> columnMapping = new Dictionary <string, int>();
            int columnShift = 3;
            int columnIndex = 0;

            table.Rows[0].LastCell.Remove();
            table.Rows[1].LastCell.Remove();

            foreach (string examID in validExamIDs)
            {
                columnMapping.Add(examID, columnIndex + columnShift);

                Cell topHeaderCell = new Cell(_template);
                if (examID == "平時評量" || examID == "課程總成績")
                {
                    WordHelper.Write(topHeaderCell, font, examID);
                }
                else
                {
                    WordHelper.Write(topHeaderCell, font, examCache[examID].Name);
                }
                table.Rows[0].Cells.Add(topHeaderCell);

                Cell subHeaderCell1 = new Cell(_template);
                WordHelper.Write(subHeaderCell1, font, "分數", "評量");
                table.Rows[1].Cells.Add(subHeaderCell1);
                columnIndex++;

                Cell subHeaderCell2 = new Cell(_template);
                WordHelper.Write(subHeaderCell2, font, "努力", "程度");
                table.Rows[1].Cells.Add(subHeaderCell2);
                columnIndex++;

                topHeaderCell.CellFormat.Width  = examWidth;
                subHeaderCell1.CellFormat.Width = subHeaderCell2.CellFormat.Width = scoreWidth;

                topHeaderCell.CellFormat.VerticalAlignment  = CellVerticalAlignment.Center;
                subHeaderCell1.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
                subHeaderCell2.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
            }

            WordHelper.MergeVerticalCell(table.Rows[0].Cells[1], 2);
            #endregion

            #region Content Cell
            int shift = 2; //Header has 2 rows
            for (int i = 0; i < rowCount; i++)
            {
                table.Rows[i + shift].LastCell.Remove();

                for (int j = 0; j < validExamIDs.Count * 2; j++)
                {
                    Cell contentCell = new Cell(_template);
                    contentCell.CellFormat.Width             = scoreWidth;
                    contentCell.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;

                    table.Rows[i + shift].Cells.Add(contentCell);
                }
            }
            #endregion

            #endregion

            #region 依節權數設定,在畫面上顯示
            string pcDisplay = string.Empty;
            if (_config.PrintPeriod && _config.PrintCredit)
            {
                pcDisplay = "節/權數";
            }
            else if (_config.PrintPeriod)
            {
                pcDisplay = "節數";
            }
            else if (_config.PrintCredit)
            {
                pcDisplay = "權數";
            }

            templateBuilder.MoveToMergeField("節權數");
            templateBuilder.Write(pcDisplay);
            #endregion

            // 取得學期歷程
            Config._StudSemesterHistoryItemDict.Clear();

            List <JHSemesterHistoryRecord> semHisRec = JHSemesterHistory.SelectByStudents(Students);
            // 當畫面學期歷程內的學年度學期與畫面上設定相同,加入
            foreach (JHSemesterHistoryRecord rec in semHisRec)
            {
                foreach (K12.Data.SemesterHistoryItem shi in rec.SemesterHistoryItems)
                {
                    if (shi.SchoolYear == _config.SchoolYear && shi.Semester == _config.Semester)
                    {
                        if (!Config._StudSemesterHistoryItemDict.ContainsKey(shi.RefStudentID))
                        {
                            Config._StudSemesterHistoryItemDict.Add(shi.RefStudentID, shi);
                        }
                    }
                }
            }

            // 取得學生服務學習時數
            Config._SRDict.Clear();
            List <string> sidList = (from data in Students select data.ID).ToList();
            Config._SRDict = Utility.GetServiceLearningDetail(sidList, _config.SchoolYear, _config.Semester);


            #region 產生
            foreach (JHStudentRecord student in Students)
            {
                count++;

                Document        each    = (Document)_template.Clone(true);
                DocumentBuilder builder = new DocumentBuilder(each);

                #region 學生基本資料
                StudentBasicInfo basicInfo = new StudentBasicInfo(builder);
                basicInfo.SetStudent(student);
                #endregion


                #region 各評量成績
                List <KH.JHSCETakeRecord> sceScoreList = null;
                if (sceScoreCache.ContainsKey(student.ID))
                {
                    sceScoreList = sceScoreCache[student.ID];
                }
                else
                {
                    sceScoreList = new List <KH.JHSCETakeRecord>();
                }

                ScoreCalculator studentCalculator = defaultScoreCalculator;
                if (calcIDCache.ContainsKey(student.ID) && calcCache.ContainsKey(calcIDCache[student.ID]))
                {
                    studentCalculator = calcCache[calcIDCache[student.ID]];
                }

                // 課程成績
                Dictionary <string, JHSCAttendRecord> attendRecDict = new Dictionary <string, JHSCAttendRecord>();
                // 領域成績(平時)
                Dictionary <string, decimal?> domainScDict = new Dictionary <string, decimal?>();
                //// 領域成績(總)
                //Dictionary<string, decimal> domainScDictTT = new Dictionary<string, decimal>();

                if (_studAttendRecDict.ContainsKey(student.ID))
                {
                    foreach (JHSCAttendRecord rec in _studAttendRecDict[student.ID])
                    {
                        if (!attendRecDict.ContainsKey(rec.Course.Subject))
                        {
                            attendRecDict.Add(rec.Course.Subject, rec);
                        }
                    }


                    List <string> tName = (from xx in _studAttendRecDict[student.ID] select xx.Course.Domain).Distinct().ToList();

                    foreach (string Name in tName)
                    {
                        decimal?sc = 0, co = 0;
                        foreach (JHSCAttendRecord rec in _studAttendRecDict[student.ID])
                        {
                            if (rec.Course.Domain == Name)
                            {
                                if (rec.OrdinarilyScore.HasValue && rec.Course.Credit.HasValue)
                                {
                                    sc += (rec.OrdinarilyScore.Value * rec.Course.Credit.Value);
                                    // 有成績才算入
                                    co += rec.Course.Credit.Value;
                                }
                            }
                        }

                        if (co.HasValue && sc.HasValue)
                        {
                            if (co.Value > 0)
                            {
                                if (!domainScDict.ContainsKey(Name))
                                {
                                    domainScDict.Add(Name, (sc.Value / co.Value));
                                }
                            }
                        }
                    }
                }

                //StudentExamScore examScore = new StudentExamScore(builder, _config, courseCache, attendRecDict,domainScDict,domainScDictTT);
                StudentExamScore examScore = new StudentExamScore(builder, _config, courseCache, attendRecDict, domainScDict);
                if (scCache.ContainsKey(student.ID))
                {
                    examScore.SetSubjects(scCache[student.ID]);
                }
                examScore.SetColumnMap(columnMapping);
                examScore.SetEffortMapper(_effortMapper);
                examScore.SetCalculator(studentCalculator);
                examScore.SetData(sceScoreList);
                #endregion

                #region 缺曠獎懲
                List <JHMeritRecord>      meritList      = null;
                List <JHDemeritRecord>    demeritList    = null;
                List <JHAttendanceRecord> attendanceList = null;

                meritList      = (meritCache.ContainsKey(student.ID)) ? meritCache[student.ID] : new List <JHMeritRecord>();
                demeritList    = (demeritCache.ContainsKey(student.ID)) ? demeritCache[student.ID] : new List <JHDemeritRecord>();
                attendanceList = (attendanceCache.ContainsKey(student.ID)) ? attendanceCache[student.ID] : new List <JHAttendanceRecord>();

                StudentMoralScore moral = new StudentMoralScore(builder, _config, periodMapping, absenceList);
                moral.SetData(meritList, demeritList, attendanceList);
                #endregion

                foreach (Section sec in each.Sections)
                {
                    _doc.Sections.Add(_doc.ImportNode(sec, true));
                }

                //回報進度
                _worker.ReportProgress((int)(count * 100.0 / total));
            }

            #region 全域 MergeField
            List <string> globalFieldName  = new List <string>();
            List <object> globalFieldValue = new List <object>();

            globalFieldName.Add("學校名稱");
            globalFieldValue.Add(K12.Data.School.ChineseName);

            globalFieldName.Add("學年度");
            globalFieldValue.Add(_config.SchoolYear.ToString());
            //globalFieldValue.Add(K12.Data.School.DefaultSchoolYear);

            globalFieldName.Add("學期");
            globalFieldValue.Add(_config.Semester.ToString());
            //globalFieldValue.Add(K12.Data.School.DefaultSemester);

            globalFieldName.Add("統計期間");
            globalFieldValue.Add(_config.StartDate.ToShortDateString() + " ~ " + _config.EndDate.ToShortDateString());

            globalFieldName.Add("列印日期");
            globalFieldValue.Add(DateConvert.CDate(DateTime.Now.ToString("yyyy/MM/dd")) + " " + DateTime.Now.ToString("HH:mm:ss"));

            string chancellor, eduDirector, stuDirector;
            chancellor = eduDirector = stuDirector = string.Empty;

            XmlElement schoolInfo         = K12.Data.School.Configuration["學校資訊"].PreviousData;
            XmlElement chancellorElement  = (XmlElement)schoolInfo.SelectSingleNode("ChancellorChineseName");
            XmlElement eduDirectorElement = (XmlElement)schoolInfo.SelectSingleNode("EduDirectorName");
            XmlElement stuDirectorElement = (XmlElement)schoolInfo.SelectSingleNode("StuDirectorName");

            if (chancellorElement != null)
            {
                chancellor = chancellorElement.InnerText;
            }
            if (eduDirectorElement != null)
            {
                eduDirector = eduDirectorElement.InnerText;
            }
            if (stuDirectorElement != null)
            {
                stuDirector = stuDirectorElement.InnerText;
            }

            globalFieldName.Add("校長");
            globalFieldValue.Add(chancellor);

            globalFieldName.Add("教務主任");
            globalFieldValue.Add(eduDirector);

            globalFieldName.Add("學務主任");
            globalFieldValue.Add(stuDirector);

            _doc.MailMerge.Execute(globalFieldName.ToArray(), globalFieldValue.ToArray());
            #endregion

            #endregion
        }
示例#7
0
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            double total = Students.Count;
            double count = 0;

            _worker.ReportProgress(0);

            List <string> studentIDs = Students.Select(x => x.ID).ToList();

            //List<string> student_ids = new List<string>();
            //foreach (JHStudentRecord item in Students)
            //    student_ids.Add(item.ID);

            #region 快取資料

            //獎勵
            // 1.依學生編號、開始日期、結束日期,取得學生獎勵紀錄
            // 2.依學生編號進行分群
            Dictionary <string, List <JHMeritRecord> > meritCache = new Dictionary <string, List <JHMeritRecord> >();
            foreach (JHMeritRecord record in JHMerit.Select(studentIDs, _config.StartDate, _config.EndDate, null, null, null, null))
            {
                if (!meritCache.ContainsKey(record.RefStudentID))
                {
                    meritCache.Add(record.RefStudentID, new List <JHMeritRecord>());
                }
                meritCache[record.RefStudentID].Add(record);
            }
            //Dictionary<string, List<JHMeritRecord>> meritCache = new Dictionary<string, List<JHMeritRecord>>();
            //foreach (JHMeritRecord record in JHMerit.SelectByStudentIDs(student_ids))
            //{
            //    if (record.OccurDate < _config.StartDate) continue;
            //    if (record.OccurDate > _config.EndDate) continue;

            //    if (!meritCache.ContainsKey(record.RefStudentID))
            //        meritCache.Add(record.RefStudentID, new List<JHMeritRecord>());
            //    meritCache[record.RefStudentID].Add(record);
            //}

            //懲戒
            // 1.依學生編號、開始日期、結束日期,取得學生懲戒紀錄
            // 2.依學生編號進行分群
            Dictionary <string, List <JHDemeritRecord> > demeritCache = new Dictionary <string, List <JHDemeritRecord> >();
            foreach (JHDemeritRecord record in JHDemerit.Select(studentIDs, _config.StartDate, _config.EndDate, null, null, null, null))
            {
                if (!demeritCache.ContainsKey(record.RefStudentID))
                {
                    demeritCache.Add(record.RefStudentID, new List <JHDemeritRecord>());
                }
                demeritCache[record.RefStudentID].Add(record);
            }

            //Dictionary<string, List<JHDemeritRecord>> demeritCache = new Dictionary<string, List<JHDemeritRecord>>();
            //foreach (JHDemeritRecord record in JHDemerit.SelectByStudentIDs(student_ids))
            //{
            //    if (record.OccurDate < _config.StartDate) continue;
            //    if (record.OccurDate > _config.EndDate) continue;

            //    if (!demeritCache.ContainsKey(record.RefStudentID))
            //        demeritCache.Add(record.RefStudentID, new List<JHDemeritRecord>());
            //    demeritCache[record.RefStudentID].Add(record);
            //}


            ////缺曠
            //// 1.依學生編號、開始日期、結束日期,取得學生缺曠紀錄
            //// 2.依學生編號進行分群
            //Dictionary<string, List<JHAttendanceRecord>> attendanceCache = new Dictionary<string, List<JHAttendanceRecord>>();
            //foreach (JHAttendanceRecord record in JHAttendance.Select(studentIDs, _config.StartDate, _config.EndDate, null, null, null))
            //{
            //    if (!attendanceCache.ContainsKey(record.RefStudentID))
            //        attendanceCache.Add(record.RefStudentID, new List<JHAttendanceRecord>());
            //    attendanceCache[record.RefStudentID].Add(record);
            //}
            //Dictionary<string, List<JHAttendanceRecord>> attendanceCache = new Dictionary<string, List<JHAttendanceRecord>>();
            //foreach (JHAttendanceRecord record in JHAttendance.SelectByStudentIDs(student_ids))
            //{
            //    if (record.OccurDate < _config.StartDate) continue;
            //    if (record.OccurDate > _config.EndDate) continue;

            //    if (!attendanceCache.ContainsKey(record.RefStudentID))
            //        attendanceCache.Add(record.RefStudentID, new List<JHAttendanceRecord>());
            //    attendanceCache[record.RefStudentID].Add(record);
            //}

            //List<string> studentIDs = new List<string>();
            //foreach (var stu in _config.Students)
            //    studentIDs.Add(stu.ID);

            //缺曠
            // 1.依學生編號、開始日期、結束日期,取得學生缺曠紀錄
            // 2.依學生編號進行分群
            Dictionary <string, List <JHAttendanceRecord> > attendanceCache = new Dictionary <string, List <JHAttendanceRecord> >();
            foreach (JHAttendanceRecord record in JHAttendance.Select(studentIDs, _config.StartDate, _config.EndDate, null, null, null))
            {
                if (!attendanceCache.ContainsKey(record.RefStudentID))
                {
                    attendanceCache.Add(record.RefStudentID, new List <JHAttendanceRecord>());
                }
                attendanceCache[record.RefStudentID].Add(record);
            }



            //修課紀錄
            // 1.依學生編號、學年度、學期,取得修課紀錄
            // 2.
            List <string> courseIDs = new List <string>();
            List <string> attendIDs = new List <string>();
            Dictionary <string, List <string> > scCache = new Dictionary <string, List <string> >();
            foreach (var attend in JHSCAttend.Select(studentIDs, null, null, "" + _config.SchoolYear, "" + _config.Semester))
            {
                attendIDs.Add(attend.ID);
                if (!scCache.ContainsKey(attend.RefStudentID))
                {
                    scCache.Add(attend.RefStudentID, new List <string>());
                }
                scCache[attend.RefStudentID].Add(attend.RefCourseID);
                if (!courseIDs.Contains(attend.RefCourseID))
                {
                    courseIDs.Add(attend.RefCourseID);
                }
            }

            //課程
            // 1.依課程編號取得課程紀錄
            // 2.略過不列入成績計算的課程
            JHCourse.RemoveByIDs(courseIDs);
            Dictionary <string, JHCourseRecord> courseCache = JHCourse.SelectByIDs(courseIDs).Where(x => x.CalculationFlag != "2").ToDictionary(x => x.ID);

            //試別資訊: 取得所有試別
            Dictionary <string, JHExamRecord> examCache = JHExam.SelectAll().ToDictionary(x => x.ID);

            // 取得社團ExamID
            List <string> NExamIDList = new List <string>();
            foreach (JHExamRecord rec in JHExam.SelectAll())
            {
                if (rec.Name.IndexOf("社團") > -1)
                {
                    NExamIDList.Add(rec.ID);
                }
            }

            //評量成績
            // 1.依修課記錄及所有試別取得評量成績
            // 2.依第1點的評量成績取得試別編號 (實際學生評量成績中的試別編號)
            // 3.依學生編號進行分群
            Dictionary <string, List <HC.JHSCETakeRecord> > sceScoreCache = new Dictionary <string, List <HC.JHSCETakeRecord> >();
            List <string> validExamIDs = new List <string>();

            //  檢查當有修課紀錄才取成績資料
            if (attendIDs.Count > 0 && examCache.Count > 0)
            {
                foreach (JHSCETakeRecord record in JHSCETake.Select(null, null, examCache.Keys, null, attendIDs))
                {
                    if (!NExamIDList.Contains(record.RefExamID))
                    {
                        if (!validExamIDs.Contains(record.RefExamID))
                        {
                            validExamIDs.Add(record.RefExamID);
                        }
                    }

                    if (!sceScoreCache.ContainsKey(record.RefStudentID))
                    {
                        sceScoreCache.Add(record.RefStudentID, new List <HC.JHSCETakeRecord>());
                    }
                    sceScoreCache[record.RefStudentID].Add(new HC.JHSCETakeRecord(record));
                }
            }

            //將『所有試別編號』與『實際學生評量成績中的試別編號』做交集,以取得使用管理的試別次序
            //假設『所有試別編號』為1,4,3,5
            //假設『實際學生評量成績中的試別編號』為3,4,1
            //交集後的結果為1,4,3
            validExamIDs = examCache.Keys.Intersect(validExamIDs).ToList();



            // 取得學生成績計算規則
            // 如果學生沒有計算規則一律用預設,預設進位方式取到小數點第2位
            ScoreCalculator defaultScoreCalculator = new ScoreCalculator(null);
            //key: ScoreCalcRuleID
            Dictionary <string, ScoreCalculator> calcCache = new Dictionary <string, ScoreCalculator>();
            //key: StudentID, val: ScoreCalcRuleID
            Dictionary <string, string> calcIDCache = new Dictionary <string, string>();

            List <string> scoreCalcRuleIDList = new List <string>();

            // 取得學生計算規則的ID,建立對照表
            // 如果學生身上有指定成績計算規則,就以學生身上成績計算規則為主
            // 如果學生身上沒有指定成績計算規則,就以學生所屬班級成績計算規則為主
            foreach (JHStudentRecord student in _config.Students)
            {
                string calcID = string.Empty;
                if (!string.IsNullOrEmpty(student.OverrideScoreCalcRuleID))
                {
                    calcID = student.OverrideScoreCalcRuleID;
                }
                else if (student.Class != null && !string.IsNullOrEmpty(student.Class.RefScoreCalcRuleID))
                {
                    calcID = student.Class.RefScoreCalcRuleID;
                }

                if (!string.IsNullOrEmpty(calcID))
                {
                    calcIDCache.Add(student.ID, calcID);
                }
            }
            // 取得計算規則建立成績進位器
            foreach (JHScoreCalcRuleRecord record in JHScoreCalcRule.SelectByIDs(calcIDCache.Values))
            {
                if (!calcCache.ContainsKey(record.ID))
                {
                    calcCache.Add(record.ID, new ScoreCalculator(record));
                }
            }


            ////修課紀錄
            //// 1.依學生編號、學年度、學期,取得修課紀錄
            //// 2.
            //List<string> courseIDs = new List<string>();
            //foreach (var attend in JHSCAttend.SelectByStudentIDs(studentIDs))
            //{
            //    if (!courseIDs.Contains(attend.RefCourseID))
            //        courseIDs.Add(attend.RefCourseID);
            //}

            //int schoolYear = _config.SchoolYear;
            //int semester = _config.Semester;
            //List<JHCourseRecord> courses = JHCourse.SelectByIDs(courseIDs);

            ////課程
            //Dictionary<string, JHCourseRecord> courseCache = new Dictionary<string, JHCourseRecord>();
            //foreach (JHCourseRecord record in JHCourse.SelectByIDs(courseIDs))
            //{
            //    if ("" + record.SchoolYear != "" + schoolYear) continue;
            //    if ("" + record.Semester != "" + semester) continue;
            //    if (record.CalculationFlag == "2") continue;
            //    //if (string.IsNullOrEmpty(record.Domain)) continue; //沒有填領域

            //    if (!courseCache.ContainsKey(record.ID))
            //        courseCache.Add(record.ID, record);
            //}

            ////試別資訊
            //Dictionary<string, JHExamRecord> examCache = new Dictionary<string, JHExamRecord>();
            //foreach (JHExamRecord exam in JHExam.SelectAll())
            //{
            //    if (!examCache.ContainsKey(exam.ID))
            //        examCache.Add(exam.ID, exam);
            //}
            //List<string> validExamIDs = new List<string>();

            ////評量成績
            //Dictionary<string, List<HC.JHSCETakeRecord>> sceScoreCache = new Dictionary<string, List<HC.JHSCETakeRecord>>();
            //foreach (JHSCETakeRecord record in JHSCETake.SelectByStudentIDs(student_ids))
            //{
            //    if (examCache.ContainsKey(record.RefExamID))
            //    {
            //        if (!validExamIDs.Contains(record.RefExamID))
            //            validExamIDs.Add(record.RefExamID);
            //    }
            //    else
            //        continue;

            //    if (!sceScoreCache.ContainsKey(record.RefStudentID))
            //        sceScoreCache.Add(record.RefStudentID, new List<HC.JHSCETakeRecord>());
            //    sceScoreCache[record.RefStudentID].Add(new HC.JHSCETakeRecord(record));
            //}
            //// TODO: 這邊的排序有可能再改
            //validExamIDs.Sort(delegate(string x, string y)
            //{
            //    int ix, iy;
            //    if (!int.TryParse(x, out ix))
            //        ix = int.MaxValue;
            //    if (!int.TryParse(y, out iy))
            //        iy = int.MaxValue;
            //    return ix.CompareTo(iy);
            //});

            //學期歷程
            //Dictionary<string, K12.Data.SemesterHistoryItem> historyCache = new Dictionary<string, K12.Data.SemesterHistoryItem>();
            //foreach (JHSemesterHistoryRecord record in JHSemesterHistory.SelectByStudentIDs(student_ids))
            //{
            //    foreach (K12.Data.SemesterHistoryItem item in record.SemesterHistoryItems)
            //    {
            //        if ("" + item.SchoolYear != K12.Data.School.DefaultSchoolYear) continue;
            //        if ("" + item.Semester != K12.Data.School.DefaultSemester) continue;

            //        if (!historyCache.ContainsKey(record.RefStudentID))
            //            historyCache.Add(record.RefStudentID, item);
            //    }
            //}
            #endregion

            #region 判斷領域是否需要展開
            //判斷領域是否展開對照表
            //Key:領域名稱
            //Value:false=展開,true=不展開
            //展開: 詳列該領域下所有科目成績
            //不展開: 只列該領域成績
            Dictionary <string, bool>           domains  = new Dictionary <string, bool>();
            Dictionary <string, List <string> > subjects = new Dictionary <string, List <string> >();

            List <JHCourseRecord> courseList = new List <JHCourseRecord>(courseCache.Values);
            courseList.Sort(delegate(JHCourseRecord x, JHCourseRecord y)
            {
                return(JHSchool.Evaluation.Subject.CompareSubjectOrdinal(x.Subject, y.Subject));
                //List<string> list = new List<string>(new string[] { "國語文", "國文", "英文", "英語", "數學", "歷史", "地理", "公民", "理化", "生物" });
                //int ix = list.IndexOf(x.Subject);
                //int iy = list.IndexOf(y.Subject);

                //if (ix >= 0 && iy >= 0)
                //    return ix.CompareTo(iy);
                //else if (ix >= 0)
                //    return -1;
                //else if (iy >= 0)
                //    return 1;
                //else
                //    return x.Subject.CompareTo(y.Subject);
            });

            DomainSubjectSetup domainSubjectSetup = _config.DomainSubjectSetup;
            //使用者設定"只列印領域"
            if (domainSubjectSetup == DomainSubjectSetup.Domain)
            {
                //預設從領域資料管理來的領域名稱皆不展開
                foreach (var domain in JHSchool.Evaluation.Subject.Domains)
                {
                    domains.Add(domain, DomainSubjectExpand.展開);
                }
                if (domains.ContainsKey("語文"))
                {
                    domains["語文"] = DomainSubjectExpand.展開;
                }

                //彈性課程一定展開
                if (!domains.ContainsKey(""))
                {
                    domains.Add("", DomainSubjectExpand.展開);
                }
                //if (!domains.ContainsKey("彈性課程")) domains.Add("彈性課程", false);
            }
            //使用者設定"只列印科目"
            else if (domainSubjectSetup == DomainSubjectSetup.Subject)
            {
                //預設從領域資料管理來的領域名稱皆展開
                foreach (var domain in JHSchool.Evaluation.Subject.Domains)
                {
                    domains.Add(domain, DomainSubjectExpand.展開);
                }
                //彈性課程一定展開
                if (!domains.ContainsKey(""))
                {
                    domains.Add("", DomainSubjectExpand.展開);
                }
                //if (!domains.ContainsKey("彈性課程")) domains.Add("彈性課程", false);
            }
            else
            {
                throw new Exception("請重新儲存一次列印設定");
            }

            //foreach (var domain in JHSchool.Evaluation.Subject.Domains)
            //    subjects.Add(domain, new List<string>());

            //if (!subjects.ContainsKey("")) subjects.Add("", new List<string>());
            //if (!subjects.ContainsKey("彈性課程")) subjects.Add("彈性課程", new List<string>());

            //foreach (var course in courseList)
            //{
            //    if (!subjects.ContainsKey(course.Domain))
            //        subjects.Add(course.Domain, new List<string>());
            //    if (!subjects[course.Domain].Contains(course.Subject))
            //        subjects[course.Domain].Add(course.Subject);
            //}

            //_config.SetPrintDomains(domains);
            //_config.SetPrintSubjects(subjects);
            _config.PrintDomains = domains;
            #endregion

            #region 建立節次對照
            Dictionary <string, string> periodMapping = JHPeriodMapping.SelectAll().ToDictionary(x => x.Name, y => y.Type);
            //Dictionary<string, string> periodMapping = new Dictionary<string, string>();
            //foreach (JHPeriodMappingInfo info in JHPeriodMapping.SelectAll())
            //{
            //    if (!periodMapping.ContainsKey(info.Name))
            //        periodMapping.Add(info.Name, info.Type);
            //}
            #endregion

            #region 假別列表
            List <string> absenceList = JHAbsenceMapping.SelectAll().Select(x => x.Name).ToList();
            //List<string> absenceList = new List<string>();
            //foreach (JHAbsenceMappingInfo info in JHAbsenceMapping.SelectAll())
            //    absenceList.Add(info.Name);
            #endregion

            #region 依評量試別重新劃分範本
            int             rowCount        = 0;
            DocumentBuilder templateBuilder = new DocumentBuilder(_template);
            templateBuilder.MoveToMergeField("各次評量");
            Font   font       = templateBuilder.Font;
            Cell   examsCell  = templateBuilder.CurrentParagraph.ParentNode as Cell;
            Table  table      = examsCell.ParentRow.ParentTable;
            double width      = examsCell.CellFormat.Width;
            double examWidth  = width / (double)validExamIDs.Count;
            double scoreWidth = width / (double)validExamIDs.Count / 3.0;

            //計算有幾個 Score Row
            foreach (Row row in table.Rows)
            {
                if (row.Cells.Count > 3)
                {
                    rowCount++;
                }
            }

            #region Header Cell
            //建立評量欄位對照表
            Dictionary <string, int> columnMapping = new Dictionary <string, int>();
            int columnShift = 3;
            int columnIndex = 0;

            table.Rows[0].LastCell.Remove();
            table.Rows[1].LastCell.Remove();
            foreach (string examID in validExamIDs)
            {
                columnMapping.Add(examID, columnIndex + columnShift);

                Cell topHeaderCell = new Cell(_template);
                WordHelper.Write(topHeaderCell, font, examCache[examID].Name);
                table.Rows[0].Cells.Add(topHeaderCell);

                Cell subHeaderCell1 = new Cell(_template);
                WordHelper.Write(subHeaderCell1, font, "定期", "評量");
                table.Rows[1].Cells.Add(subHeaderCell1);
                columnIndex++;

                Cell subHeaderCell2 = new Cell(_template);
                WordHelper.Write(subHeaderCell2, font, "平時", "評量");
                table.Rows[1].Cells.Add(subHeaderCell2);
                columnIndex++;

                Cell subHeaderCell3 = new Cell(_template);
                WordHelper.Write(subHeaderCell3, font, "總成績");
                table.Rows[1].Cells.Add(subHeaderCell3);
                columnIndex++;

                topHeaderCell.CellFormat.Width  = examWidth;
                subHeaderCell1.CellFormat.Width = scoreWidth;
                subHeaderCell2.CellFormat.Width = scoreWidth;
                subHeaderCell3.CellFormat.Width = scoreWidth;

                topHeaderCell.CellFormat.VerticalAlignment  = CellVerticalAlignment.Center;
                subHeaderCell1.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
                subHeaderCell2.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
                subHeaderCell3.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
            }
            WordHelper.MergeVerticalCell(table.Rows[0].Cells[1], 2);
            #endregion

            #region Content Cell
            int shift = 2; //Header has 2 rows
            for (int i = 0; i < rowCount; i++)
            {
                table.Rows[i + shift].LastCell.Remove();

                for (int j = 0; j < validExamIDs.Count * 3; j++)
                {
                    Cell contentCell = new Cell(_template);
                    contentCell.CellFormat.Width             = scoreWidth;
                    contentCell.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;

                    table.Rows[i + shift].Cells.Add(contentCell);
                }
            }
            #endregion

            #endregion

            #region 依節權數設定,在畫面上顯示
            string pcDisplay = string.Empty;
            if (_config.PrintPeriod && _config.PrintCredit)
            {
                pcDisplay = "節/權數";
            }
            else if (_config.PrintPeriod)
            {
                pcDisplay = "節數";
            }
            else if (_config.PrintCredit)
            {
                pcDisplay = "權數";
            }

            templateBuilder.MoveToMergeField("節權數");
            templateBuilder.Write(pcDisplay);
            #endregion

            //#region 取得學生成績計算規則

            //ScoreCalculator defaultScoreCalculator = new ScoreCalculator(null);

            ////key: ScoreCalcRuleID
            //Dictionary<string, ScoreCalculator> calcCache = new Dictionary<string, ScoreCalculator>();
            ////key: StudentID, val: ScoreCalcRuleID
            //Dictionary<string, string> calcIDCache = new Dictionary<string, string>();

            //List<string> scoreCalcRuleIDList = new List<string>();

            //foreach (JHStudentRecord student in _config.Students)
            //{
            //    string calcID = string.Empty;
            //    if (!string.IsNullOrEmpty(student.OverrideScoreCalcRuleID))
            //        calcID = student.OverrideScoreCalcRuleID;
            //    else if (student.Class != null && !string.IsNullOrEmpty(student.Class.RefScoreCalcRuleID))
            //        calcID = student.Class.RefScoreCalcRuleID;

            //    if (!string.IsNullOrEmpty(calcID))
            //        calcIDCache.Add(student.ID, calcID);
            //}
            //foreach (JHScoreCalcRuleRecord record in JHScoreCalcRule.SelectByIDs(calcIDCache.Values))
            //{
            //    if (!calcCache.ContainsKey(record.ID))
            //        calcCache.Add(record.ID, new ScoreCalculator(record));
            //}
            //#endregion

            // 取得學期歷程
            Config._StudSemesterHistoryItemDict.Clear();

            List <JHSemesterHistoryRecord> semHisRec = JHSemesterHistory.SelectByStudents(Students);
            // 當畫面學期歷程內的學年度學期與畫面上設定相同,加入
            foreach (JHSemesterHistoryRecord rec in semHisRec)
            {
                foreach (K12.Data.SemesterHistoryItem shi in rec.SemesterHistoryItems)
                {
                    if (shi.SchoolYear == _config.SchoolYear && shi.Semester == _config.Semester)
                    {
                        if (!Config._StudSemesterHistoryItemDict.ContainsKey(shi.RefStudentID))
                        {
                            Config._StudSemesterHistoryItemDict.Add(shi.RefStudentID, shi);
                        }
                    }
                }
            }

            // 取得學生服務學習時數
            Config._SRDict.Clear();
            List <string> sidList = (from data in Students select data.ID).ToList();
            Config._SRDict = Utility.GetServiceLearningDetail(sidList, _config.SchoolYear, _config.Semester);

            #region 產生
            foreach (JHStudentRecord student in Students)
            {
                count++;

                Document        each    = (Document)_template.Clone(true);
                DocumentBuilder builder = new DocumentBuilder(each);

                #region 學生基本資料
                StudentBasicInfo basicInfo = new StudentBasicInfo(builder);
                basicInfo.SetStudent(student);
                #endregion

                //#region 班導師
                //builder.MoveToMergeField("班導師");
                //if (historyCache.ContainsKey(student.ID))
                //    builder.Write(historyCache[student.ID].Teacher);
                //else
                //    builder.Write(string.Empty);
                //#endregion

                #region 各評量成績
                List <HC.JHSCETakeRecord> sceScoreList = null;
                if (sceScoreCache.ContainsKey(student.ID))
                {
                    sceScoreList = sceScoreCache[student.ID];
                }
                else
                {
                    sceScoreList = new List <HC.JHSCETakeRecord>();
                }

                ScoreCalculator studentCalculator = defaultScoreCalculator;
                if (calcIDCache.ContainsKey(student.ID) && calcCache.ContainsKey(calcIDCache[student.ID]))
                {
                    studentCalculator = calcCache[calcIDCache[student.ID]];
                }

                try {
                    StudentExamScore examScore = new StudentExamScore(builder, _config, courseCache);
                    if (scCache.ContainsKey(student.ID))
                    {
                        examScore.SetSubjects(scCache[student.ID]);
                    }
                    examScore.SetColumnMap(columnMapping);
                    examScore.SetCalculator(studentCalculator);
                    examScore.SetData(sceScoreList);
                } catch (Exception erro)
                {
                    e.Cancel = true;
                }

                #endregion

                #region 缺曠獎懲
                List <JHMeritRecord>      meritList      = null;
                List <JHDemeritRecord>    demeritList    = null;
                List <JHAttendanceRecord> attendanceList = null;

                meritList      = (meritCache.ContainsKey(student.ID)) ? meritCache[student.ID] : new List <JHMeritRecord>();
                demeritList    = (demeritCache.ContainsKey(student.ID)) ? demeritCache[student.ID] : new List <JHDemeritRecord>();
                attendanceList = (attendanceCache.ContainsKey(student.ID)) ? attendanceCache[student.ID] : new List <JHAttendanceRecord>();

                StudentMoralScore moral = new StudentMoralScore(builder, _config, periodMapping, absenceList);
                moral.SetData(meritList, demeritList, attendanceList);
                #endregion

                foreach (Section sec in each.Sections)
                {
                    _doc.Sections.Add(_doc.ImportNode(sec, true));
                }

                //回報進度
                _worker.ReportProgress((int)(count * 100.0 / total));
            }

            #region 全域 MergeField
            List <string> globalFieldName  = new List <string>();
            List <object> globalFieldValue = new List <object>();

            globalFieldName.Add("學校名稱");
            globalFieldValue.Add(K12.Data.School.ChineseName);

            globalFieldName.Add("學年度");
            //globalFieldValue.Add(K12.Data.School.DefaultSchoolYear);
            globalFieldValue.Add(_config.SchoolYear.ToString());

            globalFieldName.Add("學期");
            //globalFieldValue.Add(K12.Data.School.DefaultSemester);
            globalFieldValue.Add(_config.Semester.ToString());

            globalFieldName.Add("統計期間");
            globalFieldValue.Add(_config.StartDate.ToShortDateString() + " ~ " + _config.EndDate.ToShortDateString());

            globalFieldName.Add("列印日期");
            globalFieldValue.Add(DateConvert.CDate(DateTime.Now.ToString("yyyy/MM/dd")) + " " + DateTime.Now.ToString("HH:mm:ss"));

            string chancellor, eduDirector, stuDirector;
            chancellor = eduDirector = stuDirector = string.Empty;

            XmlElement schoolInfo         = K12.Data.School.Configuration["學校資訊"].PreviousData;
            XmlElement chancellorElement  = (XmlElement)schoolInfo.SelectSingleNode("ChancellorChineseName");
            XmlElement eduDirectorElement = (XmlElement)schoolInfo.SelectSingleNode("EduDirectorName");
            XmlElement stuDirectorElement = (XmlElement)schoolInfo.SelectSingleNode("StuDirectorName");

            if (chancellorElement != null)
            {
                chancellor = chancellorElement.InnerText;
            }
            if (eduDirectorElement != null)
            {
                eduDirector = eduDirectorElement.InnerText;
            }
            if (stuDirectorElement != null)
            {
                stuDirector = stuDirectorElement.InnerText;
            }

            globalFieldName.Add("校長");
            globalFieldValue.Add(chancellor);

            globalFieldName.Add("教務主任");
            globalFieldValue.Add(eduDirector);

            globalFieldName.Add("學務主任");
            globalFieldValue.Add(stuDirector);

            _doc.MailMerge.Execute(globalFieldName.ToArray(), globalFieldValue.ToArray());
            #endregion

            #endregion
        }
        private void CalcWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            bool error = false;

            List <StudentRecord> students    = _students;
            List <string>        student_ids = new List <string>();

            foreach (StudentRecord each in students)
            {
                student_ids.Add(each.ID);
            }
            double total = students.Count;
            double count = 0;

            #region 寫入學期歷程
            if (_studentHistoryDict != null && _studentHistoryDict.Count > 0)
            {
                try
                {
                    List <JHSchool.Data.JHSemesterHistoryRecord> list = new List <JHSchool.Data.JHSemesterHistoryRecord>();
                    int    size   = 50;
                    double count2 = 0;
                    double total2 = _studentHistoryDict.Count;
                    foreach (JHSchool.Data.JHSemesterHistoryRecord record in _studentHistoryDict.Values)
                    {
                        if (_calc_worker.CancellationPending)
                        {
                            return;
                        }

                        list.Add(record);
                        count2++;
                        if (list.Count == size)
                        {
                            JHSchool.Data.JHSemesterHistory.Update(list);
                            list.Clear();
                            _calc_worker.ReportProgress((int)(count2 * 100 / total2), "寫入學期歷程中…");
                        }
                    }
                    if (list.Count > 0)
                    {
                        JHSchool.Data.JHSemesterHistory.Update(list);
                        list.Clear();
                        _calc_worker.ReportProgress(100, "學期歷程寫入完成");
                    }
                }
                catch (Exception ex)
                {
                    MsgBox.Show("寫入學期歷程失敗。" + ex.Message);
                    e.Result = null;
                    return;
                }
            }
            #endregion

            #region 計算課程成績

            _viewer.Clear();
            _viewer.SetHeader("課程");

            _calc_worker.ReportProgress(0, "計算課程成績…");

            if (_calc_worker.CancellationPending)
            {
                return;
            }
            _raw_data = new CourseDataLoader();
            _raw_data.LoadCalculationData(this, _students, intSchoolYear.Value, intSemester.Value);

            foreach (CW.Course course in _raw_data.Courses.Values)
            {
                if (string.IsNullOrEmpty(course.ExamTemplateId) && course.ExamRequired)
                {
                    _viewer.SetMessage(course.CourseName, new List <string>(new string[] { "缺少評量設定" }));
                    error = true;
                }
            }

            if (error)
            {
                e.Result = error;
                return;
            }

            _viewer.Clear();
            if (_calc_worker.CancellationPending)
            {
                return;
            }
            CourseScoreCalculate calculate = new CourseScoreCalculate(_raw_data.Courses);
            calculate.Calculate();

            foreach (CW.Course course in _raw_data.Courses.Values)
            {
                Dictionary <string, string> examLacks       = new Dictionary <string, string>();
                Dictionary <string, int>    examScoreLacks  = new Dictionary <string, int>();
                Dictionary <string, int>    examEffortLacks = new Dictionary <string, int>();

                List <CW.SCAttend> scattends         = new List <CW.SCAttend>();
                List <CW.SCAttend> no_exam_scattends = new List <CW.SCAttend>();
                foreach (CW.SCAttend scattend in course.SCAttends.Values)
                {
                    if (student_ids.Contains(scattend.StudentIdentity))
                    {
                        if (scattend.ContainsLack)
                        {
                            scattends.Add(scattend);
                        }
                        if (scattend.NoExam)
                        {
                            no_exam_scattends.Add(scattend);
                        }
                    }
                }

                foreach (CW.SCAttend scattend in scattends)
                {
                    foreach (string exam in scattend.ScoreLack)
                    {
                        if (!examLacks.ContainsKey(exam))
                        {
                            examLacks.Add(exam, "");
                        }

                        if (!examScoreLacks.ContainsKey(exam))
                        {
                            examScoreLacks.Add(exam, 0);
                        }
                        examScoreLacks[exam]++;
                    }

                    foreach (string exam in scattend.EffortLack)
                    {
                        if (!examLacks.ContainsKey(exam))
                        {
                            examLacks.Add(exam, "");
                        }

                        if (!examEffortLacks.ContainsKey(exam))
                        {
                            examEffortLacks.Add(exam, 0);
                        }
                        examEffortLacks[exam]++;
                    }
                }

                if (scattends.Count > 0)
                {
                    List <string> msgs = new List <string>();
                    foreach (string exam in new List <string>(examLacks.Keys))
                    {
                        if (examScoreLacks.ContainsKey(exam))
                        {
                            examLacks[exam] += "有" + examScoreLacks[exam] + "位學生缺少分數評量,";
                        }
                        if (examEffortLacks.ContainsKey(exam))
                        {
                            examLacks[exam] += "有" + examEffortLacks[exam] + "位學生缺少努力程度,";
                        }
                        if (!string.IsNullOrEmpty(examLacks[exam]))
                        {
                            examLacks[exam] = examLacks[exam].Substring(0, examLacks[exam].Length - 1);
                        }

                        msgs.Add(exam + ":" + examLacks[exam]);
                    }
                    _viewer.SetMessage(course.CourseName, msgs);
                    error = true;
                }

                if (no_exam_scattends.Count > 0)
                {
                    _viewer.SetMessage(course.CourseName, new List <string>(new string[] { "沒有設定各次評量" }));
                    error = true;
                }
            }

            if (error)
            {
                e.Result = true;
                return;
            }

            if (_calc_worker.CancellationPending)
            {
                return;
            }
            CourseScoreUpdater updater = new CourseScoreUpdater(_raw_data.Courses, this, false);
            updater.UpdateToServer();
            #endregion

            #region 計算學期成績

            //List<SemesterScoreRecordEditor> editors = new List<SemesterScoreRecordEditor>();
            List <JHSemesterScoreRecord> semesterScoreRecordList = new List <JHSchool.Data.JHSemesterScoreRecord>();

            JHSchool.Evaluation.SCAttend.Instance.SyncAllBackground();

            Dictionary <string, List <JHSemesterScoreRecord> > studentSemesterScoreCache = new Dictionary <string, List <JHSchool.Data.JHSemesterScoreRecord> >();
            foreach (JHSemesterScoreRecord record in JHSemesterScore.SelectByStudentIDs(students.AsKeyList()))
            {
                if (!studentSemesterScoreCache.ContainsKey(record.RefStudentID))
                {
                    studentSemesterScoreCache.Add(record.RefStudentID, new List <JHSchool.Data.JHSemesterScoreRecord>());
                }
                studentSemesterScoreCache[record.RefStudentID].Add(record);
            }

            count = 0;
            foreach (StudentRecord each in students)
            {
                count++;

                ScoreCalcRuleRecord   old       = GetScoreCalcRuleRecord(each);
                JHScoreCalcRuleRecord dalrecord = null;
                if (old != null)
                {
                    List <JHScoreCalcRuleRecord> list = JHScoreCalcRule.SelectByIDs(new string[] { old.ID });
                    if (list.Count > 0)
                    {
                        dalrecord = list[0];
                    }
                }
                ScoreCalculator calculator = new ScoreCalculator(dalrecord);

                List <SCAttendRecord> scattends = new List <SCAttendRecord>();
                foreach (SCAttendRecord scattend in JHSchool.Evaluation.SCAttend.Instance.GetStudentAttend(each.ID))
                {
                    CourseRecord course = scattend.Course;
                    if (course.SchoolYear == intSchoolYear.Value &&
                        course.Semester == intSemester.Value &&
                        !string.IsNullOrEmpty(course.RefAssessmentSetupID) &&
                        course.CalculationFlag == "1"
                        )
                    {
                        scattends.Add(scattend);
                    }
                }

                if (scattends.Count > 0)
                {
                    List <K12.Data.SubjectScore> subjectScores = _inner_calculator.CalculateSubjectScore(scattends);
                    foreach (K12.Data.SubjectScore subject in subjectScores)
                    {
                        subject.Score = calculator.ParseSubjectScore((decimal)subject.Score);
                    }
                    List <K12.Data.DomainScore> domainScores = _inner_calculator.CalculateDomainScore(subjectScores);
                    foreach (K12.Data.DomainScore domain in domainScores)
                    {
                        domain.Score = calculator.ParseDomainScore((decimal)domain.Score);
                    }

                    List <K12.Data.DomainScore> domainListWithoutElastic = new List <K12.Data.DomainScore>();
                    bool hasElasticCourse = false;
                    foreach (K12.Data.DomainScore domain in domainScores)
                    {
                        if (domain.Domain == "彈性課程")
                        {
                            hasElasticCourse = true;
                        }
                        else
                        {
                            domainListWithoutElastic.Add(domain);
                        }
                    }

                    decimal?learnDomainScore = calculator.ParseLearnDomainScore(_inner_calculator.CalculateTotalDomainScore(domainListWithoutElastic));
                    decimal?courseLearnScore = null;
                    if (hasElasticCourse)
                    {
                        courseLearnScore = calculator.ParseLearnDomainScore(_inner_calculator.CalculateTotalDomainScore(domainScores));
                    }

                    JHSemesterScoreRecord current = null;
                    if (studentSemesterScoreCache.ContainsKey(each.ID))
                    {
                        foreach (JHSemesterScoreRecord record in studentSemesterScoreCache[each.ID])
                        {
                            if (record.SchoolYear == intSchoolYear.Value && record.Semester == intSemester.Value)
                            {
                                current = record;
                            }
                        }
                    }

                    if (current != null)
                    {
                        //editor = current.GetEditor();
                        current.Subjects = new Dictionary <string, K12.Data.SubjectScore>();
                        current.Domains  = new Dictionary <string, K12.Data.DomainScore>();
                    }
                    else
                    {
                        //current = new SemesterScoreRecordEditor(each, intSchoolYear.Value, intSemester.Value, _gradeYears[each.ID]);
                        current = new JHSchool.Data.JHSemesterScoreRecord();
                        current.RefStudentID = each.ID;
                        current.SchoolYear   = intSchoolYear.Value;
                        current.Semester     = intSemester.Value;
                    }

                    foreach (K12.Data.SubjectScore subject in subjectScores)
                    {
                        current.Subjects.Add(subject.Subject, subject);
                    }
                    foreach (K12.Data.DomainScore domain in domainScores)
                    {
                        current.Domains.Add(domain.Domain, domain);
                    }
                    current.LearnDomainScore = learnDomainScore;
                    current.CourseLearnScore = courseLearnScore;

                    //editors.Add(editor);
                    semesterScoreRecordList.Add(current);
                }

                _calc_worker.ReportProgress((int)((double)count * 100 / (double)total), "計算學期成績…");
            }

            e.Result = semesterScoreRecordList;
            #endregion
        }
        private DataTable GetClassStudentDomainScore(ParameterRec data)
        {
            //            string sql = string.Format(@"
            //WITH data_row AS (
            //    SELECT
            //        {0}::INT AS school_year
            //        , {1}::INT AS semester
            //), target_student AS(
            //	SELECT
            //		*
            //	FROM
            //		student
            //	WHERE
            //		ref_class_id IN ({2})
            //        AND status IN(1, 2)
            //)
            //SELECT
            //    student.id
            //    , student.name
            //    , student.seat_no
            //    , class.id AS class_id
            //    , class.class_name
            //	, sems_subj_score_ext.semester
            //	, sems_subj_score_ext.school_year
            //	, array_to_string(xpath('/Domain/@原始成績', subj_score_ele), '')::text AS 原始成績
            //	, array_to_string(xpath('/Domain/@成績', subj_score_ele), '')::text AS 成績
            //	, array_to_string(xpath('/Domain/@領域', subj_score_ele), '')::text AS 領域
            //    , array_to_string(xpath('/Domain/@權數', subj_score_ele), '')::text AS 權數
            //FROM (
            //		SELECT
            //			sems_subj_score.*
            //			, unnest(xpath('/root/Domains/Domain', xmlparse(content '<root>' || score_info || '</root>'))) as subj_score_ele
            //		FROM
            //			sems_subj_score
            //			INNER JOIN target_student
            //				ON target_student.id = sems_subj_score.ref_student_id
            //	) as sems_subj_score_ext
            //    LEFT OUTER JOIN student
            //        ON student.id = sems_subj_score_ext.ref_student_id
            //    LEFT OUTER JOIN class
            //        ON class.id = student.ref_class_id
            //    INNER JOIN data_row
            //      ON data_row.school_year = sems_subj_score_ext.school_year
            //      AND data_row.semester = sems_subj_score_ext.semester
            //ORDER BY
            //	sems_subj_score_ext.grade_year
            //    , class.display_order
            //    , student.seat_no
            //                ", data.SchoolYear, data.Semester, data.ClassIDs);

            //return qh.Select(sql);

            // 取得班級學生含研修
            QueryHelper qh1 = new QueryHelper();
            string      qry = @"SELECT student.id,student.name,student.seat_no,class.id AS class_id,class.class_name FROM student INNER JOIN class on student.ref_class_id = class.id WHERE student.status IN(1,2) AND class.id IN(" + data.ClassIDs + @") ORDER BY class.grade_year,class.display_order,class.class_name,student.seat_no";

            DataTable dtStudent = qh1.Select(qry);

            List <string> StudentIDList = new List <string>();

            foreach (DataRow dr in dtStudent.Rows)
            {
                StudentIDList.Add(dr["id"].ToString());
            }

            // 取得學生學期成績,即時計算使用
            List <JHSemesterScoreRecord> StudentSemesterScoreList = JHSemesterScore.SelectByStudentIDs(StudentIDList);

            // 建立成績資料索引
            Dictionary <string, List <JHSemesterScoreRecord> > StudentSemesterScoreDict = new Dictionary <string, List <JHSemesterScoreRecord> >();

            foreach (JHSemesterScoreRecord rec in StudentSemesterScoreList)
            {
                if (!StudentSemesterScoreDict.ContainsKey(rec.RefStudentID))
                {
                    StudentSemesterScoreDict.Add(rec.RefStudentID, new List <JHSemesterScoreRecord>());
                }

                StudentSemesterScoreDict[rec.RefStudentID].Add(rec);
            }


            DataTable dt = new DataTable();

            dt.Columns.Add("id");
            dt.Columns.Add("name");
            dt.Columns.Add("seat_no");
            dt.Columns.Add("class_id");
            dt.Columns.Add("class_name");
            dt.Columns.Add("semester");
            dt.Columns.Add("school_year");
            dt.Columns.Add("原始成績");
            dt.Columns.Add("成績");
            dt.Columns.Add("領域");
            dt.Columns.Add("權數");

            // 各領域學期成績
            Dictionary <string, List <decimal> > domainnScoreDict = new Dictionary <string, List <decimal> >();



            // 各領域學期成績原始
            Dictionary <string, List <decimal> > domainnScoreOrignDict = new Dictionary <string, List <decimal> >();

            // 各領域成績(算術平均)
            Dictionary <string, decimal> domainnScoreAvgDict = new Dictionary <string, decimal>();
            // 各領域成績(算術平均)(原始)
            Dictionary <string, decimal> domainnScoreAvgOrignDict = new Dictionary <string, decimal>();

            // 各領域學分
            Dictionary <string, List <decimal> > domainCreditDict = new Dictionary <string, List <decimal> >();

            // 各領域學分平均
            Dictionary <string, decimal> domainAvgCreditDict = new Dictionary <string, decimal>();

            #region 取得學生成績計算規則
            ScoreCalculator defaultScoreCalculator = new ScoreCalculator(null);

            //key: ScoreCalcRuleID
            calcCache.Clear();

            //key: StudentID, val: ScoreCalcRuleID
            calcIDCache.Clear();

            List <string> scoreCalcRuleIDList = new List <string>();

            List <StudentRecord> StudentRecList = K12.Data.Student.SelectByIDs(StudentIDList);
            foreach (StudentRecord student in StudentRecList)
            {
                //calcCache.Add(student.ID, new ScoreCalculator(student.ScoreCalcRule));
                string calcID = string.Empty;
                if (!string.IsNullOrEmpty(student.OverrideScoreCalcRuleID))
                {
                    calcID = student.OverrideScoreCalcRuleID;
                }
                else if (student.Class != null && !string.IsNullOrEmpty(student.Class.RefScoreCalcRuleID))
                {
                    calcID = student.Class.RefScoreCalcRuleID;
                }

                if (!string.IsNullOrEmpty(calcID))
                {
                    calcIDCache.Add(student.ID, calcID);
                }
            }
            foreach (JHScoreCalcRuleRecord record in JHScoreCalcRule.SelectByIDs(calcIDCache.Values))
            {
                if (!calcCache.ContainsKey(record.ID))
                {
                    calcCache.Add(record.ID, new ScoreCalculator(record));
                }
            }


            #endregion

            // 計算畢業成績使用
            StudentSemsDomainScoreSumDict.Clear();
            StudentSemsCreditSumDict.Clear();

            // 開始填資料
            foreach (DataRow dr in dtStudent.Rows)
            {
                string sid = dr["id"].ToString();

                //DataRow newRow = dt.NewRow();
                //newRow["id"] = sid;
                //newRow["name"] = dr["name"].ToString();
                //newRow["seat_no"] = dr["seat_no"].ToString();
                //newRow["class_id"] = dr["class_id"].ToString();
                //newRow["class_name"] = dr["class_name"].ToString();
                //newRow["semester"] = "";
                //newRow["school_year"] = "";

                //newRow["原始成績"] = "0";
                //newRow["成績"] = "0";
                //newRow["領域"] = "0";
                //newRow["權數"] = "0";

                // 即時計算領域成績
                if (StudentSemesterScoreDict.ContainsKey(sid))
                {
                    // 成績計算規則
                    ScoreCalculator studentCalculator = defaultScoreCalculator;
                    if (calcIDCache.ContainsKey(sid) && calcCache.ContainsKey(calcIDCache[sid]))
                    {
                        studentCalculator = calcCache[calcIDCache[sid]];
                    }

                    domainnScoreDict.Clear();

                    domainnScoreOrignDict.Clear();
                    domainnScoreAvgDict.Clear();
                    domainnScoreAvgOrignDict.Clear();
                    domainCreditDict.Clear();

                    if (!StudentSemsDomainScoreSumDict.ContainsKey(sid))
                    {
                        StudentSemsDomainScoreSumDict.Add(sid, new Dictionary <string, decimal>());
                    }

                    if (!StudentSemsCreditSumDict.ContainsKey(sid))
                    {
                        StudentSemsCreditSumDict.Add(sid, new Dictionary <string, decimal>());
                    }

                    // 整理各學期領域成績
                    foreach (JHSemesterScoreRecord rec in StudentSemesterScoreDict[sid])
                    {
                        string key = rec.SchoolYear + "_" + rec.Semester;

                        if (!StudentSemsDomainScoreSumDict[sid].ContainsKey(key))
                        {
                            StudentSemsDomainScoreSumDict[sid].Add(key, 0);
                        }

                        if (!StudentSemsCreditSumDict[sid].ContainsKey(key))
                        {
                            StudentSemsCreditSumDict[sid].Add(key, 0);
                        }

                        // 讀取成績
                        foreach (string dName in rec.Domains.Keys)
                        {
                            // 加入領域成績
                            if (rec.Domains[dName].Score.HasValue)
                            {
                                if (!domainnScoreDict.ContainsKey(dName))
                                {
                                    domainnScoreDict.Add(dName, new List <decimal>());
                                }
                                domainnScoreDict[dName].Add(rec.Domains[dName].Score.Value);

                                if (rec.Domains[dName].Credit.HasValue)
                                {
                                    StudentSemsDomainScoreSumDict[sid][key] += (rec.Domains[dName].Score.Value * rec.Domains[dName].Credit.Value);
                                }
                            }

                            // 加入領域原始
                            if (rec.Domains[dName].ScoreMakeup.HasValue)
                            {
                                if (!domainnScoreOrignDict.ContainsKey(dName))
                                {
                                    domainnScoreOrignDict.Add(dName, new List <decimal>());
                                }
                                domainnScoreOrignDict[dName].Add(rec.Domains[dName].ScoreMakeup.Value);
                            }

                            // 加入權數
                            if (rec.Domains[dName].Credit.HasValue)
                            {
                                if (!domainCreditDict.ContainsKey(dName))
                                {
                                    domainCreditDict.Add(dName, new List <decimal>());
                                }

                                domainCreditDict[dName].Add(rec.Domains[dName].Credit.Value);

                                StudentSemsCreditSumDict[sid][key] += rec.Domains[dName].Credit.Value;
                            }
                        }
                    }

                    // 計算成績
                    foreach (string dName in domainnScoreDict.Keys)
                    {
                        // 使用畢業成績計算規則四捨五入方式,即時計算平均
                        decimal avgScore = studentCalculator.ParseGraduateScore(domainnScoreDict[dName].Average());
                        if (!domainnScoreAvgDict.ContainsKey(dName))
                        {
                            domainnScoreAvgDict.Add(dName, avgScore);
                        }
                    }

                    foreach (string dName in domainnScoreOrignDict.Keys)
                    {
                        // 使用畢業成績計算規則四捨五入方式,即時計算平均(原始)
                        decimal avgScore = studentCalculator.ParseGraduateScore(domainnScoreOrignDict[dName].Average());
                        if (!domainnScoreAvgOrignDict.ContainsKey(dName))
                        {
                            domainnScoreAvgOrignDict.Add(dName, avgScore);
                        }
                    }

                    // 處理學分

                    foreach (string dName in domainCreditDict.Keys)
                    {
                        // 使用畢業成績計算規則四捨五入方式,即時計算平均(原始)
                        decimal avgScore = studentCalculator.ParseGraduateScore(domainCreditDict[dName].Average());
                        if (!domainAvgCreditDict.ContainsKey(dName))
                        {
                            domainAvgCreditDict.Add(dName, avgScore);
                        }
                    }

                    foreach (string domainName in domainnScoreAvgDict.Keys)
                    {
                        // 填資料
                        DataRow newRow = dt.NewRow();
                        newRow["id"]          = sid;
                        newRow["name"]        = dr["name"].ToString();
                        newRow["seat_no"]     = dr["seat_no"].ToString();
                        newRow["class_id"]    = dr["class_id"].ToString();
                        newRow["class_name"]  = dr["class_name"].ToString();
                        newRow["semester"]    = "";
                        newRow["school_year"] = "";

                        newRow["原始成績"] = "";
                        if (domainnScoreAvgOrignDict.ContainsKey(domainName))
                        {
                            newRow["原始成績"] = domainnScoreAvgOrignDict[domainName];
                        }

                        newRow["成績"] = domainnScoreAvgDict[domainName];
                        newRow["領域"] = domainName;
                        newRow["權數"] = "";
                        if (domainAvgCreditDict.ContainsKey(domainName))
                        {
                            newRow["權數"] = domainAvgCreditDict[domainName];
                        }

                        dt.Rows.Add(newRow);
                    }
                }
            }

            return(dt);
        }