using Edu.AOP.CustomerAttribute;
using Edu.Cache.User;
using Edu.Common.Enum.Course;
using Edu.Common.Enum.EduTask;
using Edu.Common.Enum.User;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.Entity.Course;
using Edu.Model.Entity.EduTask;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.EduTask;
using Edu.Model.ViewModel.User;
using Edu.Repository.Course;
using Edu.Repository.EduTask;
using Edu.Repository.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VT.FW.DB;

namespace Edu.Module.EduTask
{
    /// <summary>
    /// 教务单据处理类
    /// </summary>
    public class EducationReceiptModule
    {
        /// <summary>
        /// 教务单据仓储层
        /// </summary>
        private readonly RB_Education_ReceiptRepository education_ReceiptRepository = new RB_Education_ReceiptRepository();

        /// <summary>
        /// 教务单据审核记录仓储层对象
        /// </summary>
        private readonly RB_Education_RecordRepository education_RecordRepository = new RB_Education_RecordRepository();

        /// <summary>
        /// 教务单据审核人员信息仓储层对象
        /// </summary>
        private readonly RB_Education_RelevanceRepository education_RelevanceRepository = new RB_Education_RelevanceRepository();

        /// <summary>
        /// 学员退课仓储层对象
        /// </summary>
        private readonly RB_Student_BackClassRepository student_BackClassRepository = new RB_Student_BackClassRepository();

        /// <summary>
        /// 学员停课仓储层对象
        /// </summary>
        private readonly RB_Student_StopClassRepository student_StopClassRepository = new RB_Student_StopClassRepository();


        /// <summary>
        /// 调课仓储层对象
        /// </summary>
        private readonly RB_Change_ClassPlanRepository change_ClassPlanRepository = new RB_Change_ClassPlanRepository();

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

        /// <summary>
        /// 教室仓储层对象
        /// </summary>
        private readonly RB_Class_RoomRepository class_RoomRepository = new RB_Class_RoomRepository();

        /// <summary>
        /// 订单学员仓储层对象
        /// </summary>
        private readonly RB_Order_GuestRepository order_GuestRepository = new RB_Order_GuestRepository();

        /// <summary>
        /// 订单转班、拆分仓储层对象
        /// </summary>
        private readonly RB_Order_ChangeRepository order_ChangeRepository = new RB_Order_ChangeRepository();

        /// <summary>
        /// 获取教务单据分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<object> GetEducationReceiptPageModule(int pageIndex, int pageSize, out long rowsCount, EducationReceiptQuery query)
        {
            List<object> result = new List<object>();
            var list = education_ReceiptRepository.GetEducationReceiptPageRepository(pageIndex, pageSize, out rowsCount, query);
            if (list != null && list.Count > 0)
            {
                //退课详情
                List<RB_Student_BackClass_ViewModel> backClassLisit = new List<RB_Student_BackClass_ViewModel>();
                //调课申请
                List<RB_Change_ClassPlan_ViewModel> changeClassList = new List<RB_Change_ClassPlan_ViewModel>();
                //停课申请
                List<RB_Student_StopClass_ViewModel> stopClassList = new List<RB_Student_StopClass_ViewModel>();
                //老师列表
                List<RB_Teacher_ViewModel> teacherList = new List<RB_Teacher_ViewModel>();
                //学生信息
                List<RB_Order_Guest_ViewModel> orderGuestList = new List<RB_Order_Guest_ViewModel>();
                //教室列表
                List<RB_Class_Room_ViewModel> roomList = new List<RB_Class_Room_ViewModel>();
                //订单转班列表
                List<RB_Order_Change_ViewModel> orderTransList = new List<RB_Order_Change_ViewModel>();
                var groupList = list.GroupBy(qitem => new { qitem.ReceiptType }).Select(qitem => new { qitem.Key.ReceiptType });
                string Ids = string.Join(",", list.Select(qitem => qitem.Id));
                var recordList = education_RecordRepository.GetEducationRecordListRepository(new RB_Education_Record_ViewModel()
                {
                    QConditionIds = Ids,
                    AuditStatus = EduTaskRrocessStatus.AuditIng
                });
                foreach (var subItem in groupList)
                {
                    #region 退课申请
                    if (subItem.ReceiptType == Common.Enum.Finance.ReceiptTypeEnum.BackClass)
                    {
                        string backIds = string.Join(",", list.Where(qitem => qitem.ReceiptType == subItem.ReceiptType).Select(qitem => qitem.RelationId));
                        backClassLisit = student_BackClassRepository.GetStudentBackClassListRepository(new RB_Student_BackClass_ViewModel()
                        {
                            QBackIds = backIds
                        });
                    }
                    #endregion

                    #region 调课申请
                    if (subItem.ReceiptType == Common.Enum.Finance.ReceiptTypeEnum.ChangeClass)
                    {
                        string changeIds = string.Join(",", list.Where(qitem => qitem.ReceiptType == subItem.ReceiptType).Select(qitem => qitem.RelationId));
                        changeClassList = change_ClassPlanRepository.GetChangeClassPlanListRepository(new RB_Change_ClassPlan_ViewModel()
                        {
                            Q_Change_ClassPlan_Ids = changeIds
                        });
                        List<int> teacherIds = new List<int>();
                        List<int> classRoomIds = new List<int>();
                        if (changeClassList != null && changeClassList.Count > 0)
                        {
                            foreach (var tempModel in changeClassList)
                            {
                                if (tempModel != null)
                                {
                                    if (!string.IsNullOrEmpty(tempModel.SourceData))
                                    {
                                        tempModel.OldChangePlanItemList = Common.Plugin.JsonHelper.DeserializeObject<List<ChangePlanItem>>(tempModel.SourceData);
                                        if (tempModel.OldChangePlanItemList != null && tempModel.OldChangePlanItemList.Count > 0)
                                        {
                                            var tempTeacherIds = Common.ConvertHelper.StringToList(string.Join(",", tempModel.OldChangePlanItemList.Select(qitem => qitem.TeacherId)));
                                            if (tempTeacherIds != null && tempTeacherIds.Count > 0)
                                            {
                                                teacherIds.AddRange(tempTeacherIds);
                                            }
                                            var tempClassRoomIds = Common.ConvertHelper.StringToList(string.Join(",", tempModel.OldChangePlanItemList.Select(qitem => qitem.ClassRoomId)));
                                            if (tempClassRoomIds != null && tempClassRoomIds.Count > 0)
                                            {
                                                classRoomIds.AddRange(tempClassRoomIds);
                                            }
                                        }
                                    }
                                    if (!string.IsNullOrEmpty(tempModel.TargetData))
                                    {
                                        if (tempModel.MoveType == 1)
                                        {
                                            tempModel.NewChangePlanItemList = Common.Plugin.JsonHelper.DeserializeObject<List<ChangePlanItem>>(tempModel.TargetData);
                                            if (tempModel.NewChangePlanItemList != null && tempModel.NewChangePlanItemList.Count > 0)
                                            {
                                                var tempNTeacherIds = Common.ConvertHelper.StringToList(string.Join(",", tempModel.NewChangePlanItemList.Select(qitem => qitem.TeacherId)));
                                                if (tempNTeacherIds != null && tempNTeacherIds.Count > 0)
                                                {
                                                    teacherIds.AddRange(tempNTeacherIds);
                                                }
                                                var tempNClassRoomIds = Common.ConvertHelper.StringToList(string.Join(",", tempModel.NewChangePlanItemList.Select(qitem => qitem.ClassRoomId)));
                                                if (tempNClassRoomIds != null && tempNClassRoomIds.Count > 0)
                                                {
                                                    classRoomIds.AddRange(tempNClassRoomIds);
                                                }
                                            }
                                        }
                                        else if (tempModel.MoveType == 2)
                                        {
                                            tempModel.AllChangePlanModel = Common.Plugin.JsonHelper.DeserializeObject<AllChangePlanItem>(tempModel.TargetData);
                                            if (tempModel.AllChangePlanModel != null && tempModel.AllChangePlanModel.TeacherId > 0)
                                            {
                                                teacherIds.Add(tempModel.AllChangePlanModel.TeacherId);
                                            }
                                            if (tempModel.AllChangePlanModel != null && tempModel.AllChangePlanModel.ClassRoomId > 0)
                                            {
                                                classRoomIds.Add(tempModel.AllChangePlanModel.ClassRoomId);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (teacherIds != null && teacherIds.Count > 0)
                        {
                            teacherList = teacherRepository.GetTeacherListRepository(new Model.ViewModel.User.RB_Teacher_ViewModel()
                            {
                                QTIds = string.Join(",", teacherIds)
                            });
                        }
                        if (classRoomIds != null && classRoomIds.Count > 0)
                        {
                            roomList = class_RoomRepository.GetClassRoomListRepository(new RB_Class_Room_ViewModel()
                            {
                                QRoomIds = string.Join(",", classRoomIds)
                            });
                        }
                    }
                    #endregion

                    #region 停课申请

                    if (subItem.ReceiptType == Common.Enum.Finance.ReceiptTypeEnum.StopClass)
                    {
                        string changeIds = string.Join(",", list.Where(qitem => qitem.ReceiptType == subItem.ReceiptType).Select(qitem => qitem.RelationId));
                        stopClassList = student_StopClassRepository.GetStudentStopClassListRepository(new RB_Student_StopClass_ViewModel()
                        {
                            Q_Student_StopClass_Ids = changeIds,
                            IsAuditThrough=-1
                        });
                        if (stopClassList != null && stopClassList.Any())
                        {
                            string orderGuestIds = string.Join(",", stopClassList.Select(x => x.OrderGuestId));
                            orderGuestList = order_GuestRepository.GetStopingStudentPage(new RB_Order_Guest_ViewModel
                            {
                                OrderGuestIds = orderGuestIds
                            });
                            if (orderGuestList != null && orderGuestList.Any())
                            {
                                orderGuestList.ForEach(x => x.EnterName = x.EnterID > 0? (UserReidsCache.GetUserLoginInfo(x.EnterID)?.AccountName ?? ""):"");
                                stopClassList.ForEach(x => x.Order_Guest_ViewModel = orderGuestList.Where(y => y.Id == x.OrderGuestId).FirstOrDefault());
                            }
                        }
                    }

                    #endregion

                    #region 订单转班
                    if (subItem.ReceiptType == Common.Enum.Finance.ReceiptTypeEnum.OrderTransClass)
                    {
                        string transClassIds = string.Join(",", list.Where(qitem => qitem.ReceiptType == subItem.ReceiptType).Select(qitem => qitem.RelationId));
                        orderTransList = order_ChangeRepository.GetOrderChangeListRepository(new RB_Order_Change_ViewModel()
                        {
                            QIds = transClassIds,
                            ChangeType = 1,
                        });
                    }
                    #endregion
                }

                foreach (var item in list)
                {
                    object DataObj = new object();
                    //退课
                    if (item.ReceiptType == Common.Enum.Finance.ReceiptTypeEnum.BackClass)
                    {
                        DataObj = backClassLisit?.Where(qitem => qitem.BackId == item.RelationId)?.FirstOrDefault();
                    }
                    //调课
                    if (item.ReceiptType == Common.Enum.Finance.ReceiptTypeEnum.ChangeClass)
                    {
                        var tempModel = changeClassList.Where(qitem => qitem.Id == item.RelationId)?.FirstOrDefault();
                        if (tempModel.OldChangePlanItemList != null && tempModel.OldChangePlanItemList.Count > 0)
                        {
                            foreach (var sItem in tempModel.OldChangePlanItemList)
                            {
                                sItem.TeacherName = teacherList?.Where(qitem => qitem.TId == sItem.TeacherId)?.FirstOrDefault()?.TeacherName ?? "";
                                sItem.ClassRoomName = roomList?.Where(qitem => qitem.RoomId == sItem.ClassRoomId)?.FirstOrDefault()?.RoomName ?? "";
                            }
                        }
                        if (tempModel.NewChangePlanItemList != null && tempModel.NewChangePlanItemList.Count > 0)
                        {
                            foreach (var sItem in tempModel.NewChangePlanItemList)
                            {
                                sItem.TeacherName = teacherList?.Where(qitem => qitem.TId == sItem.TeacherId)?.FirstOrDefault()?.TeacherName ?? "";
                                sItem.ClassRoomName = roomList?.Where(qitem => qitem.RoomId == sItem.ClassRoomId)?.FirstOrDefault()?.RoomName ?? "";
                            }
                        }
                        if (tempModel.AllChangePlanModel != null)
                        {
                            tempModel.AllChangePlanModel.TeacherName = teacherList?.Where(qitem => qitem.TId == tempModel.AllChangePlanModel.TeacherId)?.FirstOrDefault()?.TeacherName ?? "";
                            tempModel.AllChangePlanModel.ClassRoomName = roomList?.Where(qitem => qitem.RoomId == tempModel.AllChangePlanModel.ClassRoomId)?.FirstOrDefault()?.RoomName ?? "";
                        }
                        DataObj = tempModel;
                    }
                    //停课
                    if (item.ReceiptType == Common.Enum.Finance.ReceiptTypeEnum.StopClass)
                    {
                        DataObj = stopClassList?.Where(qitem => qitem.Id == item.RelationId)?.FirstOrDefault();
                    }
                    //订单转班
                    if (item.ReceiptType == Common.Enum.Finance.ReceiptTypeEnum.OrderTransClass)
                    {
                        DataObj = orderTransList?.Where(qitem => qitem.Id == item.RelationId)?.FirstOrDefault();
                    }
                    object AuditObj = new object();
                    if (item.VerifyStatus == EduTaskRrocessStatus.NotAudit || item.VerifyStatus == EduTaskRrocessStatus.AuditIng)
                    {
                        var tempRecordList = recordList?.Where(qitem => qitem.ConditionId == item.Id)?.ToList();
                        if (tempRecordList != null && tempRecordList.Count > 0)
                        {
                            foreach (var rItem in tempRecordList)
                            {
                                rItem.AuditManName = UserReidsCache.GetUserLoginInfo(rItem.AuditEmId)?.AccountName ?? "";
                            }
                            AuditObj = new
                            {
                                tempRecordList[0].AuditNode,
                                AuditManList = tempRecordList.Select(qitem => new { qitem.AuditEmId, qitem.AuditManName })
                            };
                        }
                    }
                    var obj = new
                    {
                        item.Id,
                        item.Title,
                        item.ClassId,
                        item.ClassName,
                        item.ClassNo,
                        item.OrderId,
                        item.ReceiptType,
                        DataObj,
                        item.SpecialNode,
                        item.RelationId,
                        ReceiptTypeName = item.ReceiptType.ToName(),
                        CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName,
                        CreateTime = Common.ConvertHelper.FormatTime(item.CreateTime),
                        item.TeacherName,
                        item.SchoolName,
                        item.CourseName,
                        AuditObj,
                        item.VerifyStatus,
                        AuditStatusName = item.VerifyStatus == Common.Enum.EduTask.EduTaskRrocessStatus.NotAudit ? "待审" : item.VerifyStatus.ToName(),
                    };
                    result.Add(obj);
                }
            }
            return result;
        }

        /// <summary>
        ///  获取单据当前审核人列表
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public virtual object GetCurrentAuditManModule(int Id)
        {
            List<object> list = new List<object>();
            var recordList = education_RecordRepository.GetEducationRecordListRepository(new RB_Education_Record_ViewModel()
            {
                QConditionIds = Id.ToString(),
                AuditStatus = EduTaskRrocessStatus.AuditIng
            });
            if (recordList != null && recordList.Count > 0)
            {
                foreach (var item in recordList)
                {
                    var obj = new
                    {
                        item.Id,
                        item.ConditionId,
                        item.AuditId,
                        item.AuditEmId,
                        item.NewAuditEmId
                    };
                    list.Add(obj);
                }
            }
            return list;
        }

        /// <summary>
        /// 作废教务单据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool InvalidReceiptModule(int Id)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Education_Receipt_ViewModel.VerifyStatus),(int)Edu.Common.Enum.User.WFRrocessStatus.Invalid}
            };
            return education_ReceiptRepository.Update(fileds, new WhereHelper(nameof(RB_Education_Receipt_ViewModel.Id), Id));
        }

        /// <summary>
        /// 修改审核人员
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool EditAuditManModule(List<RB_Education_Record_ViewModel> list)
        {
            bool flag = true;
            foreach (var item in list)
            {
                if (flag && item.NewAuditEmId > 0)
                {
                    Dictionary<string, object> fileds = new Dictionary<string, object>()
                    {
                        {nameof(RB_Education_Record_ViewModel.AuditEmId),item.NewAuditEmId }
                    };
                    flag = education_RecordRepository.Update(fileds, new WhereHelper(nameof(RB_Education_Record_ViewModel.Id), item.Id));
                }
            }
            if (flag)
            {
                var recordList = education_RecordRepository.GetEducationRecordListRepository(new RB_Education_Record_ViewModel()
                {
                    AuditId = list[0].AuditId
                });
                var relevance = education_RelevanceRepository.GetEducationRelevanceListRepository(new RB_Education_Relevance_ViewModel()
                {
                    ConditionId = list[0].ConditionId,

                })?.FirstOrDefault();

                if (recordList != null && recordList.Count > 0 && relevance != null)
                {
                    string audits = string.Join(",", recordList.Select(qitem => qitem.AuditEmId));
                    Dictionary<string, object> fileds = new Dictionary<string, object>()
                    {
                        {nameof(RB_Education_Relevance_ViewModel.ToAuditId),audits.TrimStart(',').TrimEnd(',') }
                    };
                    flag = education_RelevanceRepository.Update(fileds, new WhereHelper(nameof(RB_Education_Relevance_ViewModel.Id), relevance.Id));
                }
            }
            return flag;
        }

        /// <summary>
        /// 获取单据详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public object GetEducationReceiptInfoModule(object Id)
        {
            var obj = new List<object>();
            var receipt = education_ReceiptRepository.GetEntity(Id);
            string ApplyReason = "";
            if (receipt.ReceiptType == Common.Enum.Finance.ReceiptTypeEnum.BackClass)
            {
                //获取单据实体类
                var backModel = student_BackClassRepository.GetEntity(receipt.RelationId);
                ApplyReason = backModel?.ApplyReason ?? "";
            }
            else if (receipt.ReceiptType == Common.Enum.Finance.ReceiptTypeEnum.ChangeClass)
            {
                var changeClassModel = change_ClassPlanRepository.GetEntity<RB_Change_ClassPlan_ViewModel>(receipt.RelationId);
                ApplyReason = changeClassModel?.Remarks ?? "";
            }
            else if (receipt.ReceiptType == Common.Enum.Finance.ReceiptTypeEnum.StopClass)
            {
                var changeClassModel = student_StopClassRepository.GetEntity<RB_Student_StopClass_ViewModel>(receipt.RelationId);
                ApplyReason = changeClassModel?.Remarks ?? "";
            }
            //获取审核记录
            var aurList = education_RecordRepository.GetEducationRecordListRepository(new RB_Education_Record_ViewModel()
            {
                ConditionId = receipt.Id,
            });
            //审核关联列表
            var arList = education_RelevanceRepository.GetEducationRelevanceListRepository(new RB_Education_Relevance_ViewModel()
            {
                ConditionId = receipt.Id
            });

            obj.Add(new
            {
                NodeName = "制单人",
                AduitStatus = 2,
                AuditWayName = "",
                AduitStatusName = "发起",
                SubList = new List<object>()
                {
                   new{
                         AduitName= UserReidsCache.GetUserLoginInfo(receipt.CreateBy)?.AccountName ?? "",
                         Description=ApplyReason,
                         CreateTime=Common.ConvertHelper.FormatTime(receipt.CreateTime),
                         AuditStatus=WFRrocessStatus.AuditThrough,
                         AuditStatusName = WFRrocessStatus.AuditThrough.ToName(),
                      }
                }
            });

            var existsList = arList.Where(qitem => aurList.Any(oldItem => qitem.Id == oldItem.AuditId));
            foreach (var item in existsList)
            {
                obj.Add(new
                {
                    NodeName = item.AuditDescription,
                    AduitStatus = item.Stauts,
                    AduitStatusName = GetWFRrocessStatusStrModule(item.Stauts),
                    AuditWayName = item.AuditWay != WFTAuditWayEnum.Successively ? item.AuditWay.ToName() : "",
                    SubList = aurList.Where(qitem => qitem.AuditId == item.Id).Select(qitem => new
                    {
                        AduitName = UserReidsCache.GetUserLoginInfo(qitem.AuditEmId)?.AccountName ?? "",
                        Description = !string.IsNullOrEmpty(qitem.Description) ? qitem.Description : "无",
                        CreateTime = Common.ConvertHelper.FormatTime(qitem.UpdateTime),
                        qitem.AuditStatus,
                        AuditStatusName = GetWFRrocessStatusStrModule(qitem.AuditStatus),
                    })
                });
            }
            return obj;
        }

        /// <summary>
        /// 教务单据审核
        /// </summary>
        /// <param name="model">审核信息</param>
        /// <param name="user">登录用户信息</param>
        /// <param name="message">返回提示信息</param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool AduitEducationReceiptModule(EduReceiptAudit auditModel, UserInfo user, out string message)
        {
            message = "";
            bool flag = false;
            //获取单据实体类
            var receipt = education_ReceiptRepository.GetEntity(auditModel.Id);
            if (receipt == null)
            {
                message = "单据不存在,请核实!";
                return flag;
            }
            //抄送人
            string newRecipientIds = "";
            if (!string.IsNullOrEmpty(auditModel.RecipientIds))
            {
                newRecipientIds = ((!string.IsNullOrEmpty(receipt.RecipientIds) ? receipt.RecipientIds : "") + "," + auditModel.RecipientIds).TrimStart(',').TrimEnd(',');
            }
            //获取审核记录
            var aurList = education_RecordRepository.GetEducationRecordListRepository(new RB_Education_Record_ViewModel()
            {
                ConditionId = auditModel.Id,
            });
            //审核关联列表
            var arList = education_RelevanceRepository.GetEducationRelevanceListRepository(new RB_Education_Relevance_ViewModel()
            {
                ConditionId = auditModel.Id
            });

            //驳回处理
            if (auditModel.AuditStatus == 3)
            {
                //找出当前审核
                int Notcount = arList.Where(x => x.Stauts == EduTaskRrocessStatus.AuditNotThrough).Count();
                if (Notcount > 0)
                {
                    message = "该申请单已被拒绝!";
                    return false;
                }
                var ToAuditFlow = arList.Where(x => x.Stauts == EduTaskRrocessStatus.AuditIng).OrderBy(x => x.Sort).ToList();
                if (ToAuditFlow.Count <= 0)
                {
                    message = "该申请单审核已经完结!";
                    return false;
                }
                if (ToAuditFlow.Count > 0)
                {
                    var model = ToAuditFlow[0];
                    var RecordList = aurList.Where(x => x.AuditId == model.Id).ToList();
                    var amodel = RecordList.Where(x => x.AuditStatus == EduTaskRrocessStatus.AuditIng && x.AuditEmId == user.Id).FirstOrDefault();
                    if (amodel == null)
                    {
                        message = "尚未匹配到审核相关信息，请联系管理员!";
                        return false;
                    }
                    //同时  修改  审核记录状态 审核流程 
                    model.Stauts = EduTaskRrocessStatus.AuditNotThrough;
                    if (!string.IsNullOrWhiteSpace(model.AuditedId))
                    {
                        model.AuditedId += "," + user.Id;
                    }
                    else
                    {
                        model.AuditedId = user.Id.ToString();
                    }

                    #region 更新审核记录表状态
                    flag = UpdateEduRecordModule(WFRrocessStatus.AuditNotThrough, auditModel.Description, user.Id, amodel.Id);
                    #endregion

                    #region 更新审核关联表状态
                    flag = UpdateEduRelevanceModule(model.Id, model.Stauts, model.AuditedId);
                    #endregion

                    var list = RecordList.Where(x => x.AuditStatus == EduTaskRrocessStatus.AuditIng && x.AuditEmId != user.Id).ToList();
                    int AuditCount = list.Count();
                    if (AuditCount > 0)//表示最后一个人就是子集审核   申请单 通过
                    {
                        foreach (var item in list)
                        {
                            flag = UpdateEduRecordModule(WFRrocessStatus.OtherHaveAudit, auditModel.Description, user.Id, item.Id);
                        }
                    }
                }

                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Education_Receipt_ViewModel.VerifyStatus),(int)EduTaskRrocessStatus.Rejected}
                };
                flag = education_ReceiptRepository.Update(fileds, new WhereHelper(nameof(RB_Education_Receipt_ViewModel.Id), receipt.Id));
                flag = UpdateOtherModule(receipt, auditModel);
            }
            //审核通过
            else
            {
                //找出当前审核
                int Notcount = arList.Where(x => x.Stauts == EduTaskRrocessStatus.AuditNotThrough).Count();
                if (Notcount > 0)
                {
                    message = "该申请单已被拒绝";
                    return false;
                }

                var ToAuditFlow = arList.Where(x => x.Stauts == EduTaskRrocessStatus.AuditIng).OrderBy(x => x.Sort).ToList();
                if (ToAuditFlow.Count <= 0)
                {
                    message = "该申请单审核已经完结";
                    return false;
                }
                //审核关联表字段
                var relevanceFileds = new Dictionary<string, object>();
                ///目前审核为最后一步
                if (ToAuditFlow.Count == 1)
                {
                    var model = ToAuditFlow[0];
                    var RecordList = aurList.Where(x => x.AuditId == model.Id).ToList();
                    if (model.AuditWay == WFTAuditWayEnum.Countersign)
                    {
                        //会签  所有人必须审核完该流程才算完成
                        var amodel = RecordList.Where(x => x.AuditStatus == EduTaskRrocessStatus.AuditIng && x.AuditEmId == user.Id).FirstOrDefault();
                        if (amodel == null)
                        {
                            message = "尚未匹配到审核相关信息，请联系管理员!";
                            return false;
                        }

                        #region 更新审核记录表状态
                        flag = UpdateEduRecordModule(WFRrocessStatus.AuditThrough, auditModel.Description, user.Id, amodel.Id);
                        #endregion

                        int AuditCount = RecordList.Where(x => x.AuditStatus == EduTaskRrocessStatus.AuditIng && x.AuditEmId != user.Id).Count();
                        if (AuditCount <= 0)//表示最后一个人就是子集审核   申请单 通过
                        {
                            //同时  修改  审核记录状态 审核流程 
                            model.Stauts = EduTaskRrocessStatus.AuditThrough;
                            if (!string.IsNullOrWhiteSpace(model.AuditedId))
                            {
                                model.AuditedId += "," + user.Id;
                            }
                            else
                            {
                                model.AuditedId = user.Id.ToString();
                            }

                            #region 更新审核关联表状态
                            flag = UpdateEduRelevanceModule(model.Id, model.Stauts, model.AuditedId);
                            #endregion

                            flag = UpdateOtherModule(receipt, auditModel);

                        }
                        else
                        {
                            //同时  修改  审核记录状态 审核流程 
                            model.Stauts = EduTaskRrocessStatus.AuditThrough;
                            if (!string.IsNullOrWhiteSpace(model.AuditedId))
                            {
                                model.AuditedId += "," + user.Id;
                            }
                            else
                            {
                                model.AuditedId = user.Id.ToString();
                            }

                            #region 更新审核关联表状态
                            flag = UpdateEduRelevanceModule(model.Id, null, model.AuditedId);
                            #endregion
                        }
                    }
                    else if (model.AuditWay == WFTAuditWayEnum.OrSign)
                    {
                        var amodel = RecordList.Where(x => x.AuditStatus == EduTaskRrocessStatus.AuditIng && x.AuditEmId == user.Id).FirstOrDefault();
                        if (amodel == null)
                        {
                            message = "尚未匹配到审核相关信息，请联系管理员!";
                            return false;
                        }
                        //同时  修改  审核记录状态 审核流程 
                        model.Stauts = EduTaskRrocessStatus.AuditThrough;
                        if (!string.IsNullOrWhiteSpace(model.AuditedId))
                        {
                            model.AuditedId += "," + user.Id;
                        }
                        else
                        {
                            model.AuditedId = user.Id.ToString();
                        }

                        #region 更新审核记录表状态
                        flag = UpdateEduRecordModule(WFRrocessStatus.AuditThrough, auditModel.Description, user.Id, amodel.Id);
                        #endregion

                        #region 更新审核关联表状态
                        flag = UpdateEduRelevanceModule(model.Id, model.Stauts, model.AuditedId);
                        #endregion

                        var list = RecordList.Where(x => x.AuditStatus == EduTaskRrocessStatus.AuditIng && x.AuditEmId != user.Id).ToList();
                        int AuditCount = list.Count();
                        if (AuditCount > 0)//表示最后一个人就是子集审核   申请单 通过
                        {
                            foreach (var item in list)
                            {
                                flag = UpdateEduRecordModule(WFRrocessStatus.OtherHaveAudit, auditModel.Description, user.Id, item.Id);
                            }
                        }
                        flag = UpdateOtherModule(receipt, auditModel);
                    }
                    else
                    {
                        var amodel = RecordList.Where(x => x.AuditStatus == EduTaskRrocessStatus.AuditIng && x.AuditEmId == user.Id).FirstOrDefault();
                        if (amodel == null)
                        {
                            message = "尚未匹配到审核相关信息，请联系管理员!";
                            return false;
                        }
                        var list = RecordList.Where(x => x.AuditStatus == EduTaskRrocessStatus.AuditIng && x.AuditEmId != user.Id).ToList();
                        int AuditCount = list.Count();
                        if (AuditCount > 0)
                        {
                            message = "流程配置出错啦！非会签，或签 都只能有一个审核人!";
                            return false;
                        }
                        //同时  修改  审核记录状态 审核流程 
                        model.Stauts = EduTaskRrocessStatus.AuditThrough;
                        if (!string.IsNullOrWhiteSpace(model.AuditedId))
                        {
                            model.AuditedId += "," + user.Id;
                        }
                        else
                        {
                            model.AuditedId = user.Id.ToString();
                        }
                        #region 更新审核记录表状态
                        flag = UpdateEduRecordModule(WFRrocessStatus.AuditThrough, auditModel.Description, user.Id, amodel.Id);
                        #endregion
                        #region 更新审核关联表状态
                        flag = UpdateEduRelevanceModule(model.Id, model.Stauts, model.AuditedId);
                        #endregion

                        flag = UpdateOtherModule(receipt, auditModel);
                    }

                    Dictionary<string, object> fileds = new Dictionary<string, object>()
                    {
                        {nameof(RB_Education_Receipt_ViewModel.VerifyStatus),(int)EduTaskRrocessStatus.AuditThrough}
                    };
                    flag = education_ReceiptRepository.Update(fileds, new WhereHelper(nameof(RB_Education_Receipt_ViewModel.Id), receipt.Id));
                }
                //同时创建下一步审核  复制审核人到审核关联表   创建审核记录表
                else
                {
                    var model = ToAuditFlow[0];
                    var RecordList = aurList.Where(x => x.AuditId == model.Id).ToList();

                    //会签  所有人必须审核完该流程才算完成
                    if (model.AuditWay == WFTAuditWayEnum.Countersign)
                    {
                        var amodel = RecordList.Where(x => x.AuditStatus == EduTaskRrocessStatus.AuditIng && x.AuditEmId == user.Id).FirstOrDefault();
                        if (amodel == null)
                        {
                            message = "尚未匹配到审核相关信息，请联系管理员!";
                            return false;
                        }
                        //审核记录状态
                        #region 更新审核记录表状态

                        flag = UpdateEduRecordModule(WFRrocessStatus.AuditThrough, auditModel.Description, user.Id, amodel.Id);
                        #endregion

                        int AuditCount = RecordList.Where(x => x.AuditStatus == EduTaskRrocessStatus.AuditIng && x.AuditEmId != user.Id).Count();
                        if (AuditCount <= 0)//表示最后一个人就是子集审核   申请单 通过
                        {
                            //同时  修改  审核流程 
                            model.Stauts = EduTaskRrocessStatus.AuditThrough;
                            if (!string.IsNullOrWhiteSpace(model.AuditedId))
                            {
                                model.AuditedId += "," + user.Id;
                            }
                            else
                            {
                                model.AuditedId = user.Id.ToString();
                            }
                            #region 更新审核关联表状态
                            flag = UpdateEduRelevanceModule(model.Id, model.Stauts, model.AuditedId);
                            #endregion
                            //赋值下一步到审核记录中  并更新这一步的待审核人
                            var modelNext = ToAuditFlow[1];
                            flag = InsertAuditRelevanceNext(receipt, modelNext);
                            if (flag == false)
                            {
                                message = "审核流程不完整无法审核，请联系相关负责人!";
                                return false;
                            }
                        }
                        else
                        {
                            //同时  修改  审核流程 
                            if (!string.IsNullOrWhiteSpace(model.AuditedId))
                            {
                                model.AuditedId += "," + user.Id;
                            }
                            else
                            {
                                model.AuditedId = user.Id.ToString();
                            }
                            #region 更新审核关联表状态
                            relevanceFileds = new Dictionary<string, object>
                            {
                                { nameof(RB_Education_Relevance_ViewModel.AuditedId), model.AuditedId },
                            };
                            flag = education_RelevanceRepository.Update(relevanceFileds, new WhereHelper(nameof(RB_Education_Relevance_ViewModel.Id), model.Id));
                            #endregion
                        }
                    }
                    else if (model.AuditWay == WFTAuditWayEnum.OrSign)
                    {
                        var amodel = RecordList.Where(x => x.AuditStatus == EduTaskRrocessStatus.AuditIng && x.AuditEmId == user.Id).FirstOrDefault();
                        if (amodel == null)
                        {
                            message = "尚未匹配到审核相关信息，请联系管理员!";
                            return false;
                        }
                        //同时  修改  审核记录状态 审核流程 
                        model.Stauts = EduTaskRrocessStatus.AuditThrough;
                        if (!string.IsNullOrWhiteSpace(model.AuditedId))
                        {
                            model.AuditedId += "," + user.Id;
                        }
                        else
                        {
                            model.AuditedId = user.Id.ToString();
                        }
                        #region 更新审核记录表状态

                        flag = UpdateEduRecordModule(WFRrocessStatus.AuditThrough, auditModel.Description, user.Id, amodel.Id);
                        #endregion

                        #region 更新审核关联表状态
                        flag = UpdateEduRelevanceModule(model.Id, model.Stauts, model.AuditedId);
                        #endregion

                        var list = RecordList.Where(x => x.AuditStatus == EduTaskRrocessStatus.AuditIng && x.AuditEmId != user.Id).ToList();
                        int AuditCount = list.Count();
                        if (AuditCount > 0)//表示最后一个人就是子集审核   申请单 通过
                        {
                            foreach (var item in list)
                            {
                                flag = UpdateEduRecordModule(WFRrocessStatus.OtherHaveAudit, auditModel.Description, user.Id, item.Id);
                            }
                        }
                        //赋值下一步到审核记录中  并更新这一步的待审核人
                        var modelNext = ToAuditFlow[1];
                        flag = InsertAuditRelevanceNext(receipt, modelNext);
                        if (flag == false)
                        {
                            message = "审核流程不完整无法审核，请联系相关负责人!";
                            return false;
                        }
                    }
                    else
                    {
                        var amodel = RecordList.Where(x => x.AuditStatus == EduTaskRrocessStatus.AuditIng && x.AuditEmId == user.Id).FirstOrDefault();
                        if (amodel == null)
                        {
                            message = "尚未匹配到审核相关信息，请联系管理员!";
                            return false;
                        }
                        var list = RecordList.Where(x => x.AuditStatus == EduTaskRrocessStatus.AuditIng && x.AuditEmId != user.Id).ToList();
                        int AuditCount = list.Count();
                        if (AuditCount > 0)
                        {
                            message = "流程配置出错啦！非会签、或签 都只能有一个审核人!";
                            return false;
                        }
                        //同时  修改  审核记录状态 审核流程 
                        model.Stauts = EduTaskRrocessStatus.AuditThrough;
                        if (!string.IsNullOrWhiteSpace(model.AuditedId))
                        {
                            model.AuditedId += "," + user.Id;
                        }
                        else
                        {
                            model.AuditedId = user.Id.ToString();
                        }
                        #region 更新审核记录表状态
                        flag = UpdateEduRecordModule(WFRrocessStatus.AuditThrough, auditModel.Description, user.Id, amodel.Id);
                        #endregion

                        #region 更新审核关联表状态
                        flag = UpdateEduRelevanceModule(model.Id, model.Stauts, model.AuditedId);

                        #endregion
                        //赋值下一步到审核记录中  并更新这一步的待审核人
                        var modelNext = ToAuditFlow[1];
                        flag = InsertAuditRelevanceNext(receipt, modelNext);
                        if (flag == false)
                        {
                            message = "审核流程不完整无法审核，请联系相关负责人!";
                            return false;
                        }
                    }
                    Dictionary<string, object> fileds = new Dictionary<string, object>()
                    {
                        {nameof(RB_Education_Receipt_ViewModel.VerifyStatus),(int)EduTaskRrocessStatus.AuditIng}
                    };
                    flag = education_ReceiptRepository.Update(fileds, new WhereHelper(nameof(RB_Education_Receipt_ViewModel.Id), receipt.Id));
                }
            }
            return flag;
        }

        /// <summary>
        /// 获取审核状态字符串
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        private string GetWFRrocessStatusStrModule(EduTaskRrocessStatus status)
        {
            var statusName = "待审";
            switch (status)
            {
                case EduTaskRrocessStatus.AuditNotThrough: statusName = "拒绝"; break;
                case EduTaskRrocessStatus.AuditThrough: statusName = "通过"; break;
                case EduTaskRrocessStatus.NotAudit: statusName = "待审"; break;
                case EduTaskRrocessStatus.OtherHaveAudit: statusName = "通过"; break;
                case EduTaskRrocessStatus.Rejected: statusName = "驳回"; break;
                case EduTaskRrocessStatus.Invalid: statusName = "作废"; break;
            }
            return statusName;
        }

        /// <summary>
        /// 更新其他信息
        /// </summary>
        /// <param name="receiptModel">单据实体</param>
        /// <param name="auditModel">审核实体</param>
        /// <returns></returns>
        public bool UpdateOtherModule(RB_Education_Receipt receiptModel, EduReceiptAudit auditModel)
        {
            bool flag = true;
            //退课
            if (receiptModel.ReceiptType == Common.Enum.Finance.ReceiptTypeEnum.BackClass)
            {
                if (auditModel.AuditStatus == 2)
                {
                    flag = student_BackClassRepository.UpdateStudentBackClassRepository(receiptModel, auditModel);
                }
                if (auditModel.AuditStatus == 3)
                {
                    flag = student_BackClassRepository.UpdateStudentBackClassRepository(receiptModel, auditModel);
                }
            }
            //调课
            if (receiptModel.ReceiptType == Common.Enum.Finance.ReceiptTypeEnum.ChangeClass)
            {
                if (auditModel.AuditStatus == 2)
                {
                    flag = change_ClassPlanRepository.UpdateChangeClassPlan(receiptModel.Id);
                }
            }
            //停课
            if (receiptModel.ReceiptType == Common.Enum.Finance.ReceiptTypeEnum.StopClass)
            {
                if (auditModel.AuditStatus == 2)
                {
                    flag = student_StopClassRepository.UpdateStudentStopClass(receiptModel, auditModel.AuditStatus);
                }
                if (auditModel.AuditStatus == 3)
                {
                    flag = student_StopClassRepository.UpdateStudentStopClass(receiptModel, auditModel.AuditStatus);
                }
            }
            return flag;
        }


        /// <summary>
        /// 更新审核记录表信息
        /// </summary>
        /// <param name="wFRrocessStatus">审核状态</param>
        /// <param name="Description">审核意见</param>
        /// <param name="UserId">审核人Id</param>
        /// <param name="Id">审核记录编号</param>
        /// <returns></returns>
        private bool UpdateEduRecordModule(WFRrocessStatus wFRrocessStatus, string Description, int UserId, int Id)
        {
            var recordFileds = new Dictionary<string, object>
            {
                { nameof(RB_Education_Record_ViewModel.AuditStatus), wFRrocessStatus },
                { nameof(RB_Education_Record_ViewModel.Description),Description} ,
                { nameof(RB_Education_Record_ViewModel.UpdateBy),UserId},
                { nameof(RB_Education_Record_ViewModel.UpdateTime),DateTime.Now}
            };
            bool flag = education_RecordRepository.Update(recordFileds, new WhereHelper(nameof(RB_Education_Record_ViewModel.Id), Id));
            return flag;
        }

        /// <summary>
        /// 更新审核流程信息
        /// </summary>
        /// <param name="status"></param>
        /// <param name="AuditedId"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        private bool UpdateEduRelevanceModule(int Id, EduTaskRrocessStatus? status = null, string AuditedId = "")
        {
            var relevanceFileds = new Dictionary<string, object>();
            if (!string.IsNullOrEmpty(AuditedId))
            {
                relevanceFileds.Add(nameof(RB_Education_Relevance_ViewModel.AuditedId), AuditedId);
            }
            if (status != null)
            {
                relevanceFileds.Add(nameof(RB_Education_Relevance_ViewModel.Stauts), status);
            }
            bool flag = education_RelevanceRepository.Update(relevanceFileds, new WhereHelper(nameof(RB_Education_Relevance_ViewModel.Id), Id));
            return flag;
        }

        /// <summary>
        /// 添加拷贝审核节点
        /// </summary>
        /// <param name="receiptModel">单据实体</param>
        /// <param name="modelNext">审核关联</param>
        private bool InsertAuditRelevanceNext(RB_Education_Receipt receiptModel, RB_Education_Relevance_ViewModel modelNext)
        {
            if (modelNext != null)
            {
                RB_Education_Relevance_ViewModel auditRelevance = modelNext.RefMapperTo<RB_Education_Relevance_ViewModel>();
                if (auditRelevance != null)
                {
                    List<int> empList = new List<int>();
                    if (auditRelevance.AuditType == WFTAuditTypeEnum.SpecifiedMember)
                    {
                        //添加指定用户
                        if (!string.IsNullOrEmpty(auditRelevance.UserIds))
                        {
                            var userList = Common.ConvertHelper.StringToList(auditRelevance.UserIds);
                            foreach (var item in userList)
                            {
                                if (item > 0)
                                {
                                    empList.Add(item);
                                }
                            }
                        }
                    }
                    else if (auditRelevance.AuditType == WFTAuditTypeEnum.Role)
                    {
                        //添加角色对应的人员
                        if (!string.IsNullOrEmpty(auditRelevance.PostIds))
                        {
                            var postList = Common.ConvertHelper.StringToList(auditRelevance.PostIds);
                            if (postList != null && postList.Count > 0)
                            {
                                foreach (var item in postList)
                                {
                                    //本班教师审核
                                    if (item == 1)
                                    {
                                        var teacherId = education_ReceiptRepository.GetTeacherIdRepository(receiptModel.ClassId);
                                        if (teacherId > 0)
                                        {
                                            empList.Add(teacherId);
                                        }
                                    }
                                    //关联销售审核
                                    else if (item == 2)
                                    {
                                        var saleId = education_ReceiptRepository.GetOrderSaleIdRepository(receiptModel.OrderId);
                                        empList.Add(saleId);
                                    }
                                    //分区校长审核
                                    else if (item == 3)
                                    {
                                        var schoolMasterId = education_ReceiptRepository.GetSchoolMasterIdRepository(receiptModel.Group_Id);
                                        if (schoolMasterId > 0)
                                        {
                                            empList.Add(schoolMasterId);
                                        }
                                    }
                                    //教务长审核
                                    else if (item == 4)
                                    {
                                        var schoolJiaoWuZhangId = education_ReceiptRepository.GetSchoolJiaoWuZhangIdRepository(receiptModel.Group_Id);
                                        if (schoolJiaoWuZhangId > 0)
                                        {
                                            empList.Add(schoolJiaoWuZhangId);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (auditRelevance.AuditType == WFTAuditTypeEnum.Post)
                    {
                        var postUserIdList = education_ReceiptRepository.GetPostIdsRepository(receiptModel.Group_Id, auditRelevance.SysPostIds);
                        if (postUserIdList != null && postUserIdList.Count > 0)
                        {
                            empList.AddRange(postUserIdList);
                        }
                    }
                    InsertBatcheAuditRecord(empList, receiptModel.Id, auditRelevance);
                }
            }
            return true;
        }

        /// <summary>
        /// 批量添加审核人
        /// </summary>
        /// <param name="empIds">审核人id集合</param>
        /// <param name="wfId">工作流id</param>
        /// <param name="auditRelevance">审核节点</param>
        private void InsertBatcheAuditRecord(List<int> empIds, int wfId, RB_Education_Relevance_ViewModel auditRelevance)
        {
            List<RB_Education_Record_ViewModel> auditrecordList = new List<RB_Education_Record_ViewModel>();
            foreach (var item in empIds)
            {
                RB_Education_Record_ViewModel auditrecord = new RB_Education_Record_ViewModel
                {
                    AuditEmId = item,
                    AuditId = auditRelevance.Id,
                    AuditStatus = EduTaskRrocessStatus.AuditIng,
                    CreateBy = item,
                    CreateTime = DateTime.Now,
                    UpdateBy = item,
                    UpdateTime = DateTime.Now,
                    ConditionId = wfId,
                    Description = "",
                };
                auditrecordList.Add(auditrecord);
            }
            education_RecordRepository.InsertBatch(auditrecordList);

            auditRelevance.ToAuditId = string.Join(",", empIds);
            education_RelevanceRepository.Update(auditRelevance);
        }
    }
}
