void item_Click(object sender, EventArgs e)
        {
            StudentRecord stud = null;
            ButtonItem bt = sender as ButtonItem;
            if (bt != null)
                stud = bt.Tag as StudentRecord;
            if (stud != null)
            {
                // 檢查是否加入
                int sid = int.Parse(stud.ID);
                if (!_StudDict.ContainsKey(sid))
                {
                    List<UDTScselectDef> dataList = new List<UDTScselectDef>();
                    UDTScselectDef data = new UDTScselectDef();
                    data.StudentID = sid;
                    data.CourseID = int.Parse(PrimaryKey);
                    _MaxSeatNo++;
                    data.SeatNo = _MaxSeatNo;
                    dataList.Add(data);
                    UDTTransfer.UDTSCSelectInsert(dataList);
                    _BGRun();
                }
            }

        }
        private void btnAddTempStudent_Click(object sender, EventArgs e)
        {
            CreateStudentMenuItem();

            List<UDTScselectDef> dataList = new List<UDTScselectDef>();

            foreach (object obj in btnAddTempStudent.SubItems)
            {
                StudentRecord stud = null;
                ButtonItem bt = obj as ButtonItem;
                if (bt != null)
                    stud = bt.Tag as StudentRecord;

                if (stud != null)
                {
                    // 當已經加入跳過
                    int sid = int.Parse(stud.ID);
                    if (_StudDict.ContainsKey(sid))
                        continue;

                    UDTScselectDef data = new UDTScselectDef();
                    data.StudentID = sid;
                    data.CourseID = int.Parse(PrimaryKey);
                    _MaxSeatNo++;
                    data.SeatNo = _MaxSeatNo;
                    dataList.Add(data);
                }
            }
            UDTTransfer.UDTSCSelectInsert(dataList);
            _BGRun();
        }
        /// <summary>
        /// 執行分批匯入
        /// </summary>
        /// <param name="Rows">IRowStream集合</param>
        /// <returns>回傳分批匯入執行完成訊息</returns>
        public override string Import(List<IRowStream> Rows)
        {
            mstrLog.Clear();

            if (mOption.SelectedKeyFields.Count == 5 &&
                mOption.SelectedKeyFields.Contains(constSchoolYear) &&
                mOption.SelectedKeyFields.Contains(constSemester) &&
                mOption.SelectedKeyFields.Contains(constCourseName) &&
                mOption.SelectedKeyFields.Contains(constMonth) &&
                mOption.SelectedKeyFields.Contains(constStudentNumber))
            {
   
                if (mOption.Action == ImportAction.Update)
                {
                    #region Step2:針對每筆匯入每筆資料檢查,判斷是新增或是更新
                    List<UDTScselectDef> InsertRecords = new List<UDTScselectDef>();
                    List<UDTScselectDef> UpdateRecords = new List<UDTScselectDef>();

                    foreach (IRowStream Row in Rows)
                    {
                        string CourseName = Row.GetValue(constCourseName);
                        string SchoolYear = Row.GetValue(constSchoolYear);
                        string Semester = Row.GetValue(constSemester);
                        string Month = Row.GetValue(constMonth);

                        //根據課程名稱、學年度及學期尋找是否有對應的課程
                        string CourseKey = CourseName + "," + SchoolYear + "," + Semester+","+Month;
                        int? CourseID = null;
                        if (mCourseNameIDs.ContainsKey(CourseKey))
                            CourseID = K12.Data.Int.ParseAllowNull(mCourseNameIDs[CourseKey]);
                        string StudentNumber = Row.GetValue(constStudentNumber);
                        int? StudentID = null;
                        if (mStudentNumberIDs.ContainsKey(StudentNumber))
                           StudentID = K12.Data.Int.ParseAllowNull(mStudentNumberIDs[StudentNumber]);

                        UDTScselectDef vSCAttend = null;

                        if (CourseID.HasValue && StudentID.HasValue)
                        {
                            //尋找是否有對應的課程排課資料
                             vSCAttend = mSCAttends
                                .Find(x => 
                                    x.CourseID.Equals(CourseID.Value) &&  
                                    x.StudentID.Equals(StudentID.Value));

                            if (vSCAttend != null)
                            {
                                if (mOption.SelectedFields.Contains(constSeatNo))
                                    vSCAttend.SeatNo = K12.Data.Int.Parse(Row.GetValue(constSeatNo));

                                if (mOption.SelectedFields.Contains(constCourseType))
                                    vSCAttend.Type = Row.GetValue(constCourseType);

                                UpdateRecords.Add(vSCAttend);
                        }
                        else
                        {
                            vSCAttend = new UDTScselectDef();
                            vSCAttend.CourseID = CourseID.Value;
                            vSCAttend.StudentID = StudentID.Value;

                            if (mOption.SelectedFields.Contains(constSeatNo))
                                vSCAttend.SeatNo = K12.Data.Int.Parse(Row.GetValue(constSeatNo));

                            if (mOption.SelectedFields.Contains(constCourseType))
                            vSCAttend.Type = Row.GetValue(constCourseType);
                            
                            InsertRecords.Add(vSCAttend);
                        }
                        #endregion
                        }
                    }

                    #region Step3:實際新增或更新資料
                    if (InsertRecords.Count > 0)
                    {
                        List<string> NewIDs = mHelper.InsertValues(InsertRecords);
                        mstrLog.AppendLine("已新增" + InsertRecords.Count + "筆課程資料。");
                        //在新增完後不需更新mCourseExtensions變數,因為來源資料不允許相同的課程重覆做新增
                    }
                    if (UpdateRecords.Count > 0)
                    {
                        mHelper.UpdateValues(UpdateRecords);
                        mstrLog.AppendLine("已更新" + UpdateRecords.Count + "筆課程資料。");
                        //在更新完後不需更新mCourseExtensions變數,因為來源資料不允許相同的課程重覆做更新
                    }
                    #endregion
                }
                else if (mOption.Action == ImportAction.Delete)
                {
                    #region 刪除資料
                    ////要刪除的排課課程資料
                    //List<CourseExtension> DeleteRecords = new List<CourseExtension>();

                    ////針對每筆記錄
                    //foreach (IRowStream Row in Rows)
                    //{
                    //    //取得鍵值為課程名稱、學年度及學期
                    //    string CourseName = Row.GetValue(constCourseName);
                    //    string SchoolYear = Row.GetValue(constSchoolYear);
                    //    string Semester = Row.GetValue(constSemester);

                    //    //根據課程名稱、學年度及學期尋找是否有對應的課程
                    //    string CourseKey = CourseName + "," + SchoolYear + "," + Semester;
                    //    string CourseID = mCourseNameIDs.ContainsKey(CourseKey) ? mCourseNameIDs[CourseKey] : string.Empty;

                    //    //若有找到課程資料
                    //    if (!string.IsNullOrEmpty(CourseID))
                    //    {
                    //        //尋找是否有對應的排課課程資料
                    //        CourseExtension vCourseExtension = mCourseExtensions
                    //            .Find(x => x.CourseID.Equals(K12.Data.Int.Parse(CourseID)));
                    //        //若有找到則加入到刪除的集合中
                    //        if (vCourseExtension != null)
                    //            DeleteRecords.Add(vCourseExtension);
                    //    }
                    //}

                    ////若是要刪除的集合大於0才執行
                    //if (DeleteRecords.Count > 0)
                    //{
                    //    //mHelper.DeletedValues(DeleteRecords);                      
                    //    //mstrLog.AppendLine("已刪除"+DeleteRecords.Count+"筆排課課程資料。");
                    //    //在刪除完後不需更新mCourseExtensions變數,因為來源資料不允許相同的課程重覆做刪除
                    //}
                    #endregion
                }
            }

            return mstrLog.ToString();
        }
 /// <summary>
 /// 將學生修課記錄,進行排序
 /// </summary>
 private int SortScselect(UDTScselectDef a, UDTScselectDef b)
 {
     return a.SeatNo.CompareTo(b.SeatNo);
 }
        void _bgWorkerCreateData_DoWork(object sender, DoWorkEventArgs e)
        {
            // 清空原有舊資料
            // 課程
            if (_DelCourseIDList.Count > 0)
            {
                List<UDTCourseDef> delCourseList = new List<UDTCourseDef>();
                foreach (UDTCourseDef data in _hasCourseDefList)
                {
                    int coid = int.Parse(data.UID);
                    if (_DelCourseIDList.Contains(coid))
                        delCourseList.Add(data);
                }

                UDTTransfer.UDTCourseDelete(delCourseList);

                // 課程修課
                List<UDTScselectDef> delScselect = new List<UDTScselectDef>();
                foreach (UDTScselectDef data in _hasScselectDefList)
                    if (_DelCourseIDList.Contains(data.CourseID))
                        delScselect.Add(data);

                UDTTransfer.UDTSCSelectDelete(delScselect);
                
                // 課程時間區間
                List<UDTTimeSectionDef> delTimeSectionList = new List<UDTTimeSectionDef>();
                foreach (UDTTimeSectionDef data in _hasTimeSectionDefList)
                    if (_DelCourseIDList.Contains(data.CourseID))
                        delTimeSectionList.Add(data);

                UDTTransfer.UDTTimeSectionDelete(delTimeSectionList);
                
                // 課程缺曠
                List<UDTAttendanceDef> delAttendanceList = new List<UDTAttendanceDef>();
                foreach (UDTAttendanceDef data in _hasAttendanceDefList)
                    if (_DelCourseIDList.Contains(data.CourseID))
                        delAttendanceList.Add(data);

                UDTTransfer.UDTAttendanceDelete(delAttendanceList);
            }


            // 新增課程使用
            List<UDTCourseDef> InsertCourseList = new List<UDTCourseDef>();
            // 取得新增後課程使用
            List<UDTCourseDef> NewInsertedCourseList = new List<UDTCourseDef>();
            // 新增時間區間使用
            List<UDTTimeSectionDef> InsertTimeSectionList = new List<UDTTimeSectionDef>();
            // 新增修課學生
            List<UDTScselectDef> InsertSCSelectList = new List<UDTScselectDef>();

            List<string> courseNameAdd = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J","L","M","N","O","P" }.ToList();
            // 產生課程資料
            foreach (SubjectCourseBase scb in _SubjectCourseBaseList)
            {
                for (int i = 0; i < scb.CreateCount; i++)
                {
                    UDTCourseDef data = new UDTCourseDef();
                    data.SchoolYear = scb.SchoolYear;
                    data.Semester = scb.Semester;
                    data.Month = scb.Month;
                    data.Credit = scb.Credit;
                    data.SubjectType = scb.SubjectType;
                    data.SubjectName = scb.SubjectName;
                    data.SubjectLevel = scb.SubjectLevel;
                    data.DeptName = scb.DeptName;
                    // 課程名稱使用科目名稱加級別
                    if (data.SubjectLevel.HasValue)
                        data.CourseName = scb.SubjectName + QueryData.GetNumber(scb.SubjectLevel.Value.ToString()) +courseNameAdd[i];
                    else
                        data.CourseName = scb.SubjectName + courseNameAdd[i];
                                 
                        InsertCourseList.Add(data);

                    scb.CourseNameList.Add(data.CourseName);
                }
            }

            // 課程名稱與ID對照
            Dictionary<string, int> courseIDDict = new Dictionary<string, int>();

            if (InsertCourseList.Count > 0)
            {
                // 新增課程並取回新增的課程資料
                List<string> CIDList = UDTTransfer.UDTCourseInsert(InsertCourseList);
                NewInsertedCourseList = UDTTransfer.UDTCourseSelectUIDs(CIDList);

                // 課程名稱與ID對照
                foreach (UDTCourseDef data in NewInsertedCourseList)
                {
                    if (!courseIDDict.ContainsKey(data.CourseName))
                        courseIDDict.Add(data.CourseName, int.Parse(data.UID));
                }
                
                // 建立時間區間
                // 取得日期
                List<DateTime> dateList = new List<DateTime>();
                foreach (DataGridViewRow drv in dgDate.Rows)
                    dateList.Add((DateTime)drv.Tag);


                // 處理時間區間
                foreach (SubjectCourseBase scb in _SubjectCourseBaseList)
                {
                    if (scb.PeriodXml == null)
                        continue;

                    List<int> PeriodList = new List<int>();
                    foreach (XElement elm in scb.PeriodXml.Elements("Period"))
                        PeriodList.Add(int.Parse(elm.Value));

                    
                    // 課程名稱
                    foreach (string courseName in scb.CourseNameList)
                    {
                        if (courseIDDict.ContainsKey(courseName))
                        {
                            
                            int cid = courseIDDict[courseName];

                            foreach (DateTime dt in dateList)
                            {
                                foreach (int per in PeriodList)
                                {
                                    UDTTimeSectionDef dataTs = new UDTTimeSectionDef();
                                    dataTs.CourseID = cid;
                                    dataTs.Period = per;
                                    dataTs.Date = dt;
                                    InsertTimeSectionList.Add(dataTs);
                                }
                            }
                        }                    
                    }                        
                }
                // 新增寫入時間區間
                if (InsertTimeSectionList.Count > 0)
                    UDTTransfer.UDTTimeSectionInsert(InsertTimeSectionList);
                
                // 新增修課學生
                foreach (SubjectCourseBase scb in _SubjectCourseBaseList)
                {
                    if (scb.CreateCount < 1)
                        continue;

                    int MaxStudCount = scb.MaxStudentCount;

                    int NewCount = (int)Math.Round(((decimal)scb.StudentIDList.Count / (decimal)scb.CreateCount), 0);
                    if (NewCount > MaxStudCount)
                        MaxStudCount = NewCount;

                    List<int> cousreIDList = new List<int>();
                    foreach (string name in scb.CourseNameList)
                    {
                        if (courseIDDict.ContainsKey(name))
                            cousreIDList.Add(courseIDDict[name]);
                    }
                
                    // 修課學生
                    int courseIdx = 0, seatno = 1;
                    if (cousreIDList.Count > 0)
                    {
                        foreach (SubjectCourseStudentBase stud in scb.StudentIDList)
                        {

                            if (seatno > MaxStudCount)
                            {
                                seatno = 1;
                                courseIdx++;
                            }

                            UDTScselectDef scselect = new UDTScselectDef();
                            scselect.CourseID = cousreIDList[courseIdx];
                            scselect.SeatNo = seatno;
                            scselect.StudentID = stud.StudentID;
                            scselect.Type = stud.Type;
                            InsertSCSelectList.Add(scselect);
                            seatno++;
                        }
                    }
                }
                // 新增修課學生
                if (InsertSCSelectList.Count > 0)
                {
                    UDTTransfer.UDTSCSelectInsert(InsertSCSelectList);
                }
            }
   
        }