using Edu.AOP.CustomerAttribute;
using Edu.Common.Enum;
using Edu.Common.Enum.User;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.Entity.User;
using Edu.Model.ViewModel.User;
using Edu.Module.Log;
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 AssistModule
    {
        /// <summary>
        /// 助教仓储层对象
        /// </summary>
        private readonly RB_AssistRepository assistRepository = new RB_AssistRepository();

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

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

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

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

        /// <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_Assist_ViewModel> GetAssistListModule(RB_Assist_ViewModel query)
        {
            return assistRepository.GetAssistListRepository(query);
        }


        /// <summary>
        /// 获取助教分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Assist_ViewModel> GetAssistPageListModule(int pageIndex, int pageSize, out long rowsCount, RB_Assist_ViewModel query)
        {
            var list = assistRepository.GetAssistPageListRepository(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));
                List<RB_Post_ViewModel> postList = new List<RB_Post_ViewModel>();
                List<RB_Department_ViewModel> deptList = new List<RB_Department_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 });
                }
                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 ?? "";
                }
            }
            return list;
        }

        /// <summary>
        ///【员工管理端】添加修改助教
        /// </summary>
        /// <param name="model"></param>
        /// <param name="isUpdateBasic">是否更新基础资料</param>
        /// <returns></returns>
        public bool SetAssistModule(RB_Assist_ViewModel model, bool isUpdateBasic = false)
        {
            bool flag;
            if (model.AId > 0)
            {
                var oldModel = GetAssistModule(model.AId);
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Assist_ViewModel.AssistName),model.AssistName.Trim() },
                    {nameof(RB_Assist_ViewModel.AssistTel),model.AssistTel },
                    {nameof(RB_Assist_ViewModel.AssistIcon),model.AssistIcon },
                    {nameof(RB_Assist_ViewModel.UpdateBy),model.UpdateBy },
                    {nameof(RB_Assist_ViewModel.UpdateTime),model.UpdateTime },
                };
                if (isUpdateBasic)
                {
                    fileds.Add(nameof(RB_Assist_ViewModel.Dept_Id), model.Dept_Id);
                    fileds.Add(nameof(RB_Assist_ViewModel.Post_Id), model.Post_Id);
                    fileds.Add(nameof(RB_Assist_ViewModel.AssistIntro), model.AssistIntro);
                    fileds.Add(nameof(RB_Assist_ViewModel.Teacher_Id), model.Teacher_Id);
                    fileds.Add(nameof(RB_Assist_ViewModel.School_Id), model.School_Id);
                }
                else
                {
                    if (model.LeaveStatus != LeaveStatusEnum.Departure)
                    {
                        model.LeaveTime = null;
                    }
                    fileds.Add(nameof(RB_Assist_ViewModel.IDCard), model.IDCard);
                    fileds.Add(nameof(RB_Assist_ViewModel.Sex), model.Sex);
                    fileds.Add(nameof(RB_Assist_ViewModel.EntryTime), model.EntryTime);
                    fileds.Add(nameof(RB_Assist_ViewModel.Address), model.Address);
                    fileds.Add(nameof(RB_Assist_ViewModel.BirthDate), model.BirthDate);
                    fileds.Add(nameof(RB_Assist_ViewModel.LeaveStatus), model.LeaveStatus);
                    fileds.Add(nameof(RB_Assist_ViewModel.LeaveTime), model.LeaveTime);
                    fileds.Add(nameof(RB_Assist_ViewModel.Education), model.Education);
                    fileds.Add(nameof(RB_Assist_ViewModel.Email), model.Email);
                }
                string logContent = "";
                if (model.AssistName != oldModel.AssistName)
                {
                    logContent += string.Format(",将姓名由【{0}】修改为【{1}】。", oldModel.AssistName, model.AssistName);
                }
                if (model.AssistTel != oldModel.AssistTel)
                {
                    logContent += string.Format(",将电话由【{0}】修改为【{1}】。", oldModel.AssistTel, model.AssistTel);
                }
                if (model.AssistIntro != oldModel.AssistIntro)
                {
                    logContent += string.Format(",将简介由【{0}】修改为【{1}】。", oldModel.AssistIntro, model.AssistIntro);
                }
                if (model.AssistIcon != oldModel.AssistIcon)
                {
                    logContent += string.Format(",将头像由【{0}】修改为【{1}】。", oldModel.AssistIcon, model.AssistIcon);
                }
                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}】。", Common.ConvertHelper.FormatDate(oldModel.EntryTime), Common.ConvertHelper.FormatDate(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 (!string.IsNullOrEmpty(logContent))
                {
                    //新增日志
                    userChangeLogModule.SetUserChangeLogModule(model.CreateBy, model.Group_Id, model.School_Id, logContent, model.AId, AccountTypeEnum.Assist);
                }
                flag = assistRepository.Update(fileds, new WhereHelper(nameof(RB_Assist.AId), model.AId));
            }
            else
            {
                var newId = assistRepository.Insert(model);
                model.AId = newId;
                userChangeLogModule.SetUserChangeLogModule(model.CreateBy, model.Group_Id, model.School_Id, "新建助教用户", newId, AccountTypeEnum.Assist);
                flag = newId > 0;
            }
            if (flag)
            {
                var account = accountModule.GetAccountListModule(new RB_Account_ViewModel() { AccountType = AccountTypeEnum.Assist, AccountId = model.AId })?.FirstOrDefault();
                int Id = account?.Id ?? 0;
                flag = accountModule.SetAccountModule(new RB_Account_ViewModel()
                {
                    Id = Id,
                    Account = model.AssistAccount,
                    Password = Common.DES.Encrypt(Common.Config.DefaultPwd),
                    AccountType = AccountTypeEnum.Assist,
                    AccountId = model.AId,
                    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 SetAssistModule_V2(RB_Assist_ViewModel model)
        {
            bool flag;
            if (model.AId > 0)
            {
                var oldModel = GetAssistModule(model.AId);
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Assist_ViewModel.AssistName),model.AssistName.Trim() },
                    {nameof(RB_Assist_ViewModel.AssistTel),model.AssistTel },
                    {nameof(RB_Assist_ViewModel.AssistIcon),model.AssistIcon },
                    {nameof(RB_Assist_ViewModel.UpdateBy),model.UpdateBy },
                    {nameof(RB_Assist_ViewModel.UpdateTime),model.UpdateTime },
                };

                fileds.Add(nameof(RB_Assist_ViewModel.Dept_Id), model.Dept_Id);
                fileds.Add(nameof(RB_Assist_ViewModel.Post_Id), model.Post_Id);
                fileds.Add(nameof(RB_Assist_ViewModel.AssistIntro), model.AssistIntro);
                fileds.Add(nameof(RB_Assist_ViewModel.Teacher_Id), model.Teacher_Id);
                fileds.Add(nameof(RB_Assist_ViewModel.School_Id), model.School_Id);

                string logContent = "";
                if (model.AssistName != oldModel.AssistName)
                {
                    logContent += string.Format(",将姓名由【{0}】修改为【{1}】。", oldModel.AssistName, model.AssistName);
                }
                if (model.AssistTel != oldModel.AssistTel)
                {
                    logContent += string.Format(",将电话由【{0}】修改为【{1}】。", oldModel.AssistTel, model.AssistTel);
                }
                if (model.AssistIntro != oldModel.AssistIntro)
                {
                    logContent += string.Format(",将简介由【{0}】修改为【{1}】。", oldModel.AssistIntro, model.AssistIntro);
                }
                if (model.AssistIcon != oldModel.AssistIcon)
                {
                    logContent += string.Format(",将头像由【{0}】修改为【{1}】。", oldModel.AssistIcon, model.AssistIcon);
                }
                if (!string.IsNullOrEmpty(logContent))
                {
                    //新增日志
                    userChangeLogModule.SetUserChangeLogModule(model.CreateBy, model.Group_Id, model.School_Id, logContent, model.AId, AccountTypeEnum.Assist);
                }
                flag = assistRepository.Update(fileds, new WhereHelper(nameof(RB_Assist.AId), model.AId));
            }
            else
            {
                var newId = assistRepository.Insert(model);
                model.AId = newId;
                userChangeLogModule.SetUserChangeLogModule(model.CreateBy, model.Group_Id, model.School_Id, "新建助教用户", newId, AccountTypeEnum.Assist);
                flag = newId > 0;
            }
            if (flag)
            {
                var account = accountModule.GetAccountListModule(new RB_Account_ViewModel() { AccountType = AccountTypeEnum.Assist, AccountId = model.AId })?.FirstOrDefault();
                int Id = account?.Id ?? 0;
                if (Id == 0)
                {
                    flag = accountModule.SetAccountModule(new RB_Account_ViewModel()
                    {
                        Id = Id,
                        Account = model.AssistTel,
                        Password = Common.DES.Encrypt(Common.Config.DefaultPwd),
                        AccountType = AccountTypeEnum.Assist,
                        AccountId = model.AId,
                        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>
        /// <param name="isUpdateBasic">是否更新基础资料</param>
        /// <returns></returns>
        public bool SetAssistDeptModule(RB_Assist model)
        {
            bool flag;
            if (model.AId > 0)
            {
                var oldModel = GetAssistModule(model.AId);
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Assist.UpdateBy),model.UpdateBy },
                    {nameof(RB_Assist.UpdateTime),model.UpdateTime },
                    {nameof(RB_Assist.Dept_Id),model.Dept_Id },
                    {nameof(RB_Assist.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.AId, AccountTypeEnum.Assist);
                }
                //修改账号表
                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.AId),
                    new WhereHelper(nameof(RB_Account_ViewModel.AccountType), (int) AccountTypeEnum.Assist),
                };
                flag = accountRepository.Update(accountFileds, accountWhere);
                if (flag)
                {
                    flag = assistRepository.Update(fileds, new WhereHelper(nameof(RB_Assist.AId), model.AId));
                }
            }
            else
            {
                var newId = assistRepository.Insert(model);
                model.AId = newId;
                flag = newId > 0;
            }
            return flag;
        }


        /// <summary>
        /// 添加修改助教岗位
        /// </summary>
        /// <param name="model"></param>
        /// <param name="isUpdateBasic">是否更新基础资料</param>
        /// <returns></returns>
        public bool SetAssistPostModule(RB_Assist model)
        {
            bool flag;
            if (model.AId > 0)
            {
                var oldModel = GetAssistModule(model.AId);
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Assist.UpdateBy),model.UpdateBy },
                    {nameof(RB_Assist.UpdateTime),model.UpdateTime },
                    {nameof(RB_Assist.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.AId, AccountTypeEnum.Assist);
                }
                flag = assistRepository.Update(fileds, new WhereHelper(nameof(RB_Assist.AId), model.AId));
            }
            else
            {
                var newId = assistRepository.Insert(model);
                model.AId = newId;
                flag = newId > 0;
            }
            return flag;
        }


        /// <summary>
        /// 添加修改助教离职时间
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetAssistLeaveTimeModule(RB_Assist model)
        {
            bool flag;
            if (model.AId > 0)
            {
                var oldModel = GetAssistModule(model.AId);
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Assist.LeaveStatus),model.LeaveStatus },
                    {nameof(RB_Assist.LeaveTime),model.LeaveTime },
                    {nameof(RB_Assist.UpdateBy),model.UpdateBy },
                    {nameof(RB_Assist.UpdateTime),model.UpdateTime },

                };
                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.AId, AccountTypeEnum.Assist);
                }
                flag = assistRepository.Update(fileds, new WhereHelper(nameof(RB_Assist.AId), model.AId));
            }
            else
            {
                var newId = assistRepository.Insert(model);
                model.AId = newId;
                flag = newId > 0;
            }
            return flag;
        }


        /// <summary>
        /// 根据编号获取助教实体
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Assist_ViewModel GetAssistModule(int AId)
        {
            return assistRepository.GetEntity<RB_Assist_ViewModel>(AId);
        }

        /// <summary>
        /// 根据编号移除助教
        /// </summary>
        /// <param name="AId"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool RemoveAssistModule(int AId)
        {
            bool flag = false;
            var model = GetAssistModule(AId);
            if (model != null && model.AId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Assist.Status),(int)DateStateEnum.Delete },
                };
                flag = assistRepository.Update(fileds, new WhereHelper(nameof(RB_Assist.AId), AId));
                var accountList = accountModule.GetAccountListExtModule(new RB_Account_ViewModel()
                {
                    AccountId = model.AId,
                    Account = model.AssistTel,
                    AccountType = AccountTypeEnum.Assist
                });
                if (accountList != null && accountList.Count > 0)
                {
                    flag = accountModule.SetAccountStatusModule(new RB_Account_ViewModel()
                    {
                        AccountType = AccountTypeEnum.Assist,
                        AccountId = model.AId,
                        UpdateTime = DateTime.Now,
                        Status = DateStateEnum.Delete
                    });
                }
            }
            return flag;
        }

        /// <summary>
        /// 助教重新申请
        /// </summary>
        /// <param name="AId"></param>
        /// <returns></returns>
        public bool ReApplyAssistModule(object AId)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Assist.AuditStatus),(int)AccountStatusEnum.Normal },
            };
            bool flag = assistRepository.Update(fileds, new WhereHelper(nameof(RB_Assist.AId), AId));
            return flag;
        }

        /// <summary>
        /// 讲师审核
        /// </summary>
        /// <param name="AId">助教编号</param>
        /// <param name="AuditStatus">审核状态</param>
        /// <param name="AuditRemark">审核备注</param>
        /// <param name="user">用户信息</param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool AuditAssistModule(int AId, int AuditStatus, string AuditRemark, UserInfo user)
        {
            bool flag = false;
            var model = GetAssistModule(AId);
            if (model != null && model.AId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Assist_ViewModel.AuditStatus),AuditStatus },
                    {nameof(RB_Assist_ViewModel.Remark),AuditRemark },
                };
                flag = assistRepository.Update(fileds, new WhereHelper(nameof(RB_Assist_ViewModel.AId), AId));
                AccountStatusEnum statusEnum = (AccountStatusEnum)AuditStatus;
                if (statusEnum == AccountStatusEnum.Pass && flag)
                {
                    var accountList = accountModule.GetAccountListExtModule(new RB_Account_ViewModel()
                    {
                        Account = model.AssistTel,
                        AccountType = AccountTypeEnum.Assist
                    });
                    if (accountList == null || (accountList != null && accountList.Count == 0))
                    {
                        flag = accountModule.SetAccountModule(new RB_Account_ViewModel()
                        {
                            Account = model.AssistTel,
                            Password = Common.DES.Encrypt(Common.Config.DefaultPwd),
                            AccountType = AccountTypeEnum.Assist,
                            AccountId = model.AId,
                            CreateBy = user.Id,
                            UpdateBy = user.Id,
                            CreateTime = DateTime.Now,
                            UpdateTime = DateTime.Now,
                            Group_Id = model.Group_Id,
                            School_Id = model.School_Id,
                        });
                    }
                }
            }
            return flag;
        }
    }
}