using Edu.AOP.CustomerAttribute;
using Edu.Common.Encrypt;
using Edu.Common.Enum;
using Edu.Common.Enum.User;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.User;
using Edu.Module.Log;
using Edu.Repository.Course;
using Edu.Repository.User;
using System;
using System.Collections.Generic;
using System.Linq;
using VT.FW.DB;

namespace Edu.Module.User
{
    /// <summary>
    /// 教师处理类
    /// </summary>
    public class TeacherModule
    {
        /// <summary>
        /// 讲师仓储层对象
        /// </summary>
        private readonly RB_TeacherRepository teacherRepository = new RB_TeacherRepository();

        /// <summary>
        /// 账号处理类
        /// </summary>
        private readonly AccountModule accountModule = new AccountModule();

        /// <summary>
        /// 岗位管理仓储层对象
        /// </summary>
        private readonly RB_PostRepository postRepository = new RB_PostRepository();

        /// <summary>
        /// 部门管理仓储层对象
        /// </summary>
        private readonly RB_DepartmentRepository departmentRepository = new RB_DepartmentRepository();

        /// <summary>
        /// 用户信息日志处理类对象
        /// </summary>
        private readonly UserChangeLogModule userChangeLogModule = new UserChangeLogModule();

        /// <summary>
        /// 班级仓储层对象
        /// </summary>
        private readonly RB_ClassRepository classRepository = new RB_ClassRepository();

        /// <summary>
        /// 校区管理
        /// </summary>
        private readonly RB_SchoolRepository schoolRepository = new RB_SchoolRepository();

        /// <summary>
        /// 账号仓储层对象
        /// </summary>
        private readonly RB_AccountRepository accountRepository = new RB_AccountRepository();

        /// <summary>
        /// 获取讲师列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Teacher_ViewModel> GetTeacherListModule(RB_Teacher_ViewModel query)
        {
            return teacherRepository.GetTeacherListRepository(query);
        }


        /// <summary>
        /// 获取讲师分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Teacher_ViewModel> GetTeacherPageListModule(int pageIndex, int pageSize, out long rowsCount, RB_Teacher_ViewModel query)
        {
            var list = teacherRepository.GetTeacherPageListRepository(pageIndex, pageSize, out rowsCount, query);
            if (list != null && list.Count > 0)
            {
                string postIds = string.Join(",", list.Where(qitem => qitem.Post_Id > 0).Select(qitem => qitem.Post_Id));
                string deptIds = string.Join(",", list.Where(qitem => qitem.Dept_Id > 0).Select(qitem => qitem.Dept_Id));
                string ids = string.Join(",", list.Where(qitem => qitem.TId > 0).Select(qitem => qitem.TId));
                List<RB_Post_ViewModel> postList = new List<RB_Post_ViewModel>();
                List<RB_Department_ViewModel> deptList = new List<RB_Department_ViewModel>();
                List<TeacherClassStatic_ViewModel> teacherClassList = new List<TeacherClassStatic_ViewModel>();
                if (!string.IsNullOrEmpty(postIds))
                {
                    postList = postRepository.GetPostListRepository(new RB_Post_ViewModel() { QPostIds = postIds });
                }
                if (!string.IsNullOrEmpty(deptIds))
                {
                    deptList = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { QDeptIds = deptIds });
                }
                if (!string.IsNullOrEmpty(ids))
                {
                    teacherClassList = classRepository.GetTeacherClassCountRepository(ids);
                }
                foreach (var item in list)
                {
                    item.DeptName = deptList?.Where(qitem => qitem.DeptId == item.Dept_Id)?.FirstOrDefault()?.DeptName ?? "";
                    item.PostName = postList?.Where(qitem => qitem.PostId == item.Post_Id)?.FirstOrDefault()?.PostName ?? "";
                    item.CourseCount = teacherClassList?.Where(qitem => qitem.Teacher_Id == item.TId)?.FirstOrDefault()?.ClassCount ?? 0;
                }
            }
            return list;
        }

        /// <summary>
        /// 新增修改讲师
        /// </summary>
        /// <param name="model"></param>
        /// <param name="isUpdateBasic">是否更新基础资料</param>
        /// <returns></returns>
        public bool SetTeacherModule(RB_Teacher_ViewModel model, bool isUpdateBasic = false)
        {
            bool flag;
            if (model.TId > 0)
            {
                var oldModel = GetTeacherModule(model.TId);
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Teacher_ViewModel.TeacherName),model.TeacherName },
                    {nameof(RB_Teacher_ViewModel.TeacherTel),model.TeacherTel },
                    {nameof(RB_Teacher_ViewModel.TeacherHead),model.TeacherHead },
                    {nameof(RB_Teacher_ViewModel.TeacherIcon),model.TeacherIcon },
                    {nameof(RB_Teacher_ViewModel.UpdateBy),model.UpdateBy },
                    {nameof(RB_Teacher_ViewModel.UpdateTime),model.UpdateTime },
                    {nameof(RB_Teacher_ViewModel.School_Id),model.School_Id },
                };
                if (isUpdateBasic)
                {
                    fileds.Add(nameof(RB_Teacher_ViewModel.TeachTag), model.TeachTag);
                    fileds.Add(nameof(RB_Teacher_ViewModel.SortNum), model.SortNum);
                    fileds.Add(nameof(RB_Teacher_ViewModel.IsRecommend), model.IsRecommend);
                    fileds.Add(nameof(RB_Teacher_ViewModel.IsShow), model.IsShow);
                    fileds.Add(nameof(RB_Teacher_ViewModel.TeacherIntro), model.TeacherIntro);
                    fileds.Add(nameof(RB_Teacher_ViewModel.TeacherSay), model.TeacherSay);
                    fileds.Add(nameof(RB_Teacher_ViewModel.Dept_Id), model.Dept_Id);
                    fileds.Add(nameof(RB_Teacher_ViewModel.Post_Id), model.Post_Id);
                    fileds.Add(nameof(RB_Teacher_ViewModel.BaseStuNum), model.BaseStuNum);
                    fileds.Add(nameof(RB_Teacher_ViewModel.BaseHourFee), model.BaseHourFee);
                }
                else
                {
                    if (model.LeaveStatus != LeaveStatusEnum.Departure)
                    {
                        model.LeaveTime = null;
                    }
                    fileds.Add(nameof(RB_Teacher_ViewModel.IDCard), model.IDCard);
                    fileds.Add(nameof(RB_Teacher_ViewModel.Sex), model.Sex);
                    fileds.Add(nameof(RB_Teacher_ViewModel.EntryTime), model.EntryTime);
                    fileds.Add(nameof(RB_Teacher_ViewModel.Address), model.Address);
                    fileds.Add(nameof(RB_Teacher_ViewModel.BirthDate), model.BirthDate);
                    fileds.Add(nameof(RB_Teacher_ViewModel.LeaveStatus), model.LeaveStatus);
                    fileds.Add(nameof(RB_Teacher_ViewModel.LeaveTime), model.LeaveTime);
                    fileds.Add(nameof(RB_Teacher_ViewModel.Education), model.Education);
                    fileds.Add(nameof(RB_Teacher_ViewModel.Email), model.Email);
                }
                #region 修改日志
                string logContent = "";
                if (model.TeacherName != oldModel.TeacherName)
                {
                    logContent += string.Format(",将姓名由【{0}】修改为【{1}】。", oldModel.TeacherName, model.TeacherName);
                }
                if (model.TeacherTel != oldModel.TeacherTel)
                {
                    logContent += string.Format(",将电话由【{0}】修改为【{1}】。", oldModel.TeacherTel, model.TeacherTel);
                }
                if (model.BaseStuNum != oldModel.BaseStuNum)
                {
                    logContent += string.Format(",将带班基础人数由【{0}】修改为【{1}】。", oldModel.BaseStuNum, model.BaseStuNum);
                }
                if (model.IDCard != oldModel.IDCard)
                {
                    logContent += string.Format(",将身份证由【{0}】修改为【{1}】。", oldModel.IDCard, model.IDCard);
                }
                if (model.Sex != oldModel.Sex)
                {
                    logContent += string.Format(",将性别由【{0}】修改为【{1}】。", oldModel.Sex, model.Sex);
                }
                if (Common.ConvertHelper.FormatDate(model.EntryTime) != Common.ConvertHelper.FormatDate(oldModel.EntryTime))
                {
                    logContent += string.Format(",将入职时间由【{0}】修改为【{1}】。", oldModel.EntryTime, model.EntryTime);
                }
                if (model.Address != oldModel.Address)
                {
                    logContent += string.Format(",将地址由【{0}】修改为【{1}】。", oldModel.Address, model.Address);
                }
                if (Common.ConvertHelper.FormatDate(model.BirthDate) != Common.ConvertHelper.FormatDate(oldModel.BirthDate))
                {
                    logContent += string.Format(",将生日由【{0}】修改为【{1}】。", Common.ConvertHelper.FormatDate(oldModel.BirthDate), Common.ConvertHelper.FormatDate(model.BirthDate));
                }
                if (model.LeaveStatus != oldModel.LeaveStatus)
                {
                    logContent += string.Format(",将在职状态由【{0}】修改为【{1}】。", oldModel.LeaveStatus.ToName(), model.LeaveStatus.ToName());
                }
                if (model.LeaveTime != oldModel.LeaveTime)
                {
                    logContent += string.Format(",将离职时间由【{0}】修改为【{1}】。", oldModel?.LeaveTime, model.LeaveTime);
                }
                if (model.Education != oldModel.Education)
                {
                    logContent += string.Format(",将学历由【{0}】修改为【{1}】。", oldModel.Education.ToName(), model.Education.ToName());
                }
                if (model.Email != oldModel.Email)
                {
                    logContent += string.Format(",将邮箱由【{0}】修改为【{1}】。", oldModel.Email, model.Email);
                }
                if (model.BaseHourFee != oldModel.BaseHourFee)
                {
                    logContent += string.Format(",将基础课时费由【{0}】修改为【{1}】。", oldModel.BaseHourFee, model.BaseHourFee);
                }
                if (model.BaseStuNum != oldModel.BaseStuNum)
                {
                    logContent += string.Format(",将基础带班人数由【{0}】修改为【{1}】。", oldModel.BaseStuNum, model.BaseStuNum);
                }
                if (!string.IsNullOrEmpty(logContent))
                {
                    //新增日志
                    userChangeLogModule.SetUserChangeLogModule(model.CreateBy, model.Group_Id, model.School_Id, logContent, model.TId, AccountTypeEnum.Teacher);
                }
                #endregion
                flag = teacherRepository.Update(fileds, new WhereHelper(nameof(RB_Teacher_ViewModel.TId), model.TId));
            }
            else
            {
                var newId = teacherRepository.Insert(model);
                model.TId = newId;
                userChangeLogModule.SetUserChangeLogModule(model.CreateBy, model.Group_Id, model.School_Id, "新建教师用户", newId, AccountTypeEnum.Teacher);
                flag = newId > 0;
            }
            if (flag)
            {
                var account = accountModule.GetAccountListModule(new RB_Account_ViewModel() { AccountType = AccountTypeEnum.Teacher, AccountId = model.TId })?.FirstOrDefault();
                int Id = account?.Id ?? 0;
                flag = accountModule.SetAccountModule(new RB_Account_ViewModel()
                {
                    Id = Id,
                    Account = model.TeacherAccount,
                    Password = Common.DES.Encrypt(Common.Config.DefaultPwd),
                    AccountType = AccountTypeEnum.Teacher,
                    AccountId = model.TId,
                    CreateBy = model.CreateBy,
                    UpdateBy = model.CreateBy,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    Group_Id = model.Group_Id,
                    School_Id = model.School_Id,
                    DirectSupervisor = model.DirectSupervisor
                });
            }
            return flag;
        }


        /// <summary>
        /// 新增修改讲师
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetTeacherDeptModule(RB_Teacher_ViewModel model)
        {
            bool flag;
            if (model.TId > 0)
            {
                var oldModel = GetTeacherModule(model.TId);
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Teacher_ViewModel.UpdateBy),model.UpdateBy },
                    {nameof(RB_Teacher_ViewModel.UpdateTime),model.UpdateTime },
                    {nameof(RB_Teacher_ViewModel.Dept_Id),model.Dept_Id },
                    {nameof(RB_Teacher_ViewModel.School_Id),model.School_Id },
                };
                string logContent = "";
                if (model.School_Id != oldModel.School_Id)
                {
                    var schoolList = schoolRepository.GetSchoolListRepository(new RB_School_ViewModel() { QSIds = model.School_Id + "," + oldModel.School_Id });
                    logContent += string.Format(",将校区由【{0}】修改为【{1}】。", (schoolList.Where(qitem => qitem.SId == oldModel.School_Id)?.FirstOrDefault()?.SName ?? "总部"), (schoolList.Where(qitem => qitem.SId == model.School_Id)?.FirstOrDefault()?.DeptName ?? "总部"));
                }
                if (model.Dept_Id != oldModel.Dept_Id)
                {
                    var deptList = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { QDeptIds = model.Dept_Id + "," + oldModel.Dept_Id });
                    logContent += string.Format(",将部门由【{0}】修改为【{1}】。", (deptList.Where(qitem => qitem.DeptId == oldModel.Dept_Id)?.FirstOrDefault()?.DeptName ?? ""), (deptList.Where(qitem => qitem.DeptId == model.Dept_Id)?.FirstOrDefault()?.DeptName ?? ""));
                }
                if (!string.IsNullOrEmpty(logContent))
                {
                    //新增日志
                    userChangeLogModule.SetUserChangeLogModule(model.CreateBy, model.Group_Id, model.School_Id, logContent, model.TId, AccountTypeEnum.Teacher);
                }

                //修改账号表
                Dictionary<string, object> accountFileds = new Dictionary<string, object>()
                {
                  { nameof(RB_Account_ViewModel.School_Id),model.School_Id },
                };
                List<WhereHelper> accountWhere = new List<WhereHelper>()
                {
                    new WhereHelper(nameof(RB_Account_ViewModel.AccountId),model.TId),
                    new WhereHelper(nameof(RB_Account_ViewModel.AccountType), (int) AccountTypeEnum.Teacher),
                };
                flag = accountRepository.Update(accountFileds, accountWhere);
                if (flag)
                {
                    flag = teacherRepository.Update(fileds, new WhereHelper(nameof(RB_Teacher_ViewModel.TId), model.TId));
                }
            }
            else
            {
                var newId = teacherRepository.Insert(model);
                model.TId = newId;
                flag = newId > 0;
            }
            return flag;
        }


        /// <summary>
        /// 新增修改讲师
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetTeacherPostModule(RB_Teacher_ViewModel model)
        {
            bool flag;
            if (model.TId > 0)
            {
                var oldModel = GetTeacherModule(model.TId);
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Teacher_ViewModel.UpdateBy),model.UpdateBy },
                    {nameof(RB_Teacher_ViewModel.UpdateTime),model.UpdateTime },
                    {nameof(RB_Teacher_ViewModel.Post_Id),model.Post_Id },
                };
                string logContent = "";
                if (model.Post_Id != oldModel.Post_Id)
                {
                    var postList = postRepository.GetPostListRepository(new RB_Post_ViewModel() { QPostIds = model.Post_Id + "," + oldModel.Post_Id });
                    logContent += string.Format(",将岗位由【{0}】修改为【{1}】。", (postList.Where(qitem => qitem.PostId == oldModel.Post_Id)?.FirstOrDefault()?.PostName ?? ""), (postList.Where(qitem => qitem.PostId == model.Post_Id)?.FirstOrDefault()?.PostName ?? ""));
                }
                if (!string.IsNullOrEmpty(logContent))
                {
                    //新增日志
                    userChangeLogModule.SetUserChangeLogModule(model.CreateBy, model.Group_Id, model.School_Id, logContent, model.TId, AccountTypeEnum.Teacher);
                }
                flag = teacherRepository.Update(fileds, new WhereHelper(nameof(RB_Teacher_ViewModel.TId), model.TId));
            }
            else
            {
                var newId = teacherRepository.Insert(model);
                model.TId = newId;
                flag = newId > 0;
            }
            return flag;
        }


        /// <summary>
        /// 新增修改讲师
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetTeacherLeaveTimeModule(RB_Teacher_ViewModel model)
        {
            bool flag;
            if (model.TId > 0)
            {
                var oldModel = GetTeacherModule(model.TId);
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Teacher_ViewModel.UpdateBy),model.UpdateBy },
                    {nameof(RB_Teacher_ViewModel.UpdateTime),model.UpdateTime },
                    {nameof(RB_Teacher_ViewModel.LeaveStatus),model.LeaveStatus },
                    {nameof(RB_Teacher_ViewModel.LeaveTime),model.LeaveTime }
                };
                string logContent = "";
                if (model.LeaveStatus != oldModel.LeaveStatus)
                {
                    logContent += string.Format(",将在职状态由【{0}】修改为【{1}】。", oldModel.LeaveStatus.ToName(), model.LeaveStatus.ToName());
                }
                if (model.LeaveTime != oldModel.LeaveTime)
                {
                    logContent += string.Format(",将离职时间由【{0}】修改为【{1}】。", oldModel?.LeaveTime, model.LeaveTime);
                }
                if (!string.IsNullOrEmpty(logContent))
                {
                    //新增日志
                    userChangeLogModule.SetUserChangeLogModule(model.CreateBy, model.Group_Id, model.School_Id, logContent, model.TId, AccountTypeEnum.Teacher);
                }
                flag = teacherRepository.Update(fileds, new WhereHelper(nameof(RB_Teacher_ViewModel.TId), model.TId));
            }
            else
            {
                var newId = teacherRepository.Insert(model);
                model.TId = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 根据教师编号获取实体
        /// </summary>
        /// <param name="TId"></param>
        /// <returns></returns>
        public RB_Teacher_ViewModel GetTeacherModule(int TId)
        {
            return teacherRepository.GetEntity<RB_Teacher_ViewModel>(TId);
        }

        /// <summary>
        /// 删除讲师
        /// </summary>
        /// <param name="TId"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool RemoveTeacherModule(int TId)
        {
            bool flag = false;
            var model = GetTeacherModule(TId);
            if (model != null && model.TId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Teacher_ViewModel.Status),(int)DateStateEnum.Delete },
                };
                flag = teacherRepository.Update(fileds, new WhereHelper(nameof(RB_Teacher_ViewModel.TId), TId));
                var accountList = accountModule.GetAccountListExtModule(new RB_Account_ViewModel()
                {
                    AccountId = model.TId,
                    Account = model.TeacherTel,
                    AccountType = AccountTypeEnum.Teacher
                });
                if (accountList != null && accountList.Count > 0)
                {
                    flag = accountModule.SetAccountStatusModule(new RB_Account_ViewModel()
                    {
                        AccountType = AccountTypeEnum.Teacher,
                        AccountId = model.TId,
                        UpdateTime = DateTime.Now,
                        Status = DateStateEnum.Delete
                    });
                }
            }
            return flag;
        }

        /// <summary>
        /// 重新申请
        /// </summary>
        /// <param name="TId"></param>
        /// <returns></returns>
        public bool ReApplyTeacherModule(object TId)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Teacher_ViewModel.AuditStatus),(int)AccountStatusEnum.Normal },
            };
            var flag = teacherRepository.Update(fileds, new WhereHelper(nameof(RB_Teacher_ViewModel.TId), TId));
            return flag;
        }

        /// <summary>
        /// 讲师审核
        /// </summary>
        /// <param name="TId">教师编号</param>
        /// <param name="AuditStatus">审核状态</param>
        /// <param name="AuditRemark">审核备注</param>
        /// <param name="user">用户信息</param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool AuditTeacherModule(int TId, int AuditStatus, string AuditRemark, UserInfo user)
        {
            bool flag = false;
            var model = GetTeacherModule(TId);
            if (model != null && model.TId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Teacher_ViewModel.AuditStatus),AuditStatus },
                    {nameof(RB_Teacher_ViewModel.AuditRemark),AuditRemark },
                };
                flag = teacherRepository.Update(fileds, new WhereHelper(nameof(RB_Teacher_ViewModel.TId), TId));

                AccountStatusEnum statusEnum = (AccountStatusEnum)AuditStatus;
                if (statusEnum == AccountStatusEnum.Pass && flag)
                {
                    var accountList = accountModule.GetAccountListExtModule(new RB_Account_ViewModel()
                    {
                        Account = model.TeacherTel,
                        AccountType = AccountTypeEnum.Teacher
                    });
                    if (accountList == null || (accountList != null && accountList.Count == 0))
                    {
                        flag = accountModule.SetAccountModule(new RB_Account_ViewModel()
                        {
                            Account = model.TeacherTel,
                            Password = Common.DES.Encrypt(Common.Config.DefaultPwd),
                            AccountType = AccountTypeEnum.Teacher,
                            AccountId = model.TId,
                            CreateBy = user.Id,
                            UpdateBy = user.Id,
                            CreateTime = DateTime.Now,
                            UpdateTime = DateTime.Now,
                            Group_Id = model.Group_Id,
                            School_Id = model.School_Id,
                        });
                    }
                }
            }
            return flag;
        }



        /// <summary>
        /// 根据学生id获取教师账户
        /// </summary>
        /// <param name="teacherIds"></param>
        /// <returns></returns>
        public List<RB_Teacher_ViewModel> GetListByStudentId(int Student_Id, int Group_Id)
        {
            return teacherRepository.GetListByStudentId(Student_Id, Group_Id);
        }

    }
}
