using Edu.AOP.CustomerAttribute;
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 Edu.ThirdCore.QYWinXin;
using System;
using System.Collections.Generic;
using System.Linq;
using VT.FW.DB;

namespace Edu.Module.User
{
    /// <summary>
    /// 管理者处理类
    /// </summary>
    public class ManagerModule
    {
        /// <summary>
        /// 管理者仓储层对象
        /// </summary>
        private readonly RB_ManagerRepository managerRepository = new RB_ManagerRepository();

        /// <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_SchoolRepository schoolRepository = new RB_SchoolRepository();

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

        /// <summary>
        /// 讲师仓储层对象
        /// </summary>
        private readonly RB_TeacherRepository teacherRepository = new RB_TeacherRepository();

        /// <summary>
        /// 助教仓储层对象
        /// </summary>
        private readonly RB_AssistRepository assistRepository = new RB_AssistRepository();

        /// <summary>
        /// 获取管理者列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Manager_ViewModel> GetManagerListModule(RB_Manager_ViewModel query)
        {
            return managerRepository.GetManagerListRepository(query);
        }

        /// <summary>
        /// 新增修改管理者
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public bool SetManagerModule(RB_Manager_ViewModel model)
        {
            bool flag;
            bool IsInsert = false, IsLeave = false, IsUpdate = true;
            if (model.MId > 0)
            {
                var oldModel = GetManagerModule(model.MId);
                if (oldModel.LeaveStatus != LeaveStatusEnum.Departure && model.LeaveStatus == LeaveStatusEnum.Departure)
                {
                    IsLeave = true;
                }
                else if (oldModel.LeaveStatus == LeaveStatusEnum.Departure && model.LeaveStatus != LeaveStatusEnum.Departure) {
                    IsInsert = true;
                }
                else if (oldModel.LeaveStatus == LeaveStatusEnum.Departure && model.LeaveStatus == LeaveStatusEnum.Departure)
                {
                    IsUpdate = false;
                }

                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_Manager_ViewModel.MName),model.MName.Trim()},
                    { nameof(RB_Manager_ViewModel.MTel),model.MTel.Trim()},
                    { nameof(RB_Manager_ViewModel.MHead),model.MHead },
                    { nameof(RB_Manager_ViewModel.UpdateBy),model.UpdateBy },
                    { nameof(RB_Manager_ViewModel.UpdateTime),model.UpdateTime },
                    { nameof(RB_Manager_ViewModel.IDCard),model.IDCard },
                    { nameof(RB_Manager_ViewModel.Sex),model.Sex },
                    { nameof(RB_Manager_ViewModel.EntryTime),model.EntryTime },
                    { nameof(RB_Manager_ViewModel.Address),model.Address },
                    { nameof(RB_Manager_ViewModel.BirthDate),model.BirthDate },
                    { nameof(RB_Manager_ViewModel.LeaveStatus),model.LeaveStatus },
                    { nameof(RB_Manager_ViewModel.LeaveTime),model.LeaveTime },
                    { nameof(RB_Manager_ViewModel.Education),model.Education },
                    { nameof(RB_Manager_ViewModel.Email),model.Email },
                    { nameof(RB_Manager_ViewModel.UserRole),model.UserRole },
                    { nameof(RB_Manager_ViewModel.IsTenCccUser),model.IsTenCccUser },
                };

                #region 日志
                string logContent = "";
                if (model.MName != oldModel.MName)
                {
                    logContent += string.Format(",将姓名由【{0}】修改为【{1}】。", oldModel.MName, oldModel.MName);
                }
                if (model.MTel != oldModel.MTel)
                {
                    logContent += string.Format(",将电话由【{0}】修改为【{1}】。", oldModel.MTel, oldModel.MTel);
                }
                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 (model.UserRole != oldModel.UserRole)
                {
                    logContent += string.Format(",用户角色由【{0}】修改为【{1}】。", oldModel.UserRole.ToName(), model.UserRole.ToName());
                }
                if (!string.IsNullOrEmpty(logContent))
                {
                    //新增日志
                    userChangeLogModule.SetUserChangeLogModule(model.CreateBy, model.Group_Id, model.School_Id, logContent, model.MId, AccountTypeEnum.Admin);
                }
                #endregion

                flag = managerRepository.Update(fileds, new WhereHelper(nameof(RB_Manager_ViewModel.MId), model.MId));
            }
            else
            {
                IsInsert = true;
                var newId = managerRepository.Insert(model);
                model.MId = newId;
                flag = newId > 0;
                userChangeLogModule.SetUserChangeLogModule(model.CreateBy, model.Group_Id, model.School_Id, "新建用户", newId, AccountTypeEnum.Admin);
            }
            if (flag)
            {
                var account = accountModule.GetAccountListModule(new RB_Account_ViewModel() { AccountType = AccountTypeEnum.Admin, AccountId = model.MId })?.FirstOrDefault();
                int Id = account?.Id ?? 0;
                flag = accountModule.SetAccountModule(new RB_Account_ViewModel
                {
                    Id = Id,
                    Account = model.ManagerAccount,
                    Password = model.Password,
                    AccountType = AccountTypeEnum.Admin,
                    AccountId = model.MId,
                    CreateBy = model.CreateBy,
                    CreateTime = model.CreateTime,
                    UpdateBy = model.UpdateBy,
                    UpdateTime = model.UpdateTime,
                    Group_Id = model.Group_Id,
                    School_Id = model.School_Id,
                    Status = 0,
                    AnnualLeaveDay = 0,
                    DirectSupervisor = model.DirectSupervisor
                });
                if (flag && !string.IsNullOrEmpty(model.Token) && IsUpdate) {
                    System.Threading.Tasks.Task.Run(() =>
                    {
                        //用户
                        var accountModel = accountModule.GetAccountListExtModule(new RB_Account_ViewModel() { AccountType = AccountTypeEnum.Admin, AccountId = model.MId })?.FirstOrDefault();
                        if (string.IsNullOrEmpty(accountModel.WorkUserId) && IsLeave == false) { IsInsert = true; }//走新增方法
                        if (IsInsert)
                        {
                            //新增企业微信用户
                            //成员UserID。对应管理端的帐号，企业内必须唯一。不区分大小写，长度为1~64个字节。只能由数字、字母和“_-@.”四种字符组成，且第一个字符必须是数字或字母。
                            string userId = accountModel.Id + "_" + DateTime.Now.ToString("yyyyMMddHHmmssffff@") + (new Random().Next(1000, 9999));//规则生成
                                                                                                                                                   //获取部门信息
                            int wxDeptId = departmentRepository.GetEntity(accountModel.Dept_Id)?.WorkDepartId ?? 1;
                            wxDeptId = wxDeptId == 0 ? 1 : wxDeptId;//微信 1表示默认部门
                            //新增用户
                            var inserMember = new Senparc.Weixin.Work.AdvancedAPIs.MailList.Member.MemberCreateRequest()
                            {
                                to_invite = true,
                                alias = "",
                                userid = userId,
                                name = accountModel.AccountName,
                                english_name = "",
                                mobile = accountModel.Account,
                                department = new long[] { wxDeptId },
                                order = new long[] { 0 },
                                position = accountModel.PostName,
                                gender = (model.Sex + 1).ToString(),
                                email = "",
                                enable = 1,
                                avatar_mediaid = "",
                                telephone = "",
                                address = "",
                            };
                            try
                            {
                                var cmodel = QYWeiXinHelper.CreateMember(model.Token, inserMember);
                                if (cmodel.errcode == Senparc.Weixin.ReturnCode_Work.请求成功)
                                {
                                    //更新账户表企业微信id
                                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                    { nameof(RB_Account_ViewModel.WorkUserId),userId}
                                };
                                    List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Account_ViewModel.Id),
                                      FiledValue=accountModel.Id,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                                    accountRepository.Update(keyValues, wheres);
                                }
                                else
                                {
                                    LogHelper.Write("员工 " + accountModel.AccountName + "(" + accountModel.Id + ") 创建企业微信失败；" + cmodel.errmsg);
                                }
                            }
                            catch (Exception ex)
                            {
                                LogHelper.Write("员工 " + accountModel.AccountName + "(" + accountModel.Id + ") 创建企业微信失败；" + ex.Message);
                            }                            
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(accountModel.WorkUserId))
                            {
                                //修改企业微信用户
                                if (IsLeave)
                                {
                                    try
                                    {
                                        var cmodel = QYWeiXinHelper.DeleteMember(model.Token, accountModel.WorkUserId);
                                        if (cmodel.errcode == Senparc.Weixin.ReturnCode_Work.请求成功)
                                        {
                                            //更新账户表企业微信id
                                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                        { nameof(RB_Account_ViewModel.WorkUserId),""}
                                    };
                                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Account_ViewModel.Id),
                                              FiledValue=Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                            accountRepository.Update(keyValues, wheres);
                                        }
                                        else
                                        {
                                            LogHelper.Write("员工 " + model.MName + "(" + Id + ") 删除企业微信失败；" + cmodel.errmsg);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        LogHelper.Write(ex, "删除企业微信");
                                    }
                                }
                                else
                                {
                                    //获取部门信息
                                    int wxDeptId = departmentRepository.GetEntity(accountModel.Dept_Id)?.WorkDepartId ?? 1;
                                    var updateMember = new Senparc.Weixin.Work.AdvancedAPIs.MailList.Member.MemberUpdateRequest()
                                    {
                                        userid = accountModel.WorkUserId,
                                        name = accountModel.AccountName,
                                        mobile = accountModel.Account,
                                        department = new long[] { wxDeptId },
                                        order = new long[] { 0 },
                                        position = accountModel.PostName,
                                        gender = (model.Sex + 1).ToString(),
                                        enable = 1,
                                    };
                                    var upmodel = QYWeiXinHelper.UpdateMember(model.Token, updateMember);
                                    if (upmodel.errcode != Senparc.Weixin.ReturnCode_Work.请求成功)
                                    {
                                        LogHelper.Write("员工 " + model.MName + "(" + Id + ") 更新企业微信失败；" + upmodel.errmsg);
                                    }
                                }
                            }
                        }
                    });
                }
            }
            return flag;
        }


        /// <summary>
        /// 新增修改管理者
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetManagerDeptModule(RB_Manager_ViewModel model)
        {
            bool flag = false;
            if (model.MId > 0)
            {
                var oldModel = GetManagerModule(model.MId);
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_Manager_ViewModel.UpdateBy),model.UpdateBy },
                    { nameof(RB_Manager_ViewModel.UpdateTime),model.UpdateTime },
                    { nameof(RB_Manager_ViewModel.Dept_Id),model.Dept_Id },
                    { nameof(RB_Manager_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.MId, AccountTypeEnum.Admin);
                }
                //修改账号表
                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.MId),
                    new WhereHelper(nameof(RB_Account_ViewModel.AccountType), (int) AccountTypeEnum.Admin),
                };
                flag = accountRepository.Update(accountFileds, accountWhere);
                if (flag)
                {
                    flag = managerRepository.Update(fileds, new WhereHelper(nameof(RB_Manager_ViewModel.MId), model.MId));

                    if (flag && model.Dept_Id != oldModel.Dept_Id && !string.IsNullOrEmpty(model.Token)) {
                        System.Threading.Tasks.Task.Run(() =>
                        {
                            //修改企业微信用户
                            var accountModel = accountModule.GetAccountListExtModule(new RB_Account_ViewModel() { AccountType = AccountTypeEnum.Admin, AccountId = model.MId })?.FirstOrDefault();
                            //获取部门信息
                            int wxDeptId = departmentRepository.GetEntity(accountModel.Dept_Id)?.WorkDepartId ?? 1;
                            var updateMember = new Senparc.Weixin.Work.AdvancedAPIs.MailList.Member.MemberUpdateRequest()
                            {
                                userid = accountModel.WorkUserId,
                                department = new long[] { wxDeptId },
                                enable = 1
                            };
                            var upmodel = QYWeiXinHelper.UpdateMember(model.Token, updateMember);
                            if (upmodel.errcode != Senparc.Weixin.ReturnCode_Work.请求成功)
                            {
                                LogHelper.Write("员工 " + accountModel.AccountName + "(" + accountModel.Id + ") 更新企业微信部门失败；" + upmodel.errmsg);
                            }
                        });
                    }
                }
            }
            return flag;
        }


        /// <summary>
        /// 新增修改管理者
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetManagerPostModule(RB_Manager_ViewModel model)
        {
            bool flag = false;
            if (model.MId > 0)
            {
                var oldModel = GetManagerModule(model.MId);
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_Manager_ViewModel.UpdateBy),model.UpdateBy },
                    { nameof(RB_Manager_ViewModel.UpdateTime),model.UpdateTime },
                    { nameof(RB_Manager_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.MId, AccountTypeEnum.Admin);
                }
                flag = managerRepository.Update(fileds, new WhereHelper(nameof(RB_Manager_ViewModel.MId), model.MId));

                if (flag && model.Post_Id != oldModel.Post_Id && !string.IsNullOrEmpty(model.Token))
                {
                    System.Threading.Tasks.Task.Run(() =>
                    {
                        //修改企业微信用户
                        var accountModel = accountModule.GetAccountListExtModule(new RB_Account_ViewModel() { AccountType = AccountTypeEnum.Admin, AccountId = model.MId })?.FirstOrDefault();
                        var updateMember = new Senparc.Weixin.Work.AdvancedAPIs.MailList.Member.MemberUpdateRequest()
                        {
                            userid = accountModel.WorkUserId,
                            position = accountModel.PostName,
                            enable = 1
                        };
                        var upmodel = QYWeiXinHelper.UpdateMember(model.Token, updateMember);
                        if (upmodel.errcode != Senparc.Weixin.ReturnCode_Work.请求成功)
                        {
                            LogHelper.Write("员工 " + accountModel.AccountName + "(" + accountModel.Id + ") 更新企业微信岗位失败；" + upmodel.errmsg);
                        }
                    });
                }
            }
            return flag;
        }

        /// <summary>
        /// 新增修改管理者离职时间和离职状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetManagerLeaveTimeModule(RB_Manager_ViewModel model)
        {
            bool flag = false;
            if (model.MId > 0)
            {
                var oldModel = GetManagerModule(model.MId);
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_Manager_ViewModel.UpdateBy),model.UpdateBy },
                    { nameof(RB_Manager_ViewModel.UpdateTime),model.UpdateTime },
                    { nameof(RB_Manager_ViewModel.LeaveStatus),model.LeaveStatus },
                    { nameof(RB_Manager_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.MId, AccountTypeEnum.Admin);
                }
                flag = managerRepository.Update(fileds, new WhereHelper(nameof(RB_Manager_ViewModel.MId), model.MId));
            }
            return flag;
        }


        /// <summary>
        /// 根据编号获取管理者实体
        /// </summary>
        /// <param name="MId"></param>
        /// <returns></returns>
        public RB_Manager_ViewModel GetManagerModule(int MId)
        {
            var extModel = managerRepository.GetEntity<RB_Manager_ViewModel>(MId);
            return extModel;
        }

        /// <summary>
        /// 修改管理者状态
        /// </summary>
        /// <param name="MId"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        public bool RemoveManagerModule(int MId, int Status)
        {
            bool flag = false;
            var model = GetManagerModule(MId);
            if (model != null && model.MId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Manager_ViewModel.Status), Status}
                };
                flag = managerRepository.Update(fileds, new WhereHelper(nameof(RB_Manager_ViewModel.MId), MId));
                var accountList = accountModule.GetAccountListExtModule(new RB_Account_ViewModel()
                {
                    AccountId = model.MId,
                    Account = model.MTel,
                    AccountType = AccountTypeEnum.Admin
                });
                if (accountList != null && accountList.Count > 0)
                {
                    flag = accountModule.SetAccountStatusModule(new RB_Account_ViewModel()
                    {
                        AccountType = AccountTypeEnum.Admin,
                        AccountId = model.MId,
                        UpdateTime = DateTime.Now,
                        Status = (DateStateEnum)Status
                    });
                }
            }
            return flag;
        }

        /// <summary>
        /// 创建管理者账号
        /// </summary>
        /// <param name="MId"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public bool CreateManagerAccountModule(int MId, UserInfo user)
        {
            bool flag = false;
            var model = GetManagerModule(MId);
            if (model != null && model.MId > 0)
            {
                var accountList = accountModule.GetAccountListExtModule(new RB_Account_ViewModel()
                {
                    Account = model.MTel,
                    AccountType = AccountTypeEnum.Admin
                });
                if (accountList == null || (accountList != null && accountList.Count == 0))
                {
                    flag = accountModule.SetAccountModule(new RB_Account_ViewModel()
                    {
                        Account = model.MTel,
                        Password = Common.DES.Encrypt(Common.Config.DefaultPwd),
                        AccountType = AccountTypeEnum.Admin,
                        AccountId = model.MId,
                        CreateBy = user.Id,
                        UpdateBy = user.Id,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now,
                        Group_Id = model.Group_Id,
                        School_Id = model.School_Id,
                        Status = model.Status,
                    });
                }
            }
            return flag;
        }

        /// <summary>
        /// 根据学生id获取学生对应的销售
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Manager_ViewModel> GetManagerListByStuId(int Student_Id, int Group_Id)
        {
            return managerRepository.GetManagerListByStuId(Student_Id, Group_Id);
        }

        /// <summary>
        /// 修改员工类型
        /// </summary>
        /// <param name="targetAccountType">目标用户类型</param>
        /// <param name="AccountId">编号</param>
        /// <param name="AccountType">类型</param>
        /// <param name="Remark">调整原因</param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetEmployeeTypeModule(AccountTypeEnum targetAccountType, int AccountId, AccountTypeEnum AccountType, string Remark, UserInfo UserInfo)
        {
            bool flag = false;
            var model = accountRepository.GetEmployeeListRepository(new Employee_ViewModel()
            {
                AccountId = AccountId,
                School_Id = -1,
                AccountTypeStr = ((int)AccountType).ToString()
            })?.FirstOrDefault();
            if (model != null && model.Id > 0)
            {
                #region 删除原来的数据
                if (model.AccountType == AccountTypeEnum.Admin)
                {
                    flag = managerRepository.Delete(model.AccountId) > 0;
                }
                else if (model.AccountType == AccountTypeEnum.Teacher)
                {
                    flag = teacherRepository.Delete(model.AccountId) > 0;
                }
                else if (model.AccountType == AccountTypeEnum.Assist)
                {
                    flag = assistRepository.Delete(model.AccountId) > 0;
                }
                #endregion

                if (flag)
                {
                    #region 添加新数据
                    var newId = 0;
                    Dictionary<string, object> fileds = new Dictionary<string, object>()
                    {
                        {nameof(RB_Account_ViewModel.AccountType),(int)targetAccountType }
                    };

                    if (targetAccountType == AccountTypeEnum.Admin)
                    {
                        RB_Manager_ViewModel manager = new RB_Manager_ViewModel()
                        {
                            MId = 0,
                            MName = model.EmployeeName,
                            MTel = model.EmployeeTel,
                            MHead = model.UserIcon,
                            Group_Id = model.Group_Id,
                            School_Id = model.School_Id,
                            CreateBy = UserInfo.Id,
                            CreateTime = DateTime.Now,
                            UpdateBy = UserInfo.Id,
                            UpdateTime = DateTime.Now,
                            Status = DateStateEnum.Normal,
                            Dept_Id = model.Dept_Id,
                            Post_Id = model.Post_Id,
                            IDCard = model.IDCard,
                            Sex = model.Sex,
                            EntryTime = model.EntryTime,
                            Address = model.Address,
                            BirthDate = model.BirthDate,
                            LeaveStatus = model.LeaveStatus,
                            LeaveTime = model.LeaveTime,
                            Education = model.Education,
                            Email = model.Email
                        };
                        newId = managerRepository.Insert(manager);
                        flag = newId > 0;
                        manager.MId = newId;
                        fileds.Add(nameof(RB_Account_ViewModel.AccountId), newId);
                    }
                    else if (targetAccountType == AccountTypeEnum.Teacher)
                    {
                        RB_Teacher_ViewModel teacher = new RB_Teacher_ViewModel()
                        {
                            TId = 0,
                            School_Id = model.School_Id,
                            TeacherName = model.EmployeeName,
                            TeacherTel = model.EmployeeTel,
                            TeacherHead = model.UserIcon,
                            TeacherIcon = model.UserIcon,
                            TeacherSay = "",
                            TeacherIntro = "",
                            Status = model.Status,
                            AuditStatus = AccountStatusEnum.Pass,
                            AuditRemark = "",
                            IsShow = 1,
                            IsRecommend = 0,
                            SortNum = 1,
                            CreateBy = UserInfo.Id,
                            CreateTime = DateTime.Now,
                            UpdateBy = UserInfo.Id,
                            UpdateTime = DateTime.Now,
                            Group_Id = model.Group_Id,
                            TeachTag = "",
                            Dept_Id = model.Dept_Id,
                            Post_Id = model.Post_Id,
                            IDCard = model.IDCard,
                            Sex = model.Sex,
                            EntryTime = model.EntryTime,
                            Address = model.Address,
                            BirthDate = model.BirthDate,
                            LeaveStatus = model.LeaveStatus,
                            LeaveTime = model.LeaveTime,
                            Education = model.Education,
                            BaseStuNum = 13,
                            Email = model.Email,
                            BaseHourFee = 0,
                            Nationality = "",
                            ForeignersUrl = "",
                            Specialty = "1,2,3,4",
                            BaseHoursEnabled = 1,
                            EnableTime = model.EnableTime,
                        };
                        newId = teacherRepository.Insert(teacher);
                        flag = newId > 0;
                        teacher.TId = newId;
                        fileds.Add(nameof(RB_Account_ViewModel.AccountId), newId);
                    }
                    else if (targetAccountType == AccountTypeEnum.Assist)
                    {
                        RB_Assist_ViewModel assist = new RB_Assist_ViewModel()
                        {
                            AId = 0,
                            School_Id = model.School_Id,
                            Teacher_Id = 0,
                            AssistName = model.EmployeeName,
                            AssistTel = model.EmployeeTel,
                            AssistIcon = model.UserIcon,
                            AssistIntro = "",
                            AuditStatus = AccountStatusEnum.Pass,
                            Status = model.Status,
                            Remark = "",
                            Group_Id = model.Group_Id,
                            CreateBy = UserInfo.Id,
                            CreateTime = DateTime.Now,
                            UpdateBy = UserInfo.Id,
                            UpdateTime = DateTime.Now,
                            Dept_Id = model.Dept_Id,
                            Post_Id = model.Post_Id,
                            IDCard = model.IDCard,
                            Sex = model.Sex,
                            EntryTime = model.EntryTime,
                            Address = model.Address,
                            BirthDate = model.BirthDate,
                            LeaveStatus = model.LeaveStatus,
                            LeaveTime = model.LeaveTime,
                            Education = model.Education,
                            Email = model.Email
                        };
                        newId = assistRepository.Insert(assist);
                        flag = newId > 0;
                        assist.AId = newId;
                        fileds.Add(nameof(RB_Account_ViewModel.AccountId), newId);
                    }

                    if (fileds != null && fileds.Count > 0 && flag)
                    {
                        //更新关联编号
                        flag = accountRepository.Update(fileds, new WhereHelper(nameof(RB_Account_ViewModel.Id), model.Id));
                    }
                    string logContent = Remark;
                    if (model.AccountType != targetAccountType)
                    {
                        logContent += string.Format(",将在由【{0}】修改为【{1}】。", model.AccountType.ToName(), targetAccountType.ToName());
                    }
                    if (!string.IsNullOrEmpty(logContent))
                    {
                        //新增日志
                        userChangeLogModule.SetUserChangeLogModule(UserInfo.Id, model.Group_Id, model.School_Id, logContent, newId, targetAccountType);
                    }
                    #endregion
                }
            }
            return flag;
        }
    }
}