using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Data.Entity;
using Bowin.Common.Linq;
using Bowin.Common.Linq.Entity;
using EMIS.ViewModel.SelectCourse;
using EMIS.ViewModel;
using EMIS.Entities;
using EMIS.DataLogic.SelectCourse;
using EMIS.DataLogic.Repositories;
using EMIS.CommonLogic.SystemServices;
using EMIS.Utility.FormValidate;
using EMIS.ViewModel.EnrollManage.SpecialtyManage;
using EMIS.ViewModel.UniversityManage.ClassroomManage;
using EMIS.DataLogic.EducationSchedule;
using EMIS.DataLogic.SelectCourse.SelectCourseResult;
using System.Transactions;

namespace EMIS.CommonLogic.SelectCourse
{
    public class ExecutableFreeSelectionCouseServices : BaseWorkflowServices<EM_FreeSelectionCouseApply>, IExecutableFreeSelectionCouseServices
    {
        public FreeSelectionCoursePlanDAL FreeSelectionCoursePlanDAL { get; set; }

        public ExecutableFreeSelectionCouseRepository ExecutableFreeSelectionCouseRepository { get; set; }

        public ExecutableFreeSelectionCouseDAL ExecutableFreeSelectionCouseDAL { get; set; }

        public FreeSelectionCourseDAL FreeSelectionCourseDAL { get; set; }

        public FreeSelectionCouseTeachingModeRepository FreeSelectionCouseTeachingModeRepository { get; set; }

        public ClassroomScheduleDAL ClassroomScheduleDAL { get; set; }

        public SelectCourseResultDAL SelectCourseResultDAL { get; set; }

        public IStudentSelectCourseServices IStudentSelectCourseServices { get; set; }

        public IGridResultSet<ExecutableFreeSelectionCouseView> GetExecutableFreeSelectionCouseViewGrid(ConfiguretView configuretView,
            Guid? schoolyearID, Guid? campusID, Guid? collegeID, Guid? departmentID, int? Status, int? isOpened, int pageIndex, int pageSize)
        {
            Expression<Func<EM_ExecutableFreeSelectionCouse, bool>> exp = (x => x.RecordStatus > (int)SYS_STATUS.UNUSABLE);
            if (schoolyearID.HasValue)
                exp = exp.And(x => x.SchoolyearID == schoolyearID);
            if (campusID.HasValue)
                exp = exp.And(x => x.CF_Department.CF_College.CampusID == campusID);
            if (collegeID.HasValue)
                exp = exp.And(x => x.CF_Department.CollegeID == collegeID);
            if (departmentID.HasValue)
                exp = exp.And(x => x.DepartmentID == departmentID);
            if (isOpened.HasValue)
                exp = exp.And(x => x.IsOpened == (isOpened == 1 ? true : false));
            if (Status.HasValue)
                exp = exp.And(x => x.RecordStatus == Status);
            var freeSelectionCourseView = ExecutableFreeSelectionCouseDAL.GetExecutableFreeSelectionCouseViewQueryable(exp);
            //if (configuretView.Attribute == "TeacherName" && !string.IsNullOrEmpty(configuretView.ConditionValue))
            //{
            //    var educationMissionClassID = query.Select(x => x.EducationMissionClassID).ToList();
            //    //获取查询结果教学任务所有教师
            //    var missionClassTeacherList = educationMissionClassDAL.GetMissionClassTeacherQuery(x => educationMissionClassID.Contains(x.EducationMissionClassID)).ToList();
            //    //按教师姓名条件查询对应教学任务
            //    missionClassTeacherList = missionClassTeacherList.Where(x => x.Name == configuretView.ConditionValue).ToList();
            //    var missionClassIDList = missionClassTeacherList.Select(x => x.EducationMissionClassID).ToList();
            //    //由于教学任务可能有多个教师授课,所以还要再拿筛选后的教学任务在匹配一次教师
            //    missionClassTeacherList = educationMissionClassDAL.GetMissionClassTeacherQuery(x => missionClassIDList.Contains(x.EducationMissionClassID)).ToList();
            //    query = query.Where(x => missionClassIDList.Contains(x.EducationMissionClassID));
            //    var resultQuery = this.GetQueryByDataRangeByDepartment(query).OrderByDescending(x => x.SchoolyearCode)
            //    .ThenBy(x => x.CollegeNo.Length).ThenBy(x => x.CollegeNo).ThenByDescending(x => x.GradeYearID)
            //    .ThenBy(x => x.StandardID).ThenBy(x => x.CourseName).ThenBy(x => x.OrderNo).ThenBy(x => x.Name);
            //    var result = resultQuery.ToGridResultSet<EducationMissionClassView>(pageIndex, pageSize);
            //    result.rows.ForEach(x => x.MissionClassTeacherView = new HashSet<MissionClassTeacherView>(missionClassTeacherList.Where(y => y.EducationMissionClassID == x.EducationMissionClassID)));
            //    return result;
            //}
            var teacherView = ExecutableFreeSelectionCouseDAL.GetExecutableFreeSelectionCouseTeacherViewQueryable(exp);
            var schedulingView = SelectCourseResultDAL.GetScheduling(exp).ToList();
            var efsdcIDList = freeSelectionCourseView.Select(x => x.ExecutableFreeSelectionCouseID).ToList();
            if (configuretView.Attribute == "TeacherName" && !string.IsNullOrEmpty(configuretView.ConditionValue))
            {
                teacherView = teacherView.Where(x => x.Name.Contains(configuretView.ConditionValue));
                efsdcIDList = teacherView.Select(x => x.ExecutableFreeSelectionCouseID).ToList();
            }
            else if (!string.IsNullOrEmpty(configuretView.ConditionValue))
            {
                freeSelectionCourseView = freeSelectionCourseView.DynamicWhere(configuretView.Attribute, configuretView.Condition, configuretView.ConditionValue);
            }
            var result = this.GetQueryByDataRangeByCollege(freeSelectionCourseView).Where(x => efsdcIDList.Contains(x.ExecutableFreeSelectionCouseID)).OrderBy(x => x.SchoolyearCode).
                ThenBy(x => x.CourseCode).ThenBy(x => x.DefaultClassName).ToGridResultSet(pageIndex, pageSize);
            result.rows.ForEach(x =>
            {
                x.Teachers = new HashSet<ExecutableFreeSelectionCouseTeacherListView>(teacherView
                    .Where(w => x.ExecutableFreeSelectionCouseID == w.ExecutableFreeSelectionCouseID));

            });
            if (schedulingView.Count > 0)
            {
                var schedulingList = IStudentSelectCourseServices.GetWeekdayTimesSegmentName(schedulingView);
                result.rows.ForEach(x =>
                {
                    var list = schedulingList.Where(w => w.ID == x.ExecutableFreeSelectionCouseID);
                    x.WeekdayTimesSegmentName = string.Join(";", list.OrderBy(w => w.Weekday).Select(w => w.WeekdayTimesSegmentName));
                });
            }
            return result;
        }

        public List<ExecutableFreeSelectionCouseView> GetExecutableFreeSelectionCouseViewList(ConfiguretView configuretView,
            Guid? schoolyearID, Guid? campusID, Guid? collegeID, Guid? departmentID, int? Status, int? isOpened)
        {
            Expression<Func<EM_ExecutableFreeSelectionCouse, bool>> exp = (x => x.RecordStatus > (int)SYS_STATUS.UNUSABLE);
            if (schoolyearID.HasValue)
                exp = exp.And(x => x.SchoolyearID == schoolyearID);
            if (campusID.HasValue)
                exp = exp.And(x => x.CF_Department.CF_College.CampusID == campusID);
            if (collegeID.HasValue)
                exp = exp.And(x => x.CF_Department.CollegeID == collegeID);
            if (departmentID.HasValue)
                exp = exp.And(x => x.DepartmentID == departmentID);
            if (isOpened.HasValue)
                exp = exp.And(x => x.IsOpened == (isOpened == 1 ? true : false));
            if (Status.HasValue)
                exp = exp.And(x => x.RecordStatus == Status);
            var freeSelectionCourseView = ExecutableFreeSelectionCouseDAL.GetExecutableFreeSelectionCouseViewQueryable(exp);
            var teacherView = ExecutableFreeSelectionCouseDAL.GetExecutableFreeSelectionCouseTeacherViewQueryable(exp);
            var efsdcIDList = freeSelectionCourseView.Select(x => x.ExecutableFreeSelectionCouseID).ToList();
            if (configuretView.Attribute == "TeacherName" && !string.IsNullOrEmpty(configuretView.ConditionValue))
            {
                teacherView = teacherView.Where(x => x.Name.Contains(configuretView.ConditionValue));
                efsdcIDList = teacherView.Select(x => x.ExecutableFreeSelectionCouseID).ToList();
            }
            else if (!string.IsNullOrEmpty(configuretView.ConditionValue))
            {
                freeSelectionCourseView = freeSelectionCourseView.DynamicWhere(configuretView.Attribute, configuretView.Condition, configuretView.ConditionValue);
            }
            var schedulingView = SelectCourseResultDAL.GetScheduling(exp).ToList();

            var result = freeSelectionCourseView.Where(x => efsdcIDList.Contains(x.ExecutableFreeSelectionCouseID)).OrderBy(x => x.SchoolyearCode).ThenBy(x => x.CourseCode).ThenBy(x => x.DefaultClassName).ToList();
            result.ForEach(x =>
            {
                x.Teachers = new HashSet<ExecutableFreeSelectionCouseTeacherListView>(teacherView
                    .Where(w => x.ExecutableFreeSelectionCouseID == w.ExecutableFreeSelectionCouseID));

            });
            if (schedulingView.Count > 0)
            {
                var schedulingList = IStudentSelectCourseServices.GetWeekdayTimesSegmentName(schedulingView);
                result.ForEach(x =>
                {
                    var list = schedulingList.Where(w => w.ID == x.ExecutableFreeSelectionCouseID);
                    x.WeekdayTimesSegmentName = string.Join(";", list.OrderBy(w => w.Weekday).Select(w => w.WeekdayTimesSegmentName));
                });
            }
            return result;
        }

        public EM_FreeSelectionCouse GetFreeSelectionCourse(Guid? freeSelectionCourseID)
        {
            System.Linq.Expressions.Expression<Func<EM_FreeSelectionCouse, bool>> expression =
                (x => x.RecordStatus > (int)SYS_STATUS.UNUSABLE);
            expression = (x => x.FreeSelectionCouseID == freeSelectionCourseID);
            return FreeSelectionCourseDAL.FreeSelectionCouseRepository.GetSingle(expression, (x => x.CF_Department), (x => x.EM_Coursematerial));
        }

        public FreeSelectionCourseView GetFreeSelectionCourseView(Guid? freeSelectionCourseID)
        {
            var query = FreeSelectionCourseDAL.GetFreeSelectionCourseViewQueryable(x => x.RecordStatus > (int)SYS_STATUS.UNUSABLE);
            return query.Where(x => x.FreeSelectionCouseID == freeSelectionCourseID).FirstOrDefault();
        }

        public EM_FreeSelectionCouseTeachingSetting GetFreeSelectionCourseTeachingSetting(Guid? freeSelectionCourseID)
        {
            //查询条件
            System.Linq.Expressions.Expression<Func<EM_FreeSelectionCouseTeachingSetting, bool>> expression = (x => true);
            expression = (x => x.FreeSelectionCouseID == freeSelectionCourseID);
            return FreeSelectionCourseDAL.FreeSelectionCouseTeachingSettingRepository.GetSingle(expression);
        }

        private bool TeachingModeTypeAdd(List<int> list, Guid? ExecutableFreeSelectionCouseID)
        {
            try
            {
                if (list.Count > 0)
                {
                    UnitOfWork.Delete<EM_ExecutableFreeSelectionCouseTeachingMode>(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouseID);
                    foreach (var i in list)
                    {
                        EM_ExecutableFreeSelectionCouseTeachingMode teachingModeType = new EM_ExecutableFreeSelectionCouseTeachingMode();
                        teachingModeType.ExecutableFreeSelectionCouseTeachingModeID = Guid.NewGuid();
                        teachingModeType.ExecutableFreeSelectionCouseID = ExecutableFreeSelectionCouseID;
                        teachingModeType.TeachingModeID = i;
                        this.SetNewStatus(teachingModeType);
                        UnitOfWork.Add(teachingModeType);
                    }
                }
                return true;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 任选设定获取授课方式
        /// </summary>
        /// <param name="ExecutableFreeSelectionCouseID"></param>
        /// <returns></returns>
        public List<int> GetCourseTeachingModeType(Guid? ExecutableFreeSelectionCouseID)
        {
            var list = ExecutableFreeSelectionCouseDAL.GetTeachingModeType(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouseID)
               .Select(x => x.Value ?? 0).ToList();
            if (list.Count > 0)
                list.Add((int)EMIS.ViewModel.CF_TeachingMode.Theory);
            return list;
        }

        /// <summary>
        /// 任选设定可选年级表
        /// </summary>
        /// <param name="ExecutableFreeSelectionCouseID"></param>
        /// <returns></returns>
        public List<int> GetCourseGradeYear(Guid? ExecutableFreeSelectionCouseID)
        {
            List<int> list = new List<int>();
            return ExecutableFreeSelectionCouseDAL.GetGradeYear(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouseID)
                .Select(x => x.Value ?? 0).ToList();
        }

        public EM_FreeSelectionCouse GetFreeSelectionCourseCourse(Guid? coursematerialID)
        {
            //查询条件
            System.Linq.Expressions.Expression<Func<EM_FreeSelectionCouse, bool>> expression = (x => x.RecordStatus > (int)SYS_STATUS.UNUSABLE);
            expression = (x => x.CoursematerialID == coursematerialID);
            return FreeSelectionCourseDAL.FreeSelectionCouseRepository.GetSingle(expression, (x => x.CF_Department), (x => x.EM_Coursematerial));
        }


        public ExecutableFreeSelectionCouseView GetExecutableFreeSelectionCouseView(Guid? ExecutableFreeSelectionCouseID)
        {
            return ExecutableFreeSelectionCouseDAL.GetExecutableFreeSelectionCouseViewQueryable(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouseID)
                .FirstOrDefault();
        }

        public EM_ExecutableFreeSelectionCouse GetExecutableFreeSelectionCouse(Guid? ExecutableFreeSelectionCouseID)
        {
            //查询条件
            System.Linq.Expressions.Expression<Func<EM_ExecutableFreeSelectionCouse, bool>> expression =
                (x => x.RecordStatus > (int)SYS_STATUS.UNUSABLE);
            expression = (x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouseID);
            return ExecutableFreeSelectionCouseRepository.GetSingle(expression, x => x.EM_ExecutableFreeSelectionCouseSpecialty);
        }



        public bool ExecutableFreeSelectionCouseAdd(ExecutableFreeSelectionCouseView ExecutableFreeSelectionCouse, IList<ExecutableFreeSelectionCouseTeacherListView> teacherList, IList<ExecutableFreeSelectionCouseSpecialtyListView> specialtyList, IList<ExecutableFreeSelectionCouseSchedulingView> schedulingList, out int? type)
        {
            try
            {
                var ApprovalStatus = this.GetCorrectEndStatus();
                //schedulingList = schedulingList.Where(x => x.CoursesTimeID != null && x.Weekday != null && x.ClassroomID != null).ToList();
                if (schedulingList.Where(x => x.CoursesTimeID == null || x.Weekday == null).ToList().Count > 0)
                {
                    throw new Exception("排课信息不能为空");
                }
                //else
                //{
                //    var repeat = schedulingList.GroupBy(x => new { x.Weekday, x.CoursesTimeID }).Max().ToList();
                //    if (repeat.Count > 1)
                //        throw new Exception("上课时间不能重复");
                //}
                var SpecialtyIDList = specialtyList.Select(x => x.SpecialtyID).ToList();
                var freeSelectionCourse = this.GetFreeSelectionCourseView(ExecutableFreeSelectionCouse.FreeSelectionCouseID);
                if (this.FreeSelectionCoursePlanDAL.FreeSelectionCouseApplyRepository
                    .GetList(x => x.FreeSelectionCouseID == ExecutableFreeSelectionCouse.FreeSelectionCouseID
                            && x.SchoolyearID == ExecutableFreeSelectionCouse.SchoolyearID
                            && x.DefaultClassName == ExecutableFreeSelectionCouse.DefaultClassName
                            && x.DepartmentID == ExecutableFreeSelectionCouse.DepartmentID
                            && x.CourseTypeID == ExecutableFreeSelectionCouse.CourseTypeID
                            && x.EM_FreeSelectionCouseApplySpecialty.Any(w => SpecialtyIDList.Contains(w.SpecialtyID))
                            ).Count() > 0)
                {
                    throw new Exception(freeSelectionCourse.CourseName + "对应的" + ExecutableFreeSelectionCouse.DefaultClassName + "已在该学期申请开课并等待审核。");
                }
                if (this.ExecutableFreeSelectionCouseRepository
                    .GetList(x => x.FreeSelectionCouseID == ExecutableFreeSelectionCouse.FreeSelectionCouseID
                            && x.SchoolyearID == ExecutableFreeSelectionCouse.SchoolyearID
                            && x.DefaultClassName == ExecutableFreeSelectionCouse.DefaultClassName
                            && x.DepartmentID == ExecutableFreeSelectionCouse.DepartmentID
                            && x.CourseTypeID == ExecutableFreeSelectionCouse.CourseTypeID
                            && x.EM_ExecutableFreeSelectionCouseSpecialty.Any(w => SpecialtyIDList.Contains(w.SpecialtyID))
                            ).Count() > 0)
                {
                    throw new Exception(freeSelectionCourse.CourseName + "对应的" + ExecutableFreeSelectionCouse.DefaultClassName + "在该学期已经设置任选,无需重复设置。");
                }
                //如果IsNeedVerify为false时,不验证冲突
                if (ExecutableFreeSelectionCouse.IsNeedVerify != false)
                {
                    //判断教师和教室冲突,如果有冲突type返回1,页面js根据type弹出选择框,用户可选择继续保存或不保存,如果不返回1,弹出一般的错误提示框
                    foreach (var scheduling in schedulingList)
                    {
                        //教室不为空时判断教室冲突
                        if (ExecutableFreeSelectionCouse.ClassroomID != null)
                        {
                            //任选设定冲突
                            var repeatExecutableClassroom = ExecutableFreeSelectionCouseDAL.GetRepeatExecutableFreeSelectionCouseClassroom(scheduling.CoursesTimeID, ExecutableFreeSelectionCouse.ClassroomID, scheduling.Weekday, ExecutableFreeSelectionCouse.SchoolyearID, ExecutableFreeSelectionCouse.StartWeeklyNum, ExecutableFreeSelectionCouse.EndWeeklyNum).FirstOrDefault();
                            if (repeatExecutableClassroom != null)
                            {
                                type = 1;
                                throw new Exception("检测到排课冲突," + repeatExecutableClassroom.WeekdayName + "第" + repeatExecutableClassroom.StartTimes + "节时间段教室与任选设定【" + repeatExecutableClassroom.DefaultClassName + "】有冲突");
                            }

                            //任选申请冲突
                            var repeatApplyClassroom = ExecutableFreeSelectionCouseDAL.GetRepeatFreeSelectionCouseApplyClassroom(scheduling.CoursesTimeID, ExecutableFreeSelectionCouse.ClassroomID, scheduling.Weekday, ExecutableFreeSelectionCouse.SchoolyearID, ExecutableFreeSelectionCouse.StartWeeklyNum, ExecutableFreeSelectionCouse.EndWeeklyNum, ApprovalStatus).FirstOrDefault();
                            if (repeatApplyClassroom != null)
                            {
                                type = 1;
                                throw new Exception("检测到排课冲突," + repeatApplyClassroom.WeekdayName + "第" + repeatApplyClassroom.StartTimes + "节时间段教室与开课申请【" + repeatApplyClassroom.DefaultClassName + "】有冲突");
                            }
                            //教学任务冲突

                            var repeatEducationClassroom = ExecutableFreeSelectionCouseDAL.GetRepeatEducationMissionClassroom(scheduling.CoursesTimeID, ExecutableFreeSelectionCouse.ClassroomID, scheduling.Weekday, ExecutableFreeSelectionCouse.SchoolyearID, ExecutableFreeSelectionCouse.StartWeeklyNum, ExecutableFreeSelectionCouse.EndWeeklyNum).FirstOrDefault();
                            if (repeatEducationClassroom != null)
                            {
                                type = 1;
                                throw new Exception("检测到排课冲突," + "该设定上课时间段教室与教学任务班【" + repeatEducationClassroom.DefaultClassName + "】有冲突");
                            }
                        }
                        //判断教师冲突
                        //任选设定冲突
                        var repeatExecutableTeacher = ExecutableFreeSelectionCouseDAL.GetRepeatExecutableFreeSelectionCouseTeacher(teacherList.Select(x => x.UserID).ToList(), scheduling.CoursesTimeID, scheduling.Weekday, ExecutableFreeSelectionCouse.SchoolyearID, ExecutableFreeSelectionCouse.StartWeeklyNum, ExecutableFreeSelectionCouse.EndWeeklyNum).FirstOrDefault();
                        if (repeatExecutableTeacher != null)
                        {
                            type = 1;
                            throw new Exception("检测到排课冲突," + repeatExecutableTeacher.WeekdayName + "第" + repeatExecutableTeacher.StartTimes + "节时间段教师与任选设定【" + repeatExecutableTeacher.DefaultClassName + "】有冲突");
                        }
                        //任选申请冲突
                        var repeatApplyTeacher = ExecutableFreeSelectionCouseDAL.GetRepeatFreeSelectionCouseApplyTeacher(teacherList.Select(x => x.UserID).ToList(), scheduling.CoursesTimeID, scheduling.Weekday, ExecutableFreeSelectionCouse.SchoolyearID, ExecutableFreeSelectionCouse.StartWeeklyNum, ExecutableFreeSelectionCouse.EndWeeklyNum, ApprovalStatus).FirstOrDefault();
                        if (repeatApplyTeacher != null)
                        {
                            type = 1;
                            throw new Exception("检测到排课冲突," + repeatApplyTeacher.WeekdayName + "第" + repeatApplyTeacher.StartTimes + "节时间段教师与开课申请【" + repeatApplyTeacher.DefaultClassName + "】有冲突");
                        }
                        //教学任务冲突
                        var repeatEducationTeacher = ExecutableFreeSelectionCouseDAL.GetRepeatEducationMissionTeacher(teacherList.Select(x => x.UserID).ToList(), scheduling.CoursesTimeID, scheduling.Weekday, ExecutableFreeSelectionCouse.SchoolyearID, ExecutableFreeSelectionCouse.StartWeeklyNum, ExecutableFreeSelectionCouse.EndWeeklyNum).FirstOrDefault();
                        if (repeatEducationTeacher != null)
                        {
                            type = 1;
                            throw new Exception("检测到排课冲突," + "该设定上课时间段教师与教学任务班【" + repeatEducationTeacher.DefaultClassName + "】有冲突");
                        }
                    }
                }

                using (TransactionScope ts = new TransactionScope())
                {
                    //任选设定表
                    EM_ExecutableFreeSelectionCouse ExecutableFreeSelectionCouseEntity = new EM_ExecutableFreeSelectionCouse();
                    ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID = Guid.NewGuid();
                    ExecutableFreeSelectionCouseEntity.FreeSelectionCouseID = ExecutableFreeSelectionCouse.FreeSelectionCouseID;
                    ExecutableFreeSelectionCouseEntity.SchoolyearID = ExecutableFreeSelectionCouse.SchoolyearID;
                    ExecutableFreeSelectionCouseEntity.DefaultClassName = ExecutableFreeSelectionCouse.DefaultClassName;
                    //ExecutableFreeSelectionCouseEntity.DefaultClassName = freeSelectionCourse.DepartmentName + "-"
                    //                                                + freeSelectionCourse.CourseName + "班(任选)";
                    ExecutableFreeSelectionCouseEntity.DepartmentID = ExecutableFreeSelectionCouse.DepartmentID;
                    ExecutableFreeSelectionCouseEntity.CourseStructureID = ExecutableFreeSelectionCouse.CourseStructureID;
                    ExecutableFreeSelectionCouseEntity.CourseCategoryID = ExecutableFreeSelectionCouse.CourseCategoryID;
                    ExecutableFreeSelectionCouseEntity.CourseTypeID = ExecutableFreeSelectionCouse.CourseTypeID;
                    ExecutableFreeSelectionCouseEntity.CourseQualityID = ExecutableFreeSelectionCouse.CourseQualityID;
                    ExecutableFreeSelectionCouseEntity.PracticeTypeID = ExecutableFreeSelectionCouse.PracticeTypeID;
                    ExecutableFreeSelectionCouseEntity.ExaminationModeID = ExecutableFreeSelectionCouse.ExaminationModeID;
                    ExecutableFreeSelectionCouseEntity.TeachinglanguageID = ExecutableFreeSelectionCouse.TeachinglanguageID;
                    ExecutableFreeSelectionCouseEntity.IsNeedMaterial = ExecutableFreeSelectionCouse.IsNeedMaterial;
                    ExecutableFreeSelectionCouseEntity.PeopleNumlower = ExecutableFreeSelectionCouse.PeopleNumlower;
                    ExecutableFreeSelectionCouseEntity.PeopleNumlimit = ExecutableFreeSelectionCouse.PeopleNumlimit;
                    ExecutableFreeSelectionCouseEntity.HandleModeID = ExecutableFreeSelectionCouse.HandleModeID;
                    ExecutableFreeSelectionCouseEntity.IsOpened = ExecutableFreeSelectionCouse.IsOpened;
                    ExecutableFreeSelectionCouseEntity.ResultTypeID = ExecutableFreeSelectionCouse.ResultTypeID;
                    ExecutableFreeSelectionCouseEntity.Remarks = ExecutableFreeSelectionCouse.Remarks;
                    this.SetNewStatus(ExecutableFreeSelectionCouseEntity);
                    UnitOfWork.Add(ExecutableFreeSelectionCouseEntity);

                    //任选设定教学设置表
                    EM_ExecutableFreeSelectionCouseTeachingSetting freeSelectionCourseTeachingSetting;
                    freeSelectionCourseTeachingSetting = new EM_ExecutableFreeSelectionCouseTeachingSetting();
                    freeSelectionCourseTeachingSetting.ExecutableFreeSelectionCouseID = ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID;
                    freeSelectionCourseTeachingSetting.Credit = ExecutableFreeSelectionCouse.Credit;
                    freeSelectionCourseTeachingSetting.TheoryCourse = ExecutableFreeSelectionCouse.TheoryCourse;
                    freeSelectionCourseTeachingSetting.Practicehours = ExecutableFreeSelectionCouse.Practicehours;
                    freeSelectionCourseTeachingSetting.Trialhours = ExecutableFreeSelectionCouse.Trialhours;
                    freeSelectionCourseTeachingSetting.WeeklyNum = ExecutableFreeSelectionCouse.WeeklyNum;
                    freeSelectionCourseTeachingSetting.TheoryWeeklyNum = ExecutableFreeSelectionCouse.TheoryWeeklyNum;
                    freeSelectionCourseTeachingSetting.PracticeWeeklyNum = ExecutableFreeSelectionCouse.PracticeWeeklyNum;
                    freeSelectionCourseTeachingSetting.TrialWeeklyNum = ExecutableFreeSelectionCouse.TrialWeeklyNum;
                    freeSelectionCourseTeachingSetting.StartWeeklyNum = ExecutableFreeSelectionCouse.StartWeeklyNum;
                    freeSelectionCourseTeachingSetting.EndWeeklyNum = ExecutableFreeSelectionCouse.EndWeeklyNum;
                    freeSelectionCourseTeachingSetting.WeeklyHours = ExecutableFreeSelectionCouse.WeeklyHours;
                    //SetNewStatus(freeSelectionCourseTeachingSetting);
                    UnitOfWork.Add(freeSelectionCourseTeachingSetting);

                    //任选设定课程表
                    //首先查出至少一个教室
                    schedulingList.Where(x => x.CoursesTimeID != null && x.Weekday != null).ToList().ForEach(x =>
                    {
                        var scheduling = new EM_ExecutableFreeSelectionCouseScheduling
                        {
                            ExecutableFreeSelectionCouseSchedulingID = Guid.NewGuid(),
                            ExecutableFreeSelectionCouseID = ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID,
                            ClassroomID = ExecutableFreeSelectionCouse.ClassroomID,  //这一行没有教室时,填查询到的其它行的教室,如果都没有就为空
                            CoursesTimeID = x.CoursesTimeID,
                            Weekday = x.Weekday,
                        };
                        this.SetNewStatus(scheduling);
                        this.UnitOfWork.Add(scheduling);
                    });

                    //任选设定授课方式表,没有时默认为理论
                    if (ExecutableFreeSelectionCouse.TeachingModeID != null)
                    {
                        var list = ExecutableFreeSelectionCouse.TeachingModeID;
                        if (list.Count > 0)
                        {
                            //UnitOfWork.Delete<EM_FreeSelectionCouseTeachingMode>(x => x.FreeSelectionCouseID == ExecutableFreeSelectionCouse.freeSelectionCourseID);
                            foreach (var i in list)
                            {
                                EM_ExecutableFreeSelectionCouseTeachingMode teachingModeType = new EM_ExecutableFreeSelectionCouseTeachingMode();
                                teachingModeType.ExecutableFreeSelectionCouseTeachingModeID = Guid.NewGuid();
                                teachingModeType.ExecutableFreeSelectionCouseID = ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID;
                                teachingModeType.TeachingModeID = i;
                                //this.SetNewStatus(teachingModeType);
                                UnitOfWork.Add(teachingModeType);
                            }
                        }
                    }

                    else
                    {
                        EM_ExecutableFreeSelectionCouseTeachingMode teachingModeType = new EM_ExecutableFreeSelectionCouseTeachingMode();
                        teachingModeType.ExecutableFreeSelectionCouseTeachingModeID = Guid.NewGuid();
                        teachingModeType.ExecutableFreeSelectionCouseID = ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID;
                        teachingModeType.TeachingModeID = (int)EMIS.ViewModel.CF_TeachingMode.Theory;
                        UnitOfWork.Add(teachingModeType);
                    }

                    //任选设定年级范围表
                    if (ExecutableFreeSelectionCouse.GradeYear != null)
                    {
                        var list = ExecutableFreeSelectionCouse.GradeYear;
                        if (list.Count > 0)
                        {
                            //UnitOfWork.Delete<EM_FreeSelectionCouseTeachingMode>(x => x.FreeSelectionCouseID == ExecutableFreeSelectionCouse.freeSelectionCourseID);
                            foreach (var i in list)
                            {
                                EM_ExecutableFreeSelectionCouseGradeYear gradeYear = new EM_ExecutableFreeSelectionCouseGradeYear();
                                gradeYear.ExecutableFreeSelectionCouseGradeYearID = Guid.NewGuid();
                                gradeYear.ExecutableFreeSelectionCouseID = ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID;
                                gradeYear.GradeYear = i;
                                this.SetNewStatus(gradeYear);
                                UnitOfWork.Add(gradeYear);
                            }
                        }
                    }

                    //任选设定专业范围表
                    if (specialtyList.Count > 0)
                    {

                        //UnitOfWork.Delete<EM_FreeSelectionCouseTeachingMode>(x => x.FreeSelectionCouseID == ExecutableFreeSelectionCouse.freeSelectionCourseID);
                        foreach (var i in specialtyList)
                        {
                            EM_ExecutableFreeSelectionCouseSpecialty specialty = new EM_ExecutableFreeSelectionCouseSpecialty();
                            specialty.ExecutableFreeSelectionCouseSpecialtyID = Guid.NewGuid();
                            specialty.ExecutableFreeSelectionCouseID = ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID;
                            specialty.SpecialtyID = i.SpecialtyID;
                            this.SetNewStatus(specialty);
                            UnitOfWork.Add(specialty);
                        }

                    }

                    //任选设定教师表
                    teacherList.ToList().ForEach(x =>
                    {
                        var freeSelectionTeacher = new EM_ExecutableFreeSelectionCouseTeacher
                        {
                            ExecutableFreeSelectionCouseStaffID = Guid.NewGuid(),
                            ExecutableFreeSelectionCouseID = ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID,
                            UserID = x.UserID,
                            TeachingMethod = x.TeachingMethod
                        };
                        this.SetNewStatus(freeSelectionTeacher);
                        this.UnitOfWork.Add(freeSelectionTeacher);
                    });


                    ExecutableFreeSelectionCouseEntity.RecordStatus = (int)EMIS.ViewModel.EM_SelectCourseResultStatus.NotOpen;
                    UnitOfWork.Commit();
                    ts.Complete();
                }
                type = 0;
                return true;
            }
            catch (Exception)
            {

                throw;
            }
        }

        public bool ExecutableFreeSelectionCouseUpdate(ExecutableFreeSelectionCouseView ExecutableFreeSelectionCouse, IList<ExecutableFreeSelectionCouseTeacherListView> teacherList, IList<ExecutableFreeSelectionCouseSpecialtyListView> specialtyList, IList<ExecutableFreeSelectionCouseSchedulingView> schedulingList, out int? type)
        {
            try
            {
                var ApprovalStatus = this.GetCorrectEndStatus();
                //schedulingList = schedulingList.Where(x => x.CoursesTimeID != null && x.Weekday != null && x.ClassroomID != null).ToList();
                if (schedulingList.Where(x => x.CoursesTimeID == null || x.Weekday == null).ToList().Count > 0)
                {
                    throw new Exception("排课信息不能为空");
                }


                var distinctSchedulingList = schedulingList.GroupBy(x => new { x.Weekday, x.CoursesTimeID }).Select(x => new { Weekday = x.Key.Weekday, CoursesTimeID = x.Max(a => a.CoursesTimeID) }).ToList();
                //else
                //{
                //    var repeat = schedulingList.GroupBy(x => new { x.Weekday, x.CoursesTimeID }).Max().ToList();
                //    if (repeat.Count > 1)
                //        throw new Exception("上课时间不能重复");
                //}

                var SpecialtyIDList = specialtyList.Select(x => x.SpecialtyID).ToList();
                var freeSelectionCourse = this.GetFreeSelectionCourseView(ExecutableFreeSelectionCouse.FreeSelectionCouseID);
                var status = this.GetCorrectEndStatus();
                if (this.FreeSelectionCoursePlanDAL.FreeSelectionCouseApplyRepository
                    .GetList(x => x.FreeSelectionCouseID == ExecutableFreeSelectionCouse.FreeSelectionCouseID
                            && x.SchoolyearID == ExecutableFreeSelectionCouse.SchoolyearID
                            && x.DepartmentID == ExecutableFreeSelectionCouse.DepartmentID
                            && x.CourseTypeID == ExecutableFreeSelectionCouse.CourseTypeID
                            && x.EM_FreeSelectionCouseApplySpecialty.Any(w => SpecialtyIDList.Contains(w.SpecialtyID))
                            && x.ApprovalStatus != status
                    && x.DefaultClassName == ExecutableFreeSelectionCouse.DefaultClassName
                            ).Count() > 0)
                {
                    throw new Exception(freeSelectionCourse.CourseName + "对应的" + ExecutableFreeSelectionCouse.DefaultClassName + "在该学期已经申请过了,无需重复申请。");
                }

                if (this.ExecutableFreeSelectionCouseRepository
                    .GetList(x => x.FreeSelectionCouseID == ExecutableFreeSelectionCouse.FreeSelectionCouseID
                            && x.SchoolyearID == ExecutableFreeSelectionCouse.SchoolyearID
                        && x.DefaultClassName == ExecutableFreeSelectionCouse.DefaultClassName
                            && x.DepartmentID == ExecutableFreeSelectionCouse.DepartmentID
                            && x.EM_ExecutableFreeSelectionCouseSpecialty.Any(w => SpecialtyIDList.Contains(w.SpecialtyID))
                            && x.ExecutableFreeSelectionCouseID != ExecutableFreeSelectionCouse.ExecutableFreeSelectionCouseID
                            ).Count() > 0)
                {
                    throw new Exception(freeSelectionCourse.CourseName + "在该学期已经存在。");
                }
                //如果IsNeedVerify为false时,不验证冲突
                if (ExecutableFreeSelectionCouse.IsNeedVerify != false)
                {
                    //判断教师和教室冲突,如果有冲突type返回1,页面js根据type弹出选择框,用户可选择继续保存或不保存,如果不返回1,弹出一般的错误提示框
                    foreach (var scheduling in schedulingList)
                    {
                        //教室不为空时,判断教室
                        if (ExecutableFreeSelectionCouse.ClassroomID != null)
                        {
                            //任选设定冲突
                            var repeatExecutableClassroom = ExecutableFreeSelectionCouseDAL.GetRepeatExecutableFreeSelectionCouseClassroom(scheduling.CoursesTimeID, ExecutableFreeSelectionCouse.ClassroomID, scheduling.Weekday, ExecutableFreeSelectionCouse.SchoolyearID, ExecutableFreeSelectionCouse.StartWeeklyNum, ExecutableFreeSelectionCouse.EndWeeklyNum)
                                .Where(x => x.ID != ExecutableFreeSelectionCouse.ExecutableFreeSelectionCouseID).FirstOrDefault();
                            if (repeatExecutableClassroom != null)
                            {
                                type = 1;
                                throw new Exception(repeatExecutableClassroom.WeekdayName + repeatExecutableClassroom.StartTimes + "时间段教室与任选设定【" + repeatExecutableClassroom.DefaultClassName + "】有冲突");
                            }
                            //任选申请冲突
                            var repeatApplyClassroom = ExecutableFreeSelectionCouseDAL.GetRepeatFreeSelectionCouseApplyClassroom(scheduling.CoursesTimeID, ExecutableFreeSelectionCouse.ClassroomID, scheduling.Weekday, ExecutableFreeSelectionCouse.SchoolyearID, ExecutableFreeSelectionCouse.StartWeeklyNum, ExecutableFreeSelectionCouse.EndWeeklyNum, ApprovalStatus).FirstOrDefault();
                            if (repeatApplyClassroom != null)
                            {
                                type = 1;
                                throw new Exception("检测到排课冲突," + repeatApplyClassroom.WeekdayName + repeatApplyClassroom.StartTimes + "时间段教室与开课申请【" + repeatApplyClassroom.DefaultClassName + "】有冲突");
                            }
                            //教学任务冲突
                            var repeatEducationClassroom = ExecutableFreeSelectionCouseDAL.GetRepeatEducationMissionClassroom(scheduling.CoursesTimeID, ExecutableFreeSelectionCouse.ClassroomID, scheduling.Weekday, ExecutableFreeSelectionCouse.SchoolyearID, ExecutableFreeSelectionCouse.StartWeeklyNum, ExecutableFreeSelectionCouse.EndWeeklyNum).FirstOrDefault();
                            if (repeatEducationClassroom != null)
                            {
                                type = 1;
                                throw new Exception("检测到排课冲突," + "该设定上课时间段教室与教学任务班【" + repeatEducationClassroom.DefaultClassName + "】有冲突");
                            }
                        }

                        //任选设定冲突
                        var repeatExecutableTeacher = ExecutableFreeSelectionCouseDAL.GetRepeatExecutableFreeSelectionCouseTeacher(teacherList.Select(x => x.UserID).ToList(), scheduling.CoursesTimeID, scheduling.Weekday, ExecutableFreeSelectionCouse.SchoolyearID, ExecutableFreeSelectionCouse.StartWeeklyNum, ExecutableFreeSelectionCouse.EndWeeklyNum)
                            .Where(x => x.ID != ExecutableFreeSelectionCouse.ExecutableFreeSelectionCouseID).FirstOrDefault();
                        if (repeatExecutableTeacher != null)
                        {
                            type = 1;
                            throw new Exception("检测到排课冲突," + repeatExecutableTeacher.WeekdayName + repeatExecutableTeacher.StartTimes + "时间段教师与任选设定【" + repeatExecutableTeacher.DefaultClassName + "】有冲突");
                        }
                        //任选申请冲突
                        var repeatApplyTeacher = ExecutableFreeSelectionCouseDAL.GetRepeatFreeSelectionCouseApplyTeacher(teacherList.Select(x => x.UserID).ToList(), scheduling.CoursesTimeID, scheduling.Weekday, ExecutableFreeSelectionCouse.SchoolyearID, ExecutableFreeSelectionCouse.StartWeeklyNum, ExecutableFreeSelectionCouse.EndWeeklyNum, ApprovalStatus).FirstOrDefault();
                        if (repeatApplyTeacher != null)
                        {
                            type = 1;
                            throw new Exception("检测到排课冲突," + repeatApplyTeacher.WeekdayName + repeatApplyTeacher.StartTimes + "时间段教师与开课申请【" + repeatApplyTeacher.DefaultClassName + "】有冲突");
                        }
                        //教学任务冲突
                        var repeatEducationTeacher = ExecutableFreeSelectionCouseDAL.GetRepeatEducationMissionTeacher(teacherList.Select(x => x.UserID).ToList(), scheduling.CoursesTimeID, scheduling.Weekday, ExecutableFreeSelectionCouse.SchoolyearID, ExecutableFreeSelectionCouse.StartWeeklyNum, ExecutableFreeSelectionCouse.EndWeeklyNum).FirstOrDefault();
                        if (repeatEducationTeacher != null)
                        {
                            type = 1;
                            throw new Exception("检测到排课冲突," + "该设定上课时间段教师与教学任务班【" + repeatEducationTeacher.DefaultClassName + "】有冲突");
                        }
                    }
                }
                using (TransactionScope ts = new TransactionScope())
                {
                    EM_ExecutableFreeSelectionCouse ExecutableFreeSelectionCouseEntity = GetExecutableFreeSelectionCouse(ExecutableFreeSelectionCouse.ExecutableFreeSelectionCouseID);

                    ExecutableFreeSelectionCouseEntity.FreeSelectionCouseID = ExecutableFreeSelectionCouse.FreeSelectionCouseID;
                    ExecutableFreeSelectionCouseEntity.SchoolyearID = ExecutableFreeSelectionCouse.SchoolyearID;
                    ExecutableFreeSelectionCouseEntity.DefaultClassName = ExecutableFreeSelectionCouse.DefaultClassName;
                    //ExecutableFreeSelectionCouseEntity.DefaultClassName = freeSelectionCourse.DepartmentName + "-"
                    //                                                + freeSelectionCourse.CourseName + "班(任选)";
                    ExecutableFreeSelectionCouseEntity.DepartmentID = ExecutableFreeSelectionCouse.DepartmentID;
                    ExecutableFreeSelectionCouseEntity.CourseStructureID = ExecutableFreeSelectionCouse.CourseStructureID;
                    ExecutableFreeSelectionCouseEntity.CourseCategoryID = ExecutableFreeSelectionCouse.CourseCategoryID;
                    ExecutableFreeSelectionCouseEntity.CourseTypeID = ExecutableFreeSelectionCouse.CourseTypeID;
                    ExecutableFreeSelectionCouseEntity.CourseQualityID = ExecutableFreeSelectionCouse.CourseQualityID;
                    ExecutableFreeSelectionCouseEntity.PracticeTypeID = ExecutableFreeSelectionCouse.PracticeTypeID;
                    ExecutableFreeSelectionCouseEntity.ExaminationModeID = ExecutableFreeSelectionCouse.ExaminationModeID;
                    ExecutableFreeSelectionCouseEntity.TeachinglanguageID = ExecutableFreeSelectionCouse.TeachinglanguageID;
                    ExecutableFreeSelectionCouseEntity.IsNeedMaterial = ExecutableFreeSelectionCouse.IsNeedMaterial;
                    ExecutableFreeSelectionCouseEntity.PeopleNumlower = ExecutableFreeSelectionCouse.PeopleNumlower;
                    ExecutableFreeSelectionCouseEntity.PeopleNumlimit = ExecutableFreeSelectionCouse.PeopleNumlimit;
                    ExecutableFreeSelectionCouseEntity.HandleModeID = ExecutableFreeSelectionCouse.HandleModeID;
                    ExecutableFreeSelectionCouseEntity.IsOpened = ExecutableFreeSelectionCouse.IsOpened;
                    ExecutableFreeSelectionCouseEntity.ResultTypeID = ExecutableFreeSelectionCouse.ResultTypeID;
                    //ExecutableFreeSelectionCouseEntity.ApprovalStatus = ExecutableFreeSelectionCouse.ApprovalStatus;//(int)EMIS.ViewModel.CF_PlanApplicationStatus.NotSubmitted;
                    ExecutableFreeSelectionCouseEntity.Remarks = ExecutableFreeSelectionCouse.Remarks;

                    //任选设定教学设置表
                    EM_ExecutableFreeSelectionCouseTeachingSetting freeSelectionCourseTeachingSetting = ExecutableFreeSelectionCouseDAL.ExecutableFreeSelectionCouseTeachingSettingRepository.Entities.Where(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouse.ExecutableFreeSelectionCouseID).FirstOrDefault();
                    //freeSelectionCourseTeachingSetting = new EM_ExecutableFreeSelectionCouseTeachingSetting();
                    freeSelectionCourseTeachingSetting.ExecutableFreeSelectionCouseID = ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID;
                    freeSelectionCourseTeachingSetting.Credit = ExecutableFreeSelectionCouse.Credit;
                    freeSelectionCourseTeachingSetting.TheoryCourse = ExecutableFreeSelectionCouse.TheoryCourse;
                    freeSelectionCourseTeachingSetting.Practicehours = ExecutableFreeSelectionCouse.Practicehours;
                    freeSelectionCourseTeachingSetting.Trialhours = ExecutableFreeSelectionCouse.Trialhours;
                    freeSelectionCourseTeachingSetting.WeeklyNum = ExecutableFreeSelectionCouse.WeeklyNum;
                    freeSelectionCourseTeachingSetting.TheoryWeeklyNum = ExecutableFreeSelectionCouse.TheoryWeeklyNum;
                    freeSelectionCourseTeachingSetting.PracticeWeeklyNum = ExecutableFreeSelectionCouse.PracticeWeeklyNum;
                    freeSelectionCourseTeachingSetting.TrialWeeklyNum = ExecutableFreeSelectionCouse.TrialWeeklyNum;
                    freeSelectionCourseTeachingSetting.StartWeeklyNum = ExecutableFreeSelectionCouse.StartWeeklyNum;
                    freeSelectionCourseTeachingSetting.EndWeeklyNum = ExecutableFreeSelectionCouse.EndWeeklyNum;
                    freeSelectionCourseTeachingSetting.WeeklyHours = ExecutableFreeSelectionCouse.WeeklyHours;
                    //SetNewStatus(freeSelectionCourseTeachingSetting);

                    //任选设定课程表
                    this.UnitOfWork.Delete<EM_ExecutableFreeSelectionCouseScheduling>(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID);
                    distinctSchedulingList.ToList().ForEach(x =>
                    {
                        var scheduling = new EM_ExecutableFreeSelectionCouseScheduling
                        {
                            ExecutableFreeSelectionCouseSchedulingID = Guid.NewGuid(),
                            ExecutableFreeSelectionCouseID = ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID,
                            ClassroomID = ExecutableFreeSelectionCouse.ClassroomID,  //这一行没有教室时,填查询到的其它行的教室,如果都没有就为空
                            CoursesTimeID = x.CoursesTimeID,
                            Weekday = x.Weekday,
                        };
                        this.SetNewStatus(scheduling);
                        this.UnitOfWork.Add(scheduling);
                    });


                    //任选设定授课方式表
                    if (ExecutableFreeSelectionCouse.TeachingModeID != null)
                    {
                        TeachingModeTypeAdd(ExecutableFreeSelectionCouse.TeachingModeID, ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID);
                    }
                    this.SetModifyStatus(ExecutableFreeSelectionCouseEntity);

                    //
                    UnitOfWork.Delete<EM_ExecutableFreeSelectionCouseGradeYear>(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID);
                    if (ExecutableFreeSelectionCouse.GradeYear != null)
                    {
                        foreach (var i in ExecutableFreeSelectionCouse.GradeYear)
                        {
                            EM_ExecutableFreeSelectionCouseGradeYear gradeYear = new EM_ExecutableFreeSelectionCouseGradeYear();
                            gradeYear.ExecutableFreeSelectionCouseGradeYearID = Guid.NewGuid();
                            gradeYear.ExecutableFreeSelectionCouseID = ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID;
                            gradeYear.GradeYear = i;
                            this.SetNewStatus(gradeYear);
                            UnitOfWork.Add(gradeYear);
                        }
                    }

                    //
                    if (specialtyList.Count > 0)
                    {
                        UnitOfWork.Delete<EM_ExecutableFreeSelectionCouseSpecialty>(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID);
                        foreach (var i in specialtyList)
                        {
                            EM_ExecutableFreeSelectionCouseSpecialty specialty = new EM_ExecutableFreeSelectionCouseSpecialty();
                            specialty.ExecutableFreeSelectionCouseSpecialtyID = Guid.NewGuid();
                            specialty.ExecutableFreeSelectionCouseID = ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID;
                            specialty.SpecialtyID = i.SpecialtyID;
                            this.SetNewStatus(specialty);
                            UnitOfWork.Add(specialty);
                        }
                    }

                    this.UnitOfWork.Delete<EM_ExecutableFreeSelectionCouseTeacher>(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID);
                    teacherList.ToList().ForEach(x =>
                    {
                        var freeSelectionTeacher = new EM_ExecutableFreeSelectionCouseTeacher
                        {
                            ExecutableFreeSelectionCouseStaffID = Guid.NewGuid(),
                            ExecutableFreeSelectionCouseID = ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID,
                            UserID = x.UserID,
                            TeachingMethod = x.TeachingMethod
                        };
                        this.SetNewStatus(freeSelectionTeacher);
                        this.UnitOfWork.Add(freeSelectionTeacher);
                    });
                    SetModifyStatus(ExecutableFreeSelectionCouseEntity);
                    UnitOfWork.Commit();
                    ts.Complete();
                }
                type = 0;
                return true;
            }
            catch (Exception)
            {

                throw;
            }
        }

        public bool ExecutableFreeSelectionCouseUpdate(ExecutableFreeSelectionCouseView ExecutableFreeSelectionCouse, IList<ExecutableFreeSelectionCouseTeacherListView> teacherList)
        {
            try
            {

                EM_ExecutableFreeSelectionCouse ExecutableFreeSelectionCouseEntity = GetExecutableFreeSelectionCouse(ExecutableFreeSelectionCouse.ExecutableFreeSelectionCouseID);
                this.UnitOfWork.Delete<EM_ExecutableFreeSelectionCouseTeacher>(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID);
                teacherList.ToList().ForEach(x =>
                {
                    var freeSelectionTeacher = new EM_ExecutableFreeSelectionCouseTeacher
                    {
                        ExecutableFreeSelectionCouseStaffID = Guid.NewGuid(),
                        ExecutableFreeSelectionCouseID = ExecutableFreeSelectionCouseEntity.ExecutableFreeSelectionCouseID,
                        UserID = x.UserID,
                        TeachingMethod = x.TeachingMethod
                    };
                    this.SetNewStatus(freeSelectionTeacher);
                    this.UnitOfWork.Add(freeSelectionTeacher);
                });
                SetModifyStatus(ExecutableFreeSelectionCouseEntity);
                UnitOfWork.Commit();
                return true;
            }
            catch (Exception)
            {

                throw;
            }
        }


        //开放
        public bool ExecutableFreeSelectionCouseOpen(List<Guid?> ExecutableFreeSelectionCouseIDs)
        {
            try
            {
                if (ExecutableFreeSelectionCouseIDs.Count > 0)
                {
                    var ExecutableFreeSelectionCouseList = ExecutableFreeSelectionCouseRepository.GetList(x => ExecutableFreeSelectionCouseIDs.Contains(x.ExecutableFreeSelectionCouseID)).ToList();
                    foreach (var ExecutableFreeSelectionCouse in ExecutableFreeSelectionCouseList)
                    {
                        if (ExecutableFreeSelectionCouse.RecordStatus > (int)EMIS.ViewModel.EM_SelectCourseResultStatus.NotOpen)   //开放状态
                        {
                            throw new Exception("任选设定已开放");
                        }
                    }
                    UnitOfWork.Update<EM_ExecutableFreeSelectionCouse>(x => new EM_ExecutableFreeSelectionCouse { RecordStatus = (int)EMIS.ViewModel.EM_SelectCourseResultStatus.Opened }, x => ExecutableFreeSelectionCouseIDs.Contains(x.ExecutableFreeSelectionCouseID));
                    this.UnitOfWork.Commit();
                    return true;
                }
                return false;
            }
            catch (Exception)
            {

                throw;
            }
        }

        //取消开放
        public bool ExecutableFreeSelectionCouseCancel(List<Guid?> ExecutableFreeSelectionCouseIDs)
        {
            try
            {
                if (ExecutableFreeSelectionCouseIDs.Count > 0)
                {
                    var ExecutableFreeSelectionCouseList = ExecutableFreeSelectionCouseRepository.GetList(x => ExecutableFreeSelectionCouseIDs.Contains(x.ExecutableFreeSelectionCouseID)).ToList();
                    foreach (var ExecutableFreeSelectionCouse in ExecutableFreeSelectionCouseList)
                    {
                        if (ExecutableFreeSelectionCouse.RecordStatus < (int)EMIS.ViewModel.EM_SelectCourseResultStatus.Opened)   //开放状态
                        {
                            throw new Exception("任选设定未开放");
                        }
                    }
                    UnitOfWork.Update<EM_ExecutableFreeSelectionCouse>(x => new EM_ExecutableFreeSelectionCouse { RecordStatus = (int)EMIS.ViewModel.EM_SelectCourseResultStatus.NotOpen }, x => ExecutableFreeSelectionCouseIDs.Contains(x.ExecutableFreeSelectionCouseID));
                    this.UnitOfWork.Commit();
                    return true;
                }
                return false;
            }
            catch (Exception)
            {

                throw;
            }
        }

        public bool ExecutableFreeSelectionCouseDelete(List<Guid?> ExecutableFreeSelectionCouseIDs)
        {
            try
            {
                if (ExecutableFreeSelectionCouseIDs.Count > 0)
                {
                    var status = this.GetCorrectEndStatus();
                    var ExecutableFreeSelectionCouseList = ExecutableFreeSelectionCouseRepository.GetList(x => ExecutableFreeSelectionCouseIDs.Contains(x.ExecutableFreeSelectionCouseID), x => x.EM_ExecutableFreeSelectionCouseSpecialty).ToList();
                    //任选设定可能来自开课申请,因此要删除相关的开课申请,先在循环外查出对应学年学期已通过的开课申请
                    var SchoolYearIDList = ExecutableFreeSelectionCouseList.Select(x => x.SchoolyearID).ToList();
                    var FreeSelectionCouseApplyList = FreeSelectionCoursePlanDAL.FreeSelectionCouseApplyRepository.GetList(
                           (x => SchoolYearIDList.Contains(x.SchoolyearID) && x.ApprovalStatus == status)
                            , x => x.EM_FreeSelectionCouseApplySpecialty).ToList();
                    foreach (var ExecutableFreeSelectionCouse in ExecutableFreeSelectionCouseList)
                    {
                        if (ExecutableFreeSelectionCouse.RecordStatus != (int)EMIS.ViewModel.EM_SelectCourseResultStatus.NotOpen)
                            throw new Exception("只能删除未开放状态的信息。");

                        var SpecialtyIDList = ExecutableFreeSelectionCouse.EM_ExecutableFreeSelectionCouseSpecialty.Select(x => x.SpecialtyID).ToList();
                        var freeSelectionCouseApply = FreeSelectionCouseApplyList.Where(
                            x => x.FreeSelectionCouseID == ExecutableFreeSelectionCouse.FreeSelectionCouseID
                            && x.SchoolyearID == ExecutableFreeSelectionCouse.SchoolyearID
                                //&& x.DefaultClassName == ExecutableFreeSelectionCouse.DefaultClassName
                            && x.DepartmentID == ExecutableFreeSelectionCouse.DepartmentID
                            && x.CourseTypeID == ExecutableFreeSelectionCouse.CourseTypeID
                            && x.ApprovalStatus == status
                            && (SpecialtyIDList.Count == 0 || (SpecialtyIDList.Count > 0 && x.EM_FreeSelectionCouseApplySpecialty.Any(w => SpecialtyIDList.Contains(w.SpecialtyID))))
                            ).FirstOrDefault();
                        if (freeSelectionCouseApply != null)
                        {   //删除开课申请
                            UnitOfWork.Remove<Sys_ProcessRelation>(x => x.formID == freeSelectionCouseApply.FreeSelectionCouseApplyID);
                            UnitOfWork.Remove<EM_FreeSelectionCouseApplyTeachingSetting>(x => x.FreeSelectionCouseApplyID == freeSelectionCouseApply.FreeSelectionCouseApplyID);
                            UnitOfWork.Remove<EM_FreeSelectionCouseApplyTeachingMode>(x => x.FreeSelectionCouseApplyID == freeSelectionCouseApply.FreeSelectionCouseApplyID);
                            UnitOfWork.Remove<EM_FreeSelectionCouseApplyTeacher>(x => x.FreeSelectionCouseApplyID == freeSelectionCouseApply.FreeSelectionCouseApplyID);
                            UnitOfWork.Remove<EM_FreeSelectionCouseApplyGradeYear>(x => x.FreeSelectionCouseApplyID == freeSelectionCouseApply.FreeSelectionCouseApplyID);
                            UnitOfWork.Remove<EM_FreeSelectionCouseApplySpecialty>(x => x.FreeSelectionCouseApplyID == freeSelectionCouseApply.FreeSelectionCouseApplyID);
                            UnitOfWork.Remove<EM_FreeSelectionCouseApplyScheduling>(x => x.FreeSelectionCouseApplyID == freeSelectionCouseApply.FreeSelectionCouseApplyID);
                            UnitOfWork.Remove<EM_FreeSelectionCouseApply>(x => x.FreeSelectionCouseApplyID == freeSelectionCouseApply.FreeSelectionCouseApplyID);
                        }
                        UnitOfWork.Remove<EM_ExecutableFreeSelectionCouseScheduling>(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouse.ExecutableFreeSelectionCouseID);
                        UnitOfWork.Remove<EM_ExecutableFreeSelectionCouseTeachingSetting>(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouse.ExecutableFreeSelectionCouseID);
                        UnitOfWork.Remove<EM_ExecutableFreeSelectionCouseTeachingMode>(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouse.ExecutableFreeSelectionCouseID);
                        UnitOfWork.Remove<EM_ExecutableFreeSelectionCouseTeacher>(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouse.ExecutableFreeSelectionCouseID);
                        UnitOfWork.Remove<EM_ExecutableFreeSelectionCouseGradeYear>(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouse.ExecutableFreeSelectionCouseID);
                        UnitOfWork.Remove<EM_ExecutableFreeSelectionCouseSpecialty>(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouse.ExecutableFreeSelectionCouseID);
                        //UnitOfWork.Remove<EM_ExecutableFreeSelectionCouseStudent>(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouse.ExecutableFreeSelectionCouseID);
                        ExecutableFreeSelectionCouse.CF_Student = new HashSet<CF_Student>();
                        UnitOfWork.Delete(ExecutableFreeSelectionCouse, (x => x.CF_Student));
                        UnitOfWork.Remove(ExecutableFreeSelectionCouse);

                    }
                    this.UnitOfWork.Commit();
                    return true;
                }
                return false;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 开放
        /// </summary>
        /// <param name="ExecutableFreeSelectionCouseIDs"></param>
        /// <returns></returns>
        public bool ExecutableFreeSelectionCouseSubmit(List<Guid> ExecutableFreeSelectionCouseIDs)
        {
            try
            {
                var ExecutableFreeSelectionCouseList = ExecutableFreeSelectionCouseDAL.ExecutableFreeSelectionCouseRepository.GetList(x => ExecutableFreeSelectionCouseIDs.Contains(x.ExecutableFreeSelectionCouseID));
                foreach (var ExecutableFreeSelectionCouse in ExecutableFreeSelectionCouseList)
                {
                    if (ExecutableFreeSelectionCouse.RecordStatus != (int)EMIS.ViewModel.EM_SelectCourseResultStatus.NotOpen && ExecutableFreeSelectionCouse.RecordStatus != (int)EMIS.ViewModel.EM_SelectCourseResultStatus.CancleCreate)
                        throw new Exception("不能开放当前状态的数据,请核查");
                    ExecutableFreeSelectionCouse.RecordStatus = (int)EMIS.ViewModel.EM_SelectCourseResultStatus.Opened;
                }
                UnitOfWork.Commit();
                return true;
            }
            catch (Exception)
            {

                throw;
            }
        }

        public List<ExecutableFreeSelectionCouseTeacherListView> GetExecutableFreeSelectionCouseTeacherListView(Guid ExecutableFreeSelectionCouseID)
        {
            var teacherView = ExecutableFreeSelectionCouseDAL.GetExecutableFreeSelectionCouseTeacherViewQueryable(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouseID);

            return teacherView.ToList();
        }

        //查询专业范围
        public List<SpecialtyView> GetExecutableFreeSelectionCouseSpecialtyListView(Guid ExecutableFreeSelectionCouseID)
        {
            var specialtyView = ExecutableFreeSelectionCouseDAL.GetExecutableFreeSelectionCouseSpecialtyViewQueryable(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouseID);

            return specialtyView.ToList();
        }

        public List<ExecutableFreeSelectionCouseSchedulingView> GetSchedulingView(Guid ExecutableFreeSelectionCouseID)
        {
            //2016年12月1日15:28:47
            //TODO :调整教学任务课程进度统计规则[将原按教学任务获取该教学任务下所对应的教学任务班课程进度信息调整为按对应教学任务班进行统计]
            //var courseViewList = this.educationMissionClassDAL.GetCourseProcessView(x => x.EducationMissionID == educationMissionID)
            //    .OrderBy(x => x.Week).ToList();

            var courseViewList = this.ExecutableFreeSelectionCouseDAL.GetSchedulingView(x => x.ExecutableFreeSelectionCouseID == ExecutableFreeSelectionCouseID)
                .OrderBy(x => x.Weekday).ToList();



            return courseViewList;
        }

        public IGridResultSet<ClassroomView> GetAvailableClassroom(ConfiguretView configuretView, Guid? buildingID,
             string schedulingWeek,
            int? weekday, Guid courseTimeID, int? classroomTypeID, int? pageIndex, int? pageSize)
        {
            List<int?> schedulingWeekList = Array.ConvertAll<string, int?>(schedulingWeek.Split('-'), s => Convert.ToInt32(s)).ToList();

            for (int i = 1; i + schedulingWeekList.Min() < schedulingWeekList.Max(); i++)
            {
                schedulingWeekList.Add(i + schedulingWeekList.Min());
            }
            Expression<Func<CF_Classroom, bool>> exp = (x => true);
            if (buildingID.HasValue)
            {
                exp = exp.And(x => x.BuildingsInfoID == buildingID);
            }
            var currentSchoolyearID = SelectCourseResultDAL.GetSelectCourseSchoolyear();
            var classroomView = ClassroomScheduleDAL.GetAvailableClassroom(currentSchoolyearID,
                schedulingWeekList, weekday.Value, courseTimeID, classroomTypeID > 0 ? classroomTypeID : null);
            if (!string.IsNullOrEmpty(configuretView.ConditionValue))
                classroomView = classroomView.DynamicWhere(configuretView.Attribute, configuretView.Condition, configuretView.ConditionValue);
            return classroomView.OrderBy(x => x.BuildingsInfoName)
                .ThenBy(x => x.Name)
                .ThenBy(x => x.Totalseating).ToGridResultSet(pageIndex, pageSize);
        }

        /// <summary>
        /// 根据起止周次定义班号顺序
        /// </summary>
        /// <param name="SchoolyearID"></param>
        /// <param name="freeSelectionCourseID"></param>
        /// <param name="StartWeeklyNum"></param>
        /// <param name="EndWeeklyNum"></param>
        /// <returns></returns>
        public string DefaultClassNo(Guid SchoolyearID, Guid freeSelectionCourseID, string StartWeeklyNum, string EndWeeklyNum)
        {
            if (StartWeeklyNum != "" && EndWeeklyNum != "")
            {
                //var freeSelectionCouseApply = ExecutableFreeSelectionCouseRepository.FreeSelectionCouseApplyRepository.GetList(x => x.SchoolyearID == SchoolyearID && x.FreeSelectionCouseID == freeSelectionCourseID, x => x.EM_ExecutableFreeSelectionCouseTeachingSetting).ToList();
                var FreeSelectionCouseApplyTeachingSetting = ExecutableFreeSelectionCouseDAL.ExecutableFreeSelectionCouseTeachingSettingRepository.GetList(x => x.EM_ExecutableFreeSelectionCouse.SchoolyearID == SchoolyearID && x.EM_ExecutableFreeSelectionCouse.FreeSelectionCouseID == freeSelectionCourseID);
                var list = FreeSelectionCouseApplyTeachingSetting.Select(x => new { WeeklyNum = x.StartWeeklyNum.Value + x.EndWeeklyNum.Value }).ToList();
                List<int> l = new List<int> { Convert.ToInt32(StartWeeklyNum) + Convert.ToInt32(EndWeeklyNum) };
                list.ForEach(x => l.Add(x.WeeklyNum));
                l.Sort();
                int index = l.IndexOf(Convert.ToInt32(StartWeeklyNum) + Convert.ToInt32(EndWeeklyNum)) + 1;
                return index.ToString();
            }
            return "";
        }

        public void SaveTeachers(Guid executableFreeSelectionCouseID, IList<ExecutableFreeSelectionCouseTeacherListView> teacherList)
        {
            var freeSelectionCourseApply = ExecutableFreeSelectionCouseDAL.ExecutableFreeSelectionCouseRepository
                .GetSingle(x => x.ExecutableFreeSelectionCouseID == executableFreeSelectionCouseID, (x => x.EM_ExecutableFreeSelectionCouseTeacher));

            freeSelectionCourseApply.EM_ExecutableFreeSelectionCouseTeacher.ToList().ForEach(x => this.UnitOfWork.Remove(x));
            //teacherList.ToList().ForEach(x =>
            //{
            //    var freeSelectionCourseApplyStaffEntity = new EM_FreeSelectionCouseApplyStaff
            //    {
            //        FreeSelectionCouseApplyStaffID = Guid.NewGuid(),
            //        FreeSelectionCouseApplyID = freeSelectionCourseApplyID,
            //        UserID = x.UserID,
            //        TeachingMethod = x.TeachingMethod
            //    };
            //    this.SetNewStatus(freeSelectionCourseApplyStaffEntity);

            //    this.UnitOfWork.Add(freeSelectionCourseApplyStaffEntity);
            //});

            this.UnitOfWork.Commit();
        }


    }
}