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.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 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>
        /// <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));
                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 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 },
                    {nameof(RB_Teacher_ViewModel.Dept_Id),model.Dept_Id },
                    {nameof(RB_Teacher_ViewModel.Post_Id),model.Post_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);
                }
                else
                {
                    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);
                }
                string logContent = "";
                if (model.TeacherName != oldModel.TeacherName)
                {
                    logContent += string.Format(",将姓名由【{0}】修改为【{1}】。", oldModel.TeacherName, oldModel.TeacherName);
                }
                if (model.TeacherTel != oldModel.TeacherTel)
                {
                    logContent += string.Format(",将电话由【{0}】修改为【{1}】。", oldModel.TeacherTel, oldModel.TeacherTel);
                }
                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 (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 (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 (!string.IsNullOrEmpty(logContent))
                {
                    //新增日志
                    userChangeLogModule.SetUserChangeLogModule(model.CreateBy, model.Group_Id, model.School_Id, logContent);
                }
                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;
        }
    }
}
