
using Edu.Cache.User;
using Edu.Common;
using Edu.Common.Enum.Course;
using Edu.Common.Enum.User;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.Entity.Course;
using Edu.Model.ViewModel.Course;
using Edu.Repository.Course;
using Edu.Repository.Flow;
using Edu.Repository.Log;
using Edu.Repository.User;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VT.FW.DB;

namespace Edu.Module.Course
{
    /// <summary>
    /// 学员单据处理类
    /// </summary>
    public class StudentBillModule
    {
        /// <summary>
        /// 学员退课单据仓储层对象
        /// </summary>
        private readonly RB_Student_BackClassRepository student_BackClassRepository = new RB_Student_BackClassRepository();

        /// <summary>
        /// 退款单据审核人员信息仓储层对象
        /// </summary>
        private readonly RB_Student_BackRelevanceRepository student_BackRelevanceRepository = new RB_Student_BackRelevanceRepository();

        /// <summary>
        /// 学员退课单据审核记录仓储层对象
        /// </summary>
        private readonly RB_Student_BackRecordRepository student_BackRecordRepository = new RB_Student_BackRecordRepository();

        /// <summary>
        /// 旅客表仓储层对象
        /// </summary>
        private readonly RB_Order_GuestRepository order_GuestRepository = new RB_Order_GuestRepository();

        /// <summary>
        /// 订单仓储层对象
        /// </summary>
        private readonly RB_OrderRepository orderRepository = new RB_OrderRepository();

        /// <summary>
        /// 班级
        /// </summary>
        private readonly RB_ClassRepository classRepository = new RB_ClassRepository();

        /// <summary>
        /// 学校
        /// </summary>
        private readonly RB_SchoolRepository schoolRepository = new RB_SchoolRepository();

        /// <summary>
        /// 账号
        /// </summary>
        private readonly RB_AccountRepository accountRepository = new RB_AccountRepository();

        /// <summary>
        /// 日志
        /// </summary>
        private readonly RB_User_ChangeLogRepository changeLogRepository = new RB_User_ChangeLogRepository();

        /// <summary>
        /// 班级基础配置表仓储层对象
        /// </summary>
        private readonly RB_Class_ConfigRepository class_ConfigRepository = new RB_Class_ConfigRepository();

        /// <summary>
        /// 学员签到仓储层对象
        /// </summary>
        private readonly RB_Class_CheckRepository class_CheckRepository = new RB_Class_CheckRepository();

        /// <summary>
        /// 财务配置
        /// </summary>
        private readonly RB_Finance_ConfigRepository finance_ConfigRepository = new RB_Finance_ConfigRepository();

        /// <summary>
        /// 班级处理类
        /// </summary>
        private readonly ClassModule classModule = new ClassModule();

        /// <summary>
        /// 获取学员退课单据分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Student_BackClass_ViewModel> GetStudentBackClassPageListModule(int pageIndex, int pageSize, out long rowsCount, RB_Student_BackClass_ViewModel query)
        {
            return student_BackClassRepository.GetStudentBackClassPageListRepository(pageIndex, pageSize, out rowsCount, query);
        }

        /// <summary>
        /// 计算学员退课金额
        /// </summary>
        /// <param name="BackId"></param>
        /// <returns></returns>
        public object GetBackBillMoneyModule(int BackId)
        {
            var backModel = student_BackClassRepository.GetEntity(BackId);
            var guestModel = order_GuestRepository.GetEntity(backModel.GuestId);
            var orderModel = orderRepository.GetEntity(backModel.OrderId);
            //班级实体类
            var classModel = classRepository.GetEntity(backModel.ClassId);
            //基础课时分钟数
            var BasicMinutes = class_ConfigRepository.GetClassConfigRepository(new RB_Class_Config_ViewModel() { Group_Id = backModel.Group_Id })?.BasicMinutes ?? 45;
            var stuCheckList = class_CheckRepository.GetGuestFinishMinutesRepository(backModel.GuestId.ToString());
            //总签到上课分钟数
            var totalFinishMinutes = stuCheckList?.Sum(qitem => qitem.FinishMinutes) ?? 0;
            //完成课时数
            var FinishHours = Convert.ToInt32(totalFinishMinutes) / BasicMinutes;
            //课时单价
            var classHourPrice = Math.Round(orderModel.PreferPrice / orderModel.GuestNum / classModel.ClassHours, 2);
            //预计退款金额
            var backMoney = (classModel.ClassHours - FinishHours) * classHourPrice;
            var obj = new
            {
                orderModel.PreferPrice,
                orderModel.GuestNum,
                classModel.ClassHours,
                FinishHours,
                classHourPrice,
                backMoney = Math.Round(backMoney, 2)
            };
            return obj;
        }

        /// <summary>
        /// 退课单据审核
        /// </summary>
        /// <param name="BackId">退课单据号</param>
        /// <param name="AuditStatus">审核状态(1-待审核，2-审核通过，3-驳回)</param>
        /// <param name="Description">审核备注</param>
        /// <param name="user">登录用户信息</param>
        /// <param name="message">返回提示信息</param>
        /// <param name="BackMoney"></param>
        /// <returns></returns>
        public virtual bool SetBackBillAduitModule(int BackId, int AuditStatus, string Description, UserInfo user, out string message, int SpecialNode = 0, decimal BackMoney = 0, string RecipientIds = "")
        {
            message = "";
            bool flag = false;
            //获取单据实体类
            var backModel = student_BackClassRepository.GetEntity(BackId);
            if (backModel == null)
            {
                message = "单据不存在,请核实!";
                return flag;
            }
            //抄送人
            string newRecipientIds = "";
            if (!string.IsNullOrEmpty(RecipientIds))
            {
                newRecipientIds = ((!string.IsNullOrEmpty(backModel.RecipientIds) ? backModel.RecipientIds : "") + "," + RecipientIds).TrimStart(',').TrimEnd(',');
            }

            //获取审核记录
            var aurList = student_BackRecordRepository.GetStudentBackRecordListRepository(new RB_Student_BackRecord_ViewModel()
            {
                ConditionId = backModel.BackId,
            });
            //审核关联列表
            var arList = student_BackRelevanceRepository.GetStudentBackRelevanceListRepository(new RB_Student_BackRelevance_ViewModel()
            {
                ConditionId = backModel.BackId
            });

            //驳回处理
            if (AuditStatus == 3)
            {
                //找出当前审核
                int Notcount = arList.Where(x => x.Stauts == WFRrocessStatus.AuditNotThrough).Count();
                if (Notcount > 0)
                {
                    message = "该申请单已被拒绝!";
                    return false;
                }
                var ToAuditFlow = arList.Where(x => x.Stauts == WFRrocessStatus.NotAudit).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 == WFRrocessStatus.NotAudit && x.AuditEmId == user.Id).FirstOrDefault();
                    if (amodel == null)
                    {
                        message = "尚未匹配到审核相关信息，请联系管理员!";
                        return false;
                    }
                    //同时  修改  审核记录状态 审核流程 
                    model.Stauts = WFRrocessStatus.AuditNotThrough;
                    if (!string.IsNullOrWhiteSpace(model.AuditedId))
                    {
                        model.AuditedId += "," + user.Id;
                    }
                    else
                    {
                        model.AuditedId = user.Id.ToString();
                    }
                    #region 更新审核记录表状态
                    flag = UpdateStuRecordModule(WFRrocessStatus.AuditNotThrough, Description, user.Id, amodel.Id);
                    #endregion
                    #region 更新审核关联表状态
                    flag = UpdateStuRelevanceModule(model.Id, model.Stauts, model.AuditedId);
                    #endregion

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

                #region  更新订单旅客表未驳回状态
                flag = UpdateOrderGuestStatusModule(4, backModel.StudentId);
                #endregion

                #region 更新退课单据为驳回状态
                flag = UpdateStuBackBillStatusModule(BackClassAuditStatusEnum.Rejected, newRecipientIds, backModel, SpecialNode: SpecialNode, BackMoney: BackMoney);
                #endregion
            }
            //审核通过
            else
            {
                //找出当前审核
                int Notcount = arList.Where(x => x.Stauts == WFRrocessStatus.AuditNotThrough).Count();
                if (Notcount > 0)
                {
                    message = "该退课申请单已被拒绝";
                    return false;
                }

                var ToAuditFlow = arList.Where(x => x.Stauts == WFRrocessStatus.NotAudit).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 == WFRrocessStatus.NotAudit && x.AuditEmId == user.Id).FirstOrDefault();
                        if (amodel == null)
                        {
                            message = "尚未匹配到审核相关信息，请联系管理员!";
                            return false;
                        }
                        #region 更新审核记录表状态
                        flag = UpdateStuRecordModule(WFRrocessStatus.AuditThrough, Description, user.Id, amodel.Id);
                        #endregion

                        int AuditCount = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId != user.Id).Count();
                        if (AuditCount <= 0)//表示最后一个人就是子集审核   申请单 通过
                        {
                            //同时  修改  审核记录状态 审核流程 
                            model.Stauts = WFRrocessStatus.AuditThrough;
                            if (!string.IsNullOrWhiteSpace(model.AuditedId))
                            {
                                model.AuditedId += "," + user.Id;
                            }
                            else
                            {
                                model.AuditedId = user.Id.ToString();
                            }
                            #region 更新审核关联表状态
                            flag = UpdateStuRelevanceModule(model.Id, model.Stauts, model.AuditedId);
                            #endregion
                            //更新主表状态
                            flag = UpdateStuBackBillStatusModule(BackClassAuditStatusEnum.Pass, newRecipientIds, backModel, SpecialNode: SpecialNode, BackMoney: BackMoney);
                            #region  更新订单旅客表未通过状态
                            flag = UpdateOrderGuestStatusModule(2, backModel.StudentId);
                            #endregion
                        }
                        else
                        {
                            //同时  修改  审核记录状态 审核流程 
                            model.Stauts = WFRrocessStatus.AuditThrough;
                            if (!string.IsNullOrWhiteSpace(model.AuditedId))
                            {
                                model.AuditedId += "," + user.Id;
                            }
                            else
                            {
                                model.AuditedId = user.Id.ToString();
                            }
                            #region 更新审核关联表状态
                            flag = UpdateStuRelevanceModule(model.Id, null, model.AuditedId);
                            #endregion
                        }
                    }
                    else if (model.AuditWay == WFTAuditWayEnum.OrSign)
                    {
                        var amodel = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId == user.Id).FirstOrDefault();
                        if (amodel == null)
                        {
                            message = "尚未匹配到审核相关信息，请联系管理员!";
                            return false;
                        }
                        //同时  修改  审核记录状态 审核流程 
                        model.Stauts = WFRrocessStatus.AuditThrough;
                        if (!string.IsNullOrWhiteSpace(model.AuditedId))
                        {
                            model.AuditedId += "," + user.Id;
                        }
                        else
                        {
                            model.AuditedId = user.Id.ToString();
                        }
                        #region 更新审核记录表状态
                        flag = UpdateStuRecordModule(WFRrocessStatus.AuditThrough, Description, user.Id, amodel.Id);
                        #endregion

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

                        var list = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId != user.Id).ToList();
                        int AuditCount = list.Count();
                        if (AuditCount > 0)//表示最后一个人就是子集审核   申请单 通过
                        {
                            foreach (var item in list)
                            {
                                flag = UpdateStuRecordModule(WFRrocessStatus.OtherHaveAudit, Description, user.Id, item.Id);
                            }
                        }
                        //更新主表状态
                        flag = UpdateStuBackBillStatusModule(BackClassAuditStatusEnum.Pass, newRecipientIds, backModel, SpecialNode: SpecialNode, BackMoney: BackMoney);
                        #region  更新订单旅客表未通过状态
                        flag = UpdateOrderGuestStatusModule(2, backModel.StudentId);
                        #endregion
                    }
                    else
                    {
                        var amodel = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId == user.Id).FirstOrDefault();
                        if (amodel == null)
                        {
                            message = "尚未匹配到审核相关信息，请联系管理员!";
                            return false;
                        }
                        var list = RecordList.Where(x => x.AuditStatus == WFRrocessStatus.NotAudit && x.AuditEmId != user.Id).ToList();
                        int AuditCount = list.Count();
                        if (AuditCount > 0)
                        {
                            message = "流程配置出错啦！非会签，或签 都只能有一个审核人!";
                            return false;
                        }
                        //同时  修改  审核记录状态 审核流程 
                        model.Stauts = WFRrocessStatus.AuditThrough;
                        if (!string.IsNullOrWhiteSpace(model.AuditedId))
                        {
                            model.AuditedId += "," + user.Id;
                        }
                        else
                        {
                            model.AuditedId = user.Id.ToString();
                        }
                        #region 更新审核记录表状态
                        flag = UpdateStuRecordModule(WFRrocessStatus.AuditThrough, Description, user.Id, amodel.Id);
                        #endregion
                        #region 更新审核关联表状态
                        flag = UpdateStuRelevanceModule(model.Id, model.Stauts, model.AuditedId);
                        #endregion
                        //更新主表状态
                        flag = UpdateStuBackBillStatusModule(BackClassAuditStatusEnum.Pass, newRecipientIds, backModel, SpecialNode: SpecialNode, BackMoney: BackMoney);
                        #region  更新订单旅客表未通过状态
                        flag = UpdateOrderGuestStatusModule(2, backModel.StudentId);
                        #endregion
                    }
                }
                //同时创建下一步审核  复制审核人到审核关联表   创建审核记录表
                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 == WFRrocessStatus.NotAudit && x.AuditEmId == user.Id).FirstOrDefault();
                        if (amodel == null)
                        {
                            message = "尚未匹配到审核相关信息，请联系管理员!";
                            return false;
                        }
                        //审核记录状态
                        #region 更新审核记录表状态

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

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

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

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

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

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

                        #endregion
                        //赋值下一步到审核记录中  并更新这一步的待审核人
                        var modelNext = ToAuditFlow[1];
                        flag = InsertAuditRelevanceNext(backModel, modelNext);
                        if (flag == false)
                        {
                            message = "审核流程不完整无法审核，请联系相关负责人!";
                            return false;
                        }
                    }
                }
            }
            return flag;
        }

        /// <summary>
        /// 更新退课主表状态
        /// </summary>
        /// <param name="statusEnum">审核状态</param>
        /// <param name="newRecipientIds">抄送人</param>
        /// <param name="backModel">退课表实体信息</param>
        /// <param name="SpecialNode">是否是特殊节点(1-是)</param>
        /// <param name="BackMoney">实际退款金额</param>
        /// <returns></returns>
        private bool UpdateStuBackBillStatusModule(BackClassAuditStatusEnum statusEnum, string newRecipientIds, RB_Student_BackClass backModel, int SpecialNode = 0, decimal BackMoney = 0)
        {
            Dictionary<string, object> backFileds = new Dictionary<string, object>()
            {
               {nameof(RB_Student_BackClass_ViewModel.AuditStatus), (int)statusEnum }
            };
            if (!string.IsNullOrEmpty(newRecipientIds))
            {
                backFileds.Add(nameof(RB_Student_BackClass_ViewModel.RecipientIds), newRecipientIds);
            }
            //特殊节点更新时间退课金额
            if (SpecialNode == 1)
            {
                backFileds.Add(nameof(RB_Student_BackClass_ViewModel.RealityBackMoney), BackMoney);
            }

            bool flag = student_BackClassRepository.Update(backFileds, new WhereHelper(nameof(RB_Student_BackClass_ViewModel.BackId), backModel.BackId));
            if (flag)
            {
                var guestList = order_GuestRepository.GetList(new RB_Order_Guest_ViewModel() { OrderId = backModel.OrderId });
                if (guestList != null && guestList.Where(qitem => qitem.GuestState == 2).Count() == guestList.Count())
                {
                    //更新订单为退学状态
                    Dictionary<string, object> orderFileds = new Dictionary<string, object>()
                    {
                        {nameof(RB_Order.OrderState),OrderStateEnum.DropOut }
                    };
                    flag = orderRepository.Update(orderFileds, new WhereHelper(nameof(RB_Order.OrderId), backModel.OrderId));
                }
            }
            return flag;
        }

        /// <summary>
        /// 更新学员退课状态
        /// </summary>
        /// <param name="GuestState"></param>
        /// <param name="guestId"></param>
        /// <returns></returns>
        private bool UpdateOrderGuestStatusModule(int GuestState, int guestId)
        {
            Dictionary<string, object> guestFileds = new Dictionary<string, object>()
            {
                {nameof(RB_Order_Guest_ViewModel.GuestState),GuestState }
            };
            return order_GuestRepository.Update(guestFileds, new WhereHelper(nameof(RB_Order_Guest_ViewModel.Id), guestId));
        }

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

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

        /// <summary>
        /// 添加拷贝审核节点
        /// </summary>
        /// <param name="backModel">退课单据实体</param>
        /// <param name="modelNext">审核关联</param>
        private bool InsertAuditRelevanceNext(RB_Student_BackClass backModel, RB_Student_BackRelevance_ViewModel modelNext)
        {
            if (modelNext != null)
            {
                RB_Student_BackRelevance_ViewModel auditRelevance = modelNext.RefMapperTo<RB_Student_BackRelevance_ViewModel>();
                if (auditRelevance != null)
                {
                    List<int> empList = new List<int>();
                    //添加角色对应的人员
                    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)
                                {
                                    empList.Add(backModel.TeacherId);
                                }
                                //关联销售审核
                                else if (item == 2)
                                {
                                    var orderModel = orderRepository.GetEntity(backModel.OrderId);
                                    empList.Add(orderModel.EnterID);
                                }
                                //分区校长审核
                                else if (item == 3)
                                {
                                    var headmaster = accountRepository.GetAccountListExtRepository(new Model.ViewModel.User.RB_Account_ViewModel()
                                    {
                                        Post_Id = Common.Config.SchoolPostId,
                                        Group_Id = backModel.Group_Id
                                    })?.FirstOrDefault();
                                    if (headmaster != null && headmaster.Id > 0)
                                    {
                                        empList.Add(headmaster.Id);
                                    }
                                }
                                else if (item == 4)
                                {
                                    var headmaster = accountRepository.GetAccountListExtRepository(new Model.ViewModel.User.RB_Account_ViewModel()
                                    {
                                        Post_Id = Common.Config.JiaoWuZhang,
                                        Group_Id = backModel.Group_Id
                                    })?.FirstOrDefault();
                                    if (headmaster != null && headmaster.Id > 0)
                                    {
                                        empList.Add(headmaster.Id);
                                    }
                                }
                            }
                        }
                    }
                    //添加指定用户
                    if (!string.IsNullOrEmpty(auditRelevance.UserIds))
                    {
                        var userList = Common.ConvertHelper.StringToList(auditRelevance.UserIds);
                        foreach (var item in userList)
                        {
                            if (item > 0)
                            {
                                empList.Add(item);
                            }
                        }
                    }
                    InsertBatcheAuditRecord(empList, backModel.BackId, auditRelevance);
                }
            }
            return true;
        }

        /// <summary>
        /// 批量添加审核人
        /// </summary>
        /// <param name="empIds">审核人id集合</param>
        /// <param name="wfId">工作流id</param>
        /// <param name="wFTTemplateTypeEnum">工作流模板</param>
        /// <param name="trans">事务</param>
        /// <param name="auditRelevance">审核节点</param>
        private void InsertBatcheAuditRecord(List<int> empIds, int wfId, RB_Student_BackRelevance_ViewModel auditRelevance)
        {
            List<RB_Student_BackRecord_ViewModel> auditrecordList = new List<RB_Student_BackRecord_ViewModel>();
            foreach (var item in empIds)
            {
                RB_Student_BackRecord_ViewModel auditrecord = new RB_Student_BackRecord_ViewModel
                {
                    AuditEmId = item,
                    AuditId = auditRelevance.Id,
                    AuditStatus = WFRrocessStatus.NotAudit,
                    CreateBy = item,
                    CreateTime = DateTime.Now,
                    UpdateBy = item,
                    UpdateTime = DateTime.Now,
                    ConditionId = wfId,
                    Description = "",
                    BackrelevanceId = auditRelevance.Id
                };
                auditrecordList.Add(auditrecord);
            }
            student_BackRecordRepository.InsertBatch(auditrecordList);

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

        /// <summary>
        /// 获取退课单据信息
        /// </summary>
        /// <param name="backId"></param>
        /// <returns></returns>
        public object GetStuBackInfoModule(int backId)
        {
            var obj = new List<object>();
            //获取单据实体类
            var backModel = student_BackClassRepository.GetEntity(backId);
            //获取审核记录
            var aurList = student_BackRecordRepository.GetStudentBackRecordListRepository(new RB_Student_BackRecord_ViewModel()
            {
                ConditionId = backId,
            });
            //审核关联列表
            var arList = student_BackRelevanceRepository.GetStudentBackRelevanceListRepository(new RB_Student_BackRelevance_ViewModel()
            {
                ConditionId = backId
            });

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

            var existsList = arList.Where(qitem => aurList.Any(oldItem => qitem.Id == oldItem.BackrelevanceId));
            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="status"></param>
        /// <returns></returns>
        private string GetWFRrocessStatusStrModule(WFRrocessStatus status)
        {
            var statusName = "待审";
            switch (status)
            {
                case WFRrocessStatus.AuditNotThrough: statusName = "拒绝"; break;
                case WFRrocessStatus.AuditThrough: statusName = "通过"; break;
                case WFRrocessStatus.NotAudit: statusName = "待审"; break;
                case WFRrocessStatus.OtherHaveAudit: statusName = "通过"; break;
                case WFRrocessStatus.Rejected: statusName = "驳回"; break;
            }
            return statusName;
        }

        /// <summary>
        /// 退课一键制单
        /// </summary>
        /// <param name="backClassId"></param>
        /// <param name="IsPublic"></param>
        /// <param name="CurrencyId"></param>
        /// <param name="clientType"></param>
        /// <param name="clientId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetStudentBackFinance(int backClassId, int IsPublic, int CurrencyId, int clientType, int clientId, UserInfo userInfo)
        {
            var backModel = student_BackClassRepository.GetEntity(backClassId);
            if (backModel == null || backModel.AuditStatus != BackClassAuditStatusEnum.Pass) { return "退课流程未审核通过"; }
            if (backModel.FinanceId > 0) { return "已制单，无法再次生成财务单据"; }
            var guestModel = order_GuestRepository.GetEntity(backModel.GuestId);
            if (guestModel == null || guestModel.GuestState != 2) { return "客人名单状态不正确"; }
            var fcmodel = finance_ConfigRepository.GetList(new RB_Finance_Config_ViewModel() { Group_Id = userInfo.Group_Id, Type = FinanceConfigTypeEnum.DropCourse }).FirstOrDefault();
            if (fcmodel == null) { return "未配置制单流程"; }

            string msg = "";
            #region 新增财务单据
            var detailList = new List<object>
            {
                new
                {
                    fcmodel.CostTypeId,
                    Number = 1,
                    OriginalMoney = backModel.RealityBackMoney,
                    UnitPrice = backModel.RealityBackMoney,
                    Remark = "学员【"+guestModel.GuestName+"】退课"
                }
            };
            var classModel = classRepository.GetEntity(backModel.ClassId);
            string Remark = "【" + (classModel?.ClassName ?? "") + "】下,订单" + backModel.OrderId + " 客人退课";
            var financeObj = new
            {
                IsPublic,
                ClientType = clientType,
                ClientID = clientId,
                CurrencyId,
                WBMoney = backModel.RealityBackMoney,
                PayDate = DateTime.Now.ToString("yyyy-MM-dd"),
                TemplateId = fcmodel.TempleteId,
                OrderSource = 17,
                OrderID = backModel.OrderId,
                TCIDList = new List<int>() { backModel.ClassId },
                OtherType = 28,
                ReFinanceId = backModel.BackId,
                Remark,
                detailList,
                CreateBy = userInfo.Id,
                RB_Branch_Id = classModel.School_Id,
                RB_Depart_Id = userInfo.DeptId,
                RB_Group_Id = userInfo.Group_Id,
                RB_CreateByName = userInfo.AccountName,
                RB_DepartName = userInfo.DeptName,
                RB_BranchName = schoolRepository.GetEntity(classModel.School_Id)?.SName ?? "",
                RB_GroupName = userInfo.GroupName,
                FinanceType = 2
            };
            string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.ReadConfigKey("FinanceKey"));
            var resultInfo = new
            {
                msg = sign
            };

            string apiResult = HttpHelper.HttpPost(Config.ReadConfigKey("PaymentFinanceApi"), JsonHelper.Serialize(resultInfo), "");
            JObject parmsJob = JObject.Parse(apiResult);
            string resultCode = parmsJob.GetStringValue("resultCode");
            int frid = parmsJob.GetInt("data", 0);

            if (resultCode == "1" && frid > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Student_BackClass.FinanceId),frid}
                };
                bool flag = student_BackClassRepository.Update(keyValues, new WhereHelper(nameof(RB_Student_BackClass.BackId), backModel.BackId));
                if (flag)
                {
                    //记录日志
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 1,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = "生成学员退课财务单据【" + backModel.BackId + "】",
                        School_Id = userInfo.School_Id,
                        SourceId = 0
                    });
                }
            }
            else
            {
                string message = parmsJob.GetStringValue("message");
                LogHelper.Write("SetStudentBackFinance:" + message);
                msg += backModel.BackId + "创建财务单据失败;";
            }
            #endregion
            return msg;
        }

        /// <summary>
        /// 学员续课订单
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="guestId"></param>
        /// <param name="orderModel">订单实体类</param>
        /// <param name="message">提示信息</param>
        /// <returns></returns>
        public virtual bool RenewOrderModule(int orderId, int guestId, RB_Order_ViewModel orderModel, out string message)
        {
            bool flag = false;
            message = "";
            var oldOrderModel = orderRepository.GetEntity(orderId);
            if (oldOrderModel == null)
            {
                message = "原订单不存在!请核实在重新申请!";
                flag = false;
                return flag;
            }
            if (oldOrderModel.OrderState == OrderStateEnum.Cancel)
            {
                message = "原订单已取消!请核实在重新申请!";
                flag = false;
                return flag;
            }
            var oldGuestModel = order_GuestRepository.GetEntity(guestId);
            if (oldGuestModel == null)
            {
                message = "原旅客信息不存在!请核实在重新申请!";
                flag = false;
                return flag;
            }
            if (oldGuestModel.GuestState != 1)
            {
                message = "原旅客状态不正确!请核实在重新申请!";
                flag = false;
                return flag;
            }
            var classModel = classRepository.GetEntity(orderModel.ClassId);
            orderModel.School_Id = classModel?.School_Id ?? 0;
            orderModel.EnterID = oldOrderModel.EnterID;
            orderModel.OrderState = OrderStateEnum.Normal;
            orderModel.OrderSource = oldOrderModel.OrderSource;
            orderModel.OrderForm = oldOrderModel.OrderForm;

            //新增订单
            var newOrderId = orderRepository.Insert(orderModel);
            orderModel.OrderId = newOrderId;
            flag = newOrderId > 0;
            if (flag)
            {
                //新增旅客
                var guestModel = new RB_Order_Guest()
                {
                    OrderId = orderModel.OrderId,
                    ClassId = orderModel.ClassId,
                    GuestName = oldGuestModel.GuestName,
                    GuestState = 1,
                    Profession = oldGuestModel?.Profession ?? "",
                    Sex = oldGuestModel?.Sex ?? 1,
                    Age = oldGuestModel?.Age ?? 0,
                    Mobile = oldGuestModel?.Mobile ?? "",
                    Basics = oldGuestModel?.Basics ?? "",
                    Education = oldGuestModel?.Education ?? 0,
                    GuestSource = oldGuestModel?.GuestSource ?? 0,
                    LearningGoals = oldGuestModel?.LearningGoals ?? 0,
                    Contact = oldGuestModel?.Contact ?? "",
                    ContactMobile = oldGuestModel?.ContactMobile ?? "",
                    Status = 0,
                    Group_Id = orderModel.Group_Id,
                    School_Id = orderModel?.School_Id ?? 0,
                    CreateBy = orderModel.CreateBy,
                    CreateTime = orderModel.CreateTime,
                    UpdateBy = orderModel.UpdateBy,
                    UpdateTime = orderModel.UpdateTime,
                    DropOutRemark = "",
                };
                var newGuestId = order_GuestRepository.Insert(guestModel);
                guestModel.Id = newGuestId;
                flag = newGuestId > 0;
            }
            if (flag)
            {
                Dictionary<string, object> orderFileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Order.RenewOrderId), newOrderId}
                };
                flag = orderRepository.Update(orderFileds, new WhereHelper(nameof(RB_Order.OrderId), orderId));
            }
            return flag;
        }

        /// <summary>
        /// 获取续费课程列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<object> GetRenewClassModule(int pageIndex, int pageSize, out long rowsCount, RB_Class_ViewModel query)
        {
            List<object> list = new List<object>();
            var classList = classModule.GetClassPageListModule(pageIndex, pageSize, out rowsCount, query, isGetStepPrice: true);
            foreach (var item in classList)
            {
                var obj = new
                {
                    item.ClassId,
                    item.ClassName,
                    item.CourseName,
                    item.ClassHours,
                    item.TeacherName,
                    item.RoomName,
                    OpenTime = Common.ConvertHelper.FormatDate(item.OpenTime),
                    item.OriginalPrice,
                    item.SellPrice,
                    item.ClassPersion,
                    item.OrderStudentCount,
                    item.ClassStepPriceList,
                    item.InnerRemark
                };
                list.Add(obj);
            }
            return list;
        }
    }
}
