using Edu.AOP.CustomerAttribute;
using Edu.Cache.User;
using Edu.Common.API;
using Edu.Common.Enum;
using Edu.Common.Enum.Course;
using Edu.Common.Enum.Sale;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.Log;
using Edu.Model.ViewModel.User;
using Edu.Repository.Course;
using Edu.Repository.Log;
using Edu.Repository.StudyAbroad;
using Edu.Repository.User;
using System;
using System.Collections.Generic;
using System.Linq;
using VT.FW.DB;

namespace Edu.Module.Course
{
    /// <summary>
    /// 订单处理类
    /// </summary>
    public partial class OrderModule
    {
        /// <summary>
        /// 订单
        /// </summary>
        private readonly RB_OrderRepository orderRepository = new RB_OrderRepository();

        /// <summary>
        /// 订单备注
        /// </summary>
        private readonly RB_Order_RemarkRepository order_RemarkRepository = new RB_Order_RemarkRepository();

        /// <summary>
        /// 客人
        /// </summary>
        private readonly RB_Order_GuestRepository order_GuestRepository = new RB_Order_GuestRepository();

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

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

        /// <summary>
        /// 阶梯价格
        /// </summary>
        private readonly RB_Class_StepPriceRepository class_StepPriceRepository = new RB_Class_StepPriceRepository();

        /// <summary>
        /// 订单阶梯价格
        /// </summary>
        private readonly RB_Order_StepPriceRepository order_StepPriceRepository = new RB_Order_StepPriceRepository();

        /// <summary>
        /// 课程计划
        /// </summary>
        private readonly RB_Class_PlanRepository class_PlanRepository = new RB_Class_PlanRepository();

        /// <summary>
        /// 教师
        /// </summary>
        private readonly RB_TeacherRepository teacherRepository = new RB_TeacherRepository();

        /// <summary>
        /// 助教
        /// </summary>
        private readonly RB_AssistRepository assistRepository = new RB_AssistRepository();

        /// <summary>
        /// 学生
        /// </summary>
        private readonly RB_StudentRepository studentRepository = new RB_StudentRepository();

        /// <summary>
        /// 学生关联
        /// </summary>
        private readonly RB_Student_OrderGuestRepository student_OrderGuestRepository = new RB_Student_OrderGuestRepository();

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

        /// <summary>
        /// 合同
        /// </summary>
        private readonly RB_Education_ContractRepository education_ContractRepository = new RB_Education_ContractRepository();

        /// <summary>
        /// 留学就业仓储层对象
        /// </summary>
        private readonly RB_StudyAbroadRepository studyAbroadRepository = new RB_StudyAbroadRepository();

        /// <summary>
        /// 报价单仓储层对象
        /// </summary>
        private readonly RB_Course_OfferRepository course_OfferRepository = new RB_Course_OfferRepository();


        #region 日语培训

        /// <summary>
        /// 获取日语培训
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Class_ViewModel> GetClassPruductList(int pageIndex, int pageSize, out long count, RB_Class_ViewModel dmodel)
        {
            var list = classRepository.GetClassProductPageList(pageIndex, pageSize, out count, dmodel);
            if (list.Any())
            {
                string classIds = string.Join(",", list.Select(x => x.ClassId));
                //查询阶梯价格
                var stepList = class_StepPriceRepository.GetClassStepPriceListRepository(new RB_Class_StepPrice_ViewModel() { QClassIds = classIds });
                List<RB_Class_Plan_ViewModel> PlanFixed = new List<RB_Class_Plan_ViewModel>();
                string k2classIds = string.Join(",", list.Where(x => x.ClassStyle == Common.Enum.Course.ClassStyleEnum.FixedDate).Select(x => x.ClassId));
                if (!string.IsNullOrEmpty(k2classIds))
                {
                    PlanFixed = class_PlanRepository.GetClassPlanListRepository(new RB_Class_Plan_ViewModel() { QClassIds = k2classIds });
                }
                foreach (var item in list)
                {
                    item.ClassStepPriceList = stepList.Where(x => x.ClassId == item.ClassId).OrderBy(x => x.PersionNum).ToList();
                    item.ClassTimeList = new List<RB_Class_Time_ViewModel>();
                    if (item.ClassStyle != Common.Enum.Course.ClassStyleEnum.OnLine)
                    {
                        if (!string.IsNullOrEmpty(item.DefaultTimeJson))
                        {
                            item.ClassTimeList = JsonHelper.DeserializeObject<List<RB_Class_Time_ViewModel>>(item.DefaultTimeJson);
                        }
                    }
                    item.ClassPlanList = new List<RB_Class_Plan_ViewModel>();
                    if (item.ClassStyle == Common.Enum.Course.ClassStyleEnum.Week || item.ClassStyle == Common.Enum.Course.ClassStyleEnum.Month)
                    {
                        if (!string.IsNullOrEmpty(item.DateJson))
                        {
                            List<int> DayList = JsonHelper.DeserializeObject<List<int>>(item.DateJson);
                            foreach (var qitem in DayList)
                            {
                                item.ClassPlanList.Add(new RB_Class_Plan_ViewModel()
                                {
                                    WeekDay = qitem
                                });
                            }
                        }
                    }
                    else if (item.ClassStyle == Common.Enum.Course.ClassStyleEnum.FixedDate)
                    {
                        item.ClassPlanList = PlanFixed.Where(x => x.ClassId == item.ClassId).ToList();
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取班级名称
        /// </summary>
        /// <param name="classIds"></param>
        /// <returns></returns>
        public List<RB_Class_ViewModel> GetClassNameList(string classIds)
        {
            return classRepository.GetClassListRepository(new RB_Class_ViewModel() { Q_ClassIds = classIds });
        }

        /// <summary>
        /// 日语培训下单
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public bool SetClassOrder(RB_Order_ViewModel demodel, UserInfo userInfo, out string message)
        {
            bool flag = false;
            message = "";
            if (demodel.OrderId > 0)
            {
                var orderModel = orderRepository.GetEntity(demodel.OrderId);
                if (orderModel == null)
                {
                    flag = false;
                    message = "订单不存在";
                    return flag;
                }
                if (orderModel.OrderState == Common.Enum.Course.OrderStateEnum.Cancel)
                {
                    flag = false;
                    message = "取消订单无法修改";
                    return flag;
                }
                var classModel = classRepository.GetEntity(orderModel.ClassId);
                if (classModel == null)
                {
                    flag = false;
                    message = "班级不存在";
                    return flag;
                }
                int BNum = orderRepository.GetClassOrderPeopleNum(demodel.ClassId.ToString()).FirstOrDefault()?.GuestNum ?? 0;
                if (BNum + demodel.GuestNum - orderModel.GuestNum > classModel.ClassPersion)
                {
                    flag = false;
                    message = "人数报超" + (classModel.ClassPersion - (BNum + demodel.GuestNum - orderModel.GuestNum));
                    return flag;
                }
                #region 验证学生名单数量
                var glist = order_GuestRepository.GetList(new RB_Order_Guest_ViewModel() { Group_Id = demodel.Group_Id, OrderId = demodel.OrderId, GuestState = 1 });
                if (glist.Count() > demodel.GuestNum)
                {
                    flag = false;
                    message = "请先取消学生名单再修改订单人员数量";
                    return flag;
                }
                #endregion
                decimal MinPrice = orderModel.Class_Price;
                if (demodel.GuestNum > 1)
                {
                    var spList = order_StepPriceRepository.GetList(new RB_Order_StepPrice_ViewModel() { OrderId = demodel.OrderId });
                    if (spList.Any())
                    {
                        MinPrice = spList.Where(x => demodel.GuestNum >= x.PersionNum).OrderByDescending(x => x.PersionNum).FirstOrDefault().PersionPrice;
                    }
                }
                if (demodel.Unit_Price < MinPrice)
                {
                    flag = false;
                    message = "成交单价不能小于最低价格";
                    return flag;
                }
                if (demodel.PreferPrice != demodel.Unit_Price * demodel.GuestNum)
                {
                    flag = false;
                    message = "应收总额不正确";
                    return flag;
                }
                Dictionary<string, object> keyValues = new Dictionary<string, object>()
                {
                    { nameof(RB_Order_ViewModel.GuestNum),demodel.GuestNum},
                    { nameof(RB_Order_ViewModel.Unit_Price),demodel.Unit_Price},
                    { nameof(RB_Order_ViewModel.PreferPrice),demodel.PreferPrice},
                    { nameof(RB_Order_ViewModel.OrderSource),demodel.OrderSource},
                    { nameof(RB_Order_ViewModel.SaleRemark),demodel.SaleRemark}
                };
                flag = orderRepository.Update(keyValues, new WhereHelper(nameof(RB_Order_ViewModel.OrderId), demodel.OrderId));
                if (flag)
                {
                    //记录日志信息
                    string LogContent = $"修改日语培训订单【{demodel.OrderId}】";
                    if (orderModel.GuestNum != demodel.GuestNum)
                    {
                        LogContent += $"，人数由【{orderModel.GuestNum}】修改为【{demodel.GuestNum}】";
                    }
                    if (orderModel.Unit_Price != demodel.Unit_Price)
                    {
                        LogContent += $"，成交单价由【{orderModel.Unit_Price}】修改为【{demodel.Unit_Price}】";
                    }
                    if (orderModel.PreferPrice != demodel.PreferPrice)
                    {
                        LogContent += $"，应收金额由【{orderModel.PreferPrice}】修改为【{demodel.PreferPrice}】";
                    }
                    if (orderModel.OrderSource != demodel.OrderSource)
                    {
                        LogContent += $"，客人来源由【{orderModel.OrderSource.ToName()}】修改为【{demodel.OrderSource.ToName()}】";
                    }
                    //记录订单备注
                    if (orderModel.SaleRemark != demodel.SaleRemark)
                    {
                        LogContent += $"，销售备注由【{orderModel.SaleRemark}】修改为【{demodel.SaleRemark}】";
                        order_RemarkRepository.Insert(new Model.Entity.Course.RB_Order_Remark()
                        {
                            Id = 0,
                            Content = demodel.SaleRemark,
                            CreateBy = demodel.CreateBy,
                            CreateTime = DateTime.Now,
                            OrderId = demodel.OrderId,
                            Type = 1
                        });
                    }
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 2,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = LogContent,
                        School_Id = userInfo.School_Id,
                        SourceId = demodel.OrderId
                    });
                }
            }
            else
            {
                //查询班级信息
                var classModel = classRepository.GetEntity(demodel.ClassId);
                if (classModel == null)
                {
                    flag = false;
                    message = "班级不存在";
                    return flag;
                }
                if (classModel.ClassStatus != Common.Enum.Course.ClassStatusEnum.NonOpenClass)
                {
                    flag = false;
                    message = "班级状态不正确";
                    return flag;
                }
                if (classModel.EndOrderTime < Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")))
                {
                    flag = false;
                    message = "已过期，无法报名";
                    return flag;
                }
                int BNum = orderRepository.GetClassOrderPeopleNum(demodel.ClassId.ToString()).FirstOrDefault()?.GuestNum ?? 0;
                if (BNum + demodel.GuestNum > classModel.ClassPersion)
                {
                    flag = false;
                    message = "人数报超" + (classModel.ClassPersion - (BNum + demodel.GuestNum));
                    return flag;
                }
                demodel.Class_Price = classModel.SellPrice;
                decimal MinPrice = classModel.SellPrice;
                List<RB_Class_StepPrice_ViewModel> spList = new List<RB_Class_StepPrice_ViewModel>();
                if (classModel.IsStepPrice == 1)
                {
                    spList = class_StepPriceRepository.GetClassStepPriceListRepository(new RB_Class_StepPrice_ViewModel() { ClassId = demodel.ClassId });
                    if (spList.Any() && demodel.GuestNum > 1)
                    {
                        MinPrice = spList.Where(x => demodel.GuestNum >= x.PersionNum).OrderByDescending(x => x.PersionNum).FirstOrDefault().PersionPrice;
                    }
                }
                if (demodel.Unit_Price < MinPrice)
                {
                    flag = false;
                    message = "成交单价不能小于最低价格";
                    return flag;
                }
                if (demodel.PreferPrice != demodel.Unit_Price * demodel.GuestNum)
                {
                    flag = false;
                    message = "应收总额不正确";
                    return flag;
                }
                int OrderId = orderRepository.Insert(demodel);
                flag = OrderId > 0;
                if (flag)
                {
                    //记录历史阶梯价格
                    foreach (var item in spList)
                    {
                        order_StepPriceRepository.Insert(new Model.Entity.Course.RB_Order_StepPrice()
                        {
                            Id = 0,
                            Group_Id = demodel.Group_Id,
                            OrderId = OrderId,
                            PersionNum = item.PersionNum,
                            PersionPrice = item.PersionPrice,
                            School_Id = demodel.School_Id
                        });
                    }
                    //记录订单备注
                    if (!string.IsNullOrEmpty(demodel.SaleRemark))
                    {
                        order_RemarkRepository.Insert(new Model.Entity.Course.RB_Order_Remark()
                        {
                            Id = 0,
                            Content = demodel.SaleRemark,
                            CreateBy = demodel.CreateBy,
                            CreateTime = DateTime.Now,
                            OrderId = OrderId,
                            Type = 1
                        });
                    }
                    //记录日志信息
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 2,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = "新增日语培训订单",
                        School_Id = userInfo.School_Id,
                        SourceId = OrderId
                    });
                }
            }
            return flag;
        }

        /// <summary>
        /// 留学就业下单
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public bool SetStudyOrder(RB_Order_ViewModel demodel, UserInfo userInfo, out string message)
        {
            bool flag = false;
            message = "";
            if (demodel.OrderId > 0)
            {
                var orderModel = orderRepository.GetEntity(demodel.OrderId);
                if (orderModel == null)
                {
                    flag = false;
                    message = "订单不存在";
                    return flag;
                }
                if (orderModel.OrderState == Common.Enum.Course.OrderStateEnum.Cancel)
                {
                    flag = false;
                    message = "取消订单无法修改";
                    return flag;
                }
                var studyModel = studyAbroadRepository.GetEntity(orderModel.SourceId);
                if (studyModel == null)
                {
                    flag = false;
                    message = "留学就业产品不存在";
                    return flag;
                }
                if (demodel.PreferPrice != demodel.Unit_Price * demodel.GuestNum)
                {
                    flag = false;
                    message = "应收总额不正确";
                    return flag;
                }
                Dictionary<string, object> keyValues = new Dictionary<string, object>()
                {
                    { nameof(RB_Order_ViewModel.GuestNum),demodel.GuestNum},
                    { nameof(RB_Order_ViewModel.Unit_Price),demodel.Unit_Price},
                    { nameof(RB_Order_ViewModel.PreferPrice),demodel.PreferPrice},
                    { nameof(RB_Order_ViewModel.OrderSource),demodel.OrderSource},
                    { nameof(RB_Order_ViewModel.SaleRemark),demodel.SaleRemark}
                };
                flag = orderRepository.Update(keyValues, new WhereHelper(nameof(RB_Order_ViewModel.OrderId), demodel.OrderId));
                if (flag)
                {
                    //记录日志信息
                    string LogContent = $"修改留学就业订单【{demodel.OrderId}】";
                    if (orderModel.GuestNum != demodel.GuestNum)
                    {
                        LogContent += $"，人数由【{orderModel.GuestNum}】修改为【{demodel.GuestNum}】";
                    }
                    if (orderModel.Unit_Price != demodel.Unit_Price)
                    {
                        LogContent += $"，成交单价由【{orderModel.Unit_Price}】修改为【{demodel.Unit_Price}】";
                    }
                    if (orderModel.PreferPrice != demodel.PreferPrice)
                    {
                        LogContent += $"，应收金额由【{orderModel.PreferPrice}】修改为【{demodel.PreferPrice}】";
                    }
                    if (orderModel.OrderSource != demodel.OrderSource)
                    {
                        LogContent += $"，客人来源由【{orderModel.OrderSource.ToName()}】修改为【{demodel.OrderSource.ToName()}】";
                    }
                    //记录订单备注
                    if (orderModel.SaleRemark != demodel.SaleRemark)
                    {
                        LogContent += $"，销售备注由【{orderModel.SaleRemark}】修改为【{demodel.SaleRemark}】";
                        order_RemarkRepository.Insert(new Model.Entity.Course.RB_Order_Remark()
                        {
                            Id = 0,
                            Content = demodel.SaleRemark,
                            CreateBy = demodel.CreateBy,
                            CreateTime = DateTime.Now,
                            OrderId = demodel.OrderId,
                            Type = 1
                        });
                    }
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 2,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = LogContent,
                        School_Id = userInfo.School_Id,
                        SourceId = demodel.OrderId
                    });
                }
            }
            else
            {
                //查询留学就业产品
                var studyModel = studyAbroadRepository.GetEntity(demodel.SourceId);
                if (studyModel == null)
                {
                    flag = false;
                    message = "留学就业产品不存在";
                    return flag;
                }
                if (studyModel.SaleState !=  Common.Enum.Sale.SaleStateEnum.Sell)
                {
                    flag = false;
                    message = "留学就业产品不正确";
                    return flag;
                }
            
                
                demodel.Class_Price = studyModel.SellPrice;
                decimal MinPrice = studyModel.SellPrice;
                if (demodel.Unit_Price < MinPrice)
                {
                    flag = false;
                    message = "成交单价不能小于最低价格";
                    return flag;
                }
                if (demodel.PreferPrice != demodel.Unit_Price * demodel.GuestNum)
                {
                    flag = false;
                    message = "应收总额不正确";
                    return flag;
                }
                int OrderId = orderRepository.Insert(demodel);
                flag = OrderId > 0;
                if (flag)
                {
                    //记录订单备注
                    if (!string.IsNullOrEmpty(demodel.SaleRemark))
                    {
                        order_RemarkRepository.Insert(new Model.Entity.Course.RB_Order_Remark()
                        {
                            Id = 0,
                            Content = demodel.SaleRemark,
                            CreateBy = demodel.CreateBy,
                            CreateTime = DateTime.Now,
                            OrderId = OrderId,
                            Type = 1
                        });
                    }
                    //记录日志信息
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 2,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = "新增留学就业订单",
                        School_Id = userInfo.School_Id,
                        SourceId = OrderId
                    });
                }
            }
            return flag;
        }

        /// <summary>
        /// 获取订单详情
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public RB_Order_ViewModel GetClassOrderInfo(int orderId)
        {
            return orderRepository.GetEntity<RB_Order_ViewModel>(orderId);
        }

        /// <summary>
        /// 获取订单详情
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public RB_Order_ViewModel GetClassOrderInfo_V2(int orderId)
        {
            var model = orderRepository.GetEntity<RB_Order_ViewModel>(orderId);
            if (model != null)
            {
                if (model.OrderType == Common.Enum.Sale.OrderTypeEnum.CourseOrder)
                {
                    model.ClassName = classRepository.GetEntity(model.ClassId)?.ClassName ?? "";
                }
                else if(model.OrderType== Common.Enum.Sale.OrderTypeEnum.StudyabroadOrder)
                {
                    model.ClassName = studyAbroadRepository.GetEntity(model.SourceId)?.Name ?? "";
                }
            }
            return model;
        }

        /// <summary>
        /// 获取订单阶梯价格
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public List<RB_Order_StepPrice_ViewModel> GetClassOrderSetpPrice(int orderId)
        {
            return order_StepPriceRepository.GetList(new RB_Order_StepPrice_ViewModel() { OrderId = orderId });
        }

        /// <summary>
        /// 获取日志列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_User_ChangeLog_ViewModel> GetClassOrderLogList(int pageIndex, int pageSize, out long count, RB_User_ChangeLog_ViewModel dmodel)
        {
            return changeLogRepository.GetPageList(pageIndex, pageSize, out count, dmodel);
        }

        /// <summary>
        /// 转交订单
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="careOfPeople"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool SetClassOrderCareOf(int orderId, int careOfPeople, UserInfo userInfo)
        {
            var ordermodel = orderRepository.GetEntity(orderId);
            if (ordermodel == null) { return false; }
            if (ordermodel.EnterID != userInfo.Id)
            {
                return false;
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Order_ViewModel.EnterID),careOfPeople}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Order_ViewModel.OrderId),
                      FiledValue=orderId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = orderRepository.Update(keyValues, wheres);
            if (flag) {
                //记录日志信息
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 2,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = userInfo.Group_Id,
                    LogContent = $"修改【{orderId}】订单业务员，由【{UserReidsCache.GetUserLoginInfo(ordermodel.EnterID).AccountName}({ordermodel.EnterID})】修改为【{UserReidsCache.GetUserLoginInfo(careOfPeople).AccountName}({careOfPeople})】",
                    School_Id = userInfo.School_Id,
                    SourceId = orderId
                });
            }
            return flag;
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool CancelClassOrder(int orderId, UserInfo userInfo)
        {
            var orderModel = orderRepository.GetEntity(orderId);
            Dictionary<string, object> keyValues = new Dictionary<string, object>() 
            {
                { nameof(RB_Order_ViewModel.OrderState),OrderStateEnum.Cancel}
            };
            if (orderModel.OfferId > 0)
            {
                keyValues.Add(nameof(RB_Order_ViewModel.OfferId), 0);
            }
            List<WhereHelper> wheres = new List<WhereHelper>() 
            {
                new WhereHelper()
                {
                    FiledName=nameof(RB_Order_ViewModel.OrderId),
                    FiledValue=orderId,
                    OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = orderRepository.Update(keyValues, wheres);
            if (flag) 
            {
                if (orderModel.OfferId > 0)
                {
                    Dictionary<string, object> offerFileds = new Dictionary<string, object>()
                    {
                        { nameof(RB_Course_Offer_ViewModel.CustomerStatus),(int)CustomerStatusEnum.Cancel},
                        { nameof(RB_Course_Offer_ViewModel.OrderId),0},
                    };
                    flag= course_OfferRepository.Update(offerFileds, new WhereHelper(nameof(RB_Course_Offer_ViewModel.Id), orderModel.OfferId));
                }
                //记录日志信息
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 2,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = userInfo.Group_Id,
                    LogContent = $"取消日语培训订单【{orderId}】",
                    School_Id = userInfo.School_Id,
                    SourceId = orderId
                });
            }
            return flag;
        }

        #endregion

        #region 班级或留学产品订单

        /// <summary>
        /// 班级或留学产品订单
        /// </summary>
        /// <param name="classId">班级编号</param>
        /// <param name="groupId"></param>
        /// <param name="SourceId">留学就业产品编号</param>
        /// <param name="ClassInfo"></param>
        /// <returns></returns>
        public List<RB_Order_ViewModel> GetClassOrderList(int classId,int groupId,int SourceId,out object ClassInfo)
        {
            ClassInfo = new { };
            //获取订单列表
            var orderList = new List<RB_Order_ViewModel>();
            if (classId > 0)
            {
                var cModel = classRepository.GetEntity(classId);
                if (cModel == null)
                {
                    return new List<RB_Order_ViewModel>();
                }
                //获取班级教师
                var tModel = teacherRepository.GetEntity(cModel.Teacher_Id);
                var zModel = assistRepository.GetEntity(cModel.Assist_Id);
                ClassInfo = new
                {
                    cModel.ClassName,
                    tModel?.TeacherName,
                    tModel?.TeacherIcon,
                    zModel?.AssistName,
                    zModel?.AssistIcon
                };
            }
            else if(SourceId>0)
            {
                var studyModel = studyAbroadRepository.GetEntity(SourceId);
                if (studyModel != null && studyModel.Id > 0)
                {
                    ClassInfo = new
                    {
                       StudyName=studyModel.Name,
                    };
                }
            }
            //获取订单列表
            orderList = orderRepository.GetList(new RB_Order_ViewModel() { Group_Id = groupId, ClassId = classId,SourceId=SourceId });
            if (orderList.Any())
            {
                string orderIds = string.Join(",", orderList.Select(x => x.OrderId));
                //获取备注列表
                var remarkList = order_RemarkRepository.GetList(new RB_Order_Remark_ViewModel() { }, orderIds);
                //获取名单列表
                var guestList = order_GuestRepository.GetList(new RB_Order_Guest_ViewModel() { OrderIds = orderIds });
                //获取合同列表
                var clist = education_ContractRepository.GetList(new RB_Education_Contract_ViewModel() { Group_Id = groupId, OrderIds = orderIds, Status = -1 }).Where(x => x.Status != 4).ToList();
                foreach (var item in orderList) {
                    item.SaleRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 1).ToList();
                    item.TeacherRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 2).ToList();
                    item.RectorRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 3).ToList();
                    item.DirectorRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 4).ToList();
                    item.GuestList = guestList.Where(x => x.OrderId == item.OrderId).ToList();
                    item.ContractList = clist.Where(x => x.OrderId == item.OrderId).ToList();
                    var ZList = item.GuestList.Where(x => !item.ContractList.Select(z => z.GuestId).Contains(x.Id)).ToList();
                    if (ZList.Any() && item.ContractList.Any())
                    {
                        foreach (var qitem in ZList)
                        {
                            item.ContractList.Add(new RB_Education_Contract_ViewModel()
                            {
                                Id = 0,
                                StudentName = qitem.GuestName,
                                ContractNo = "",
                                GuestId = qitem.Id,
                                Status = 0
                            });
                        }
                    }
                }
            }
            return orderList;
        }

        /// <summary>
        /// 设置订单使用最新的班级价格
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public bool SetClassOrderUseNewClassPrice(int orderId)
        {
            var demodel = orderRepository.GetEntity(orderId);
            //查询班级信息
            var classModel = classRepository.GetEntity(demodel.ClassId);
            if (classModel == null)
            {
                return false;
            }
            List<RB_Class_StepPrice_ViewModel> spList = new List<RB_Class_StepPrice_ViewModel>();
            if (classModel.IsStepPrice == 1)
            {
                spList = class_StepPriceRepository.GetClassStepPriceListRepository(new RB_Class_StepPrice_ViewModel() { ClassId = demodel.ClassId });
            }
            return true;
        }

        /// <summary>
        /// 更新订单销售
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="enterID"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string UpdateOrderSale(int orderId, int enterID, UserInfo userInfo)
        {
            var orderModel = orderRepository.GetEntity(orderId);
            if (orderModel == null) { return "订单不存在，请核实后再试"; }
            if (orderModel.EnterID == enterID)
            {
                return "不能转交给同一人";
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Order_ViewModel.EnterID),enterID}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Order_ViewModel.OrderId),
                      FiledValue=orderId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = orderRepository.Update(keyValues, wheres);
            if (flag) {
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 2,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = userInfo.Group_Id,
                    LogContent = "修改销售，由" + (UserReidsCache.GetUserLoginInfo(orderModel.EnterID)?.AccountName ?? "") + "(" + orderModel.EnterID + ") 修改为" + (UserReidsCache.GetUserLoginInfo(enterID)?.AccountName ?? "") + "(" + enterID + ")",
                    School_Id = userInfo.School_Id,
                    SourceId = orderId
                });
            }
            return flag ? "" : "操作失败，请联系管理员";
        }        

        /// <summary>
        /// 获取订单备注列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Order_Remark_ViewModel> GetClassOrderRemarkList(int pageIndex, int pageSize, out long count, RB_Order_Remark_ViewModel dmodel)
        {
            return order_RemarkRepository.GetPageList(pageIndex, pageSize, out count, dmodel, "");
        }

        /// <summary>
        /// 修改备注
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="type"></param>
        /// <param name="remark"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool UpdateOrderRemark(int orderId, int type, string remark, UserInfo userInfo)
        {
            var orderModel = orderRepository.GetEntity(orderId);
            if (orderModel == null) { return false; }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
            string LogContent;
            if (type == 2)
            {
                if (orderModel.TeacherRemark == remark) { return true; }
                keyValues.Add(nameof(RB_Order_ViewModel.TeacherRemark), remark);
                LogContent = "修改教务备注：由【" + orderModel.TeacherRemark + "】修改为【" + remark + "】";
            }
            else if (type == 3)
            {
                if (orderModel.RectorRemark == remark) { return true; }
                keyValues.Add(nameof(RB_Order_ViewModel.RectorRemark), remark);
                LogContent = "修改校长备注：由【" + orderModel.RectorRemark + "】修改为【" + remark + "】";
            }
            else if (type == 4)
            {
                if (orderModel.DirectorRemark == remark) { return true; }
                keyValues.Add(nameof(RB_Order_ViewModel.DirectorRemark), remark);
                LogContent = "修改经理备注：由【" + orderModel.DirectorRemark + "】修改为【" + remark + "】";
            }
            else if (type == 1) {
                if (orderModel.SaleRemark == remark) { return true; }
                keyValues.Add(nameof(RB_Order_ViewModel.SaleRemark), remark);
                LogContent = "修改销售备注：由【" + orderModel.SaleRemark + "】修改为【" + remark + "】";
            }
            else { return false; }
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Order_ViewModel.OrderId),
                      FiledValue=orderId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            var flag = orderRepository.Update(keyValues, wheres);
            if (flag)
            {
                if (type == 1) {
                    order_RemarkRepository.Insert(new Model.Entity.Course.RB_Order_Remark()
                    {
                        Id = 0,
                        OrderId = orderId,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Content = remark,
                        Type = 1
                    });
                }
                else if (type == 2)
                {
                    order_RemarkRepository.Insert(new Model.Entity.Course.RB_Order_Remark()
                    {
                        Id = 0,
                        OrderId = orderId,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Content = remark,
                        Type = 2
                    });
                }
                else if (type == 3)
                {
                    order_RemarkRepository.Insert(new Model.Entity.Course.RB_Order_Remark()
                    {
                        Id = 0,
                        OrderId = orderId,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Content = remark,
                        Type = 3
                    });
                }
                else if (type == 4) {
                    order_RemarkRepository.Insert(new Model.Entity.Course.RB_Order_Remark()
                    {
                        Id = 0,
                        OrderId = orderId,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Content = remark,
                        Type = 4
                    });
                }
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 2,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = userInfo.Group_Id,
                    LogContent = LogContent,
                    School_Id = userInfo.School_Id,
                    SourceId = orderId
                });
            }
            return flag;
        }

        /// <summary>
        /// 修改提成
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="type"></param>
        /// <param name="commissionMoney"></param>
        /// <param name="extraRewardMoney"></param>
        /// <param name="extraDeductMoney"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool UpdateOrderCommission(int orderId, int type, decimal commissionMoney, decimal extraRewardMoney, decimal extraDeductMoney, UserInfo userInfo)
        {
            var orderModel = orderRepository.GetEntity(orderId);
            if (orderModel == null) { return false; }
            if (type == 1)
            {
                if (orderModel.IsCommissionGive != 1)
                {
                    return false;
                }
                if (orderModel.CommissionMoney == commissionMoney) { return true; }
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Order_ViewModel.CommissionMoney),commissionMoney}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                     new WhereHelper(){
                         FiledName=nameof(RB_Order_ViewModel.OrderId),
                          FiledValue=orderId,
                           OperatorEnum=OperatorEnum.Equal
                     }
                };
                var flag = orderRepository.Update(keyValues, wheres);
                if (flag)
                {
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 2,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = "修改提成，由【" + orderModel.CommissionMoney + "】修改为【" + commissionMoney + "】",
                        School_Id = userInfo.School_Id,
                        SourceId = orderId
                    });
                }
                return flag;
            }
            else {
                if (orderModel.ExtraRewardMoney != extraRewardMoney || orderModel.ExtraDeductMoney != extraDeductMoney)
                {
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Order_ViewModel.ExtraRewardMoney),extraRewardMoney},
                        { nameof(RB_Order_ViewModel.ExtraDeductMoney),extraDeductMoney}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                         new WhereHelper(){
                             FiledName=nameof(RB_Order_ViewModel.OrderId),
                              FiledValue=orderId,
                               OperatorEnum=OperatorEnum.Equal
                         }
                    };
                    var flag = orderRepository.Update(keyValues, wheres);
                    if (flag)
                    {
                        string LogContent = "修改额外金额";
                        if (orderModel.ExtraRewardMoney != extraRewardMoney)
                        {
                            LogContent += "，额外奖励由【" + orderModel.ExtraRewardMoney + "】修改为【" + extraRewardMoney + "】";
                        }
                        if (orderModel.ExtraDeductMoney != extraDeductMoney)
                        {
                            LogContent += "，额外扣除由【" + orderModel.ExtraDeductMoney + "】修改为【" + extraDeductMoney + "】";
                        }
                        changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                        {
                            Id = 0,
                            Type = 2,
                            CreateBy = userInfo.Id,
                            CreateTime = DateTime.Now,
                            Group_Id = userInfo.Group_Id,
                            LogContent = LogContent,
                            School_Id = userInfo.School_Id,
                            SourceId = orderId
                        });
                    }
                    return flag;
                }
                else {
                    return true;
                }
            }
        }

        /// <summary>
        /// 订单转班
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="classId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetClassOrderCareOfClass(int orderId, int classId, UserInfo userInfo)
        {
            var orderModel = orderRepository.GetEntity(orderId);
            if (orderModel == null) { return "订单不存在"; }
            if (orderModel.OrderState == OrderStateEnum.Cancel) { return "订单状态不正确"; }
            if (orderModel.ClassId == classId) { return "转入班级不正确"; }
            var classModel = classRepository.GetEntity(classId);
            if (classModel == null) { return "班级不存在"; }
            //获取该班级下订单人数
            int BNum = orderRepository.GetClassOrderPeopleNum(classId.ToString()).FirstOrDefault()?.GuestNum ?? 0;
            if (BNum + orderModel.GuestNum > classModel.ClassPersion)
            {
                return "转入班级剩余招收人数不足，请核实后再试";
            }

            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Order_ViewModel.ClassId),classId}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Order_ViewModel.OrderId),
                      FiledValue=orderId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = orderRepository.Update(keyValues, wheres);
            if (flag)
            {
                //查询所有的学生名单
                var glist = order_GuestRepository.GetList(new RB_Order_Guest_ViewModel() { OrderId = orderId });
                foreach (var item in glist) {
                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                        { nameof(RB_Order_Guest_ViewModel.ClassId),classId}
                    };
                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Order_Guest_ViewModel.Id),
                              FiledValue=item.Id,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    order_GuestRepository.Update(keyValues1, wheres1);
                }
                //记录日志
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 2,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = userInfo.Group_Id,
                    LogContent = $"订单转班，由【{orderModel.ClassId}】转移至【{classId}】",
                    School_Id = userInfo.School_Id,
                    SourceId = orderId
                });
                return "";
            }
            else {
                return "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 设置订单应收金额
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="preferPrice"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool SetOrderPreferPrice(int orderId, decimal preferPrice, UserInfo userInfo)
        {
            var orderModel = orderRepository.GetEntity(orderId);
            if (orderModel == null) { return false; }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Order_ViewModel.PreferPrice),preferPrice}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                        FiledName=nameof(RB_Order_ViewModel.OrderId),
                        FiledValue=orderId,
                        OperatorEnum=OperatorEnum.Equal
                    }
            };
            var flag = orderRepository.Update(keyValues, wheres);
            if (flag)
            {
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 2,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = userInfo.Group_Id,
                    LogContent = "修改订单应收总额，由【" + orderModel.PreferPrice + "】修改为【" + preferPrice + "】",
                    School_Id = userInfo.School_Id,
                    SourceId = orderId
                });
            }
            return flag;
        }

        /// <summary>
        /// 获取班级订单列表
        /// </summary>
        /// <param name="classId"></param>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public List<RB_Order_ViewModel> GetClassOrderList_V2(int classId, int groupId,int SourceId)
        {
            //获取订单列表
            var orderList = orderRepository.GetList(new RB_Order_ViewModel() { Group_Id = groupId, ClassId = classId,SourceId=SourceId });
            return orderList;
        }

        #endregion

        #region 学生名单
        /// <summary>
        /// 获取学生名单列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Order_Guest_ViewModel> GetOrderGuestPageList(int pageIndex, int pageSize, out long count, RB_Order_Guest_ViewModel dmodel)
        {
            var list = order_GuestRepository.GetPageList(pageIndex, pageSize, out count, dmodel);
            return list;
        }

        /// <summary>
        /// 新增修改 学生
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetOrderGuestInfo(RB_Order_Guest_ViewModel dmodel,out string message)
        {
            bool flag = false;
            message = "";
            if (dmodel.Id > 0)
            {
                var gModel = order_GuestRepository.GetEntity(dmodel.Id);
                string LogContent = "修改学生名单【" + dmodel.Id + "】";
                if (gModel.Age != dmodel.Age)
                {
                    LogContent += "，年龄由【" + gModel.Age + "】修改为【" + dmodel.Age + "】";
                }
                gModel.Age = dmodel.Age;
          
                if (gModel.Basics != dmodel.Basics)
                {
                    LogContent += "，日语基础由【" + gModel.Basics + "】修改为【" + dmodel.Basics + "】";
                }
                gModel.Basics = dmodel.Basics;
                
                if (gModel.Contact != dmodel.Contact)
                {
                    LogContent += "，紧急联系人由【" + gModel.Contact + "】修改为【" + dmodel.Contact + "】";
                }
                gModel.Contact = dmodel.Contact;

                if (gModel.ContactMobile != dmodel.ContactMobile)
                {
                    LogContent += "，紧急联系电话由【" + gModel.ContactMobile + "】修改为【" + dmodel.ContactMobile + "】";
                }
                gModel.ContactMobile = dmodel.ContactMobile;

                if (gModel.Education != dmodel.Education)
                {
                    LogContent += "，学历由【" + gModel.Education.ToName() + "】修改为【" + dmodel.Education.ToName() + "】";
                }
                gModel.Education = dmodel.Education;

                if (gModel.GuestName != dmodel.GuestName)
                {
                    LogContent += "，客人名称由【" + gModel.GuestName + "】修改为【" + dmodel.GuestName + "】";
                }
                gModel.GuestName = dmodel.GuestName;

                if (gModel.GuestSource != dmodel.GuestSource)
                {
                    LogContent += "，客人来源由【" + gModel.GuestSource.ToName() + "】修改为【" + dmodel.GuestSource.ToName() + "】";
                }
                gModel.GuestSource = dmodel.GuestSource;

                if (gModel.LearningGoals != dmodel.LearningGoals)
                {
                    LogContent += "，学习目的由【" + gModel.LearningGoals.ToName() + "】修改为【" + dmodel.LearningGoals.ToName() + "】";
                }
                gModel.LearningGoals = dmodel.LearningGoals;
            
                if (gModel.Mobile != dmodel.Mobile)
                {
                    LogContent += "，手机号码由【" + gModel.Mobile + "】修改为【" + dmodel.Mobile + "】";
                }
                gModel.Mobile = dmodel.Mobile;
         
                if (gModel.Profession != dmodel.Profession)
                {
                    LogContent += "，职业由【" + gModel.Profession + "】修改为【" + dmodel.Profession + "】";
                }
                gModel.Profession = dmodel.Profession;
                
                if (gModel.Sex != dmodel.Sex)
                {
                    LogContent += "，性别由【" + gModel.Sex + "】修改为【" + dmodel.Sex + "】";
                }
                gModel.Sex = dmodel.Sex;
               
                if (gModel.IDCard != dmodel.IDCard)
                {
                    LogContent += "，身份证由【" + gModel.IDCard + "】修改为【" + dmodel.IDCard + "】";
                }
                gModel.IDCard = dmodel.IDCard;
               
                if (gModel.Domicile != dmodel.Domicile)
                {
                    LogContent += "，身份证居住地由【" + gModel.Domicile + "】修改为【" + dmodel.Domicile + "】";
                }
                gModel.Domicile = dmodel.Domicile;
            
                if (gModel.ContactAddress != dmodel.ContactAddress)
                {
                    LogContent += "，联系地址由【" + gModel.ContactAddress + "】修改为【" + dmodel.ContactAddress + "】";
                }
                gModel.ContactAddress = dmodel.ContactAddress;

                if (gModel.GraduatedSchool != dmodel.GraduatedSchool)
                {
                    LogContent += "，毕业院校由【" + gModel.GraduatedSchool + "】修改为【" + dmodel.GraduatedSchool + "】";
                }
                gModel.GraduatedSchool = dmodel.GraduatedSchool;

                if (gModel.GraduatedMajor != dmodel.GraduatedMajor)
                {
                    LogContent += "，毕业专业由【" + gModel.GraduatedMajor + "】修改为【" + dmodel.GraduatedMajor + "】";
                }
                gModel.GraduatedMajor = dmodel.GraduatedMajor;

                if (gModel.VolunteerMajor != dmodel.VolunteerMajor)
                {
                    LogContent += "，志愿专业由【" + gModel.VolunteerMajor + "】修改为【" + dmodel.VolunteerMajor + "】";
                }
                gModel.VolunteerMajor = dmodel.VolunteerMajor;

                if (gModel.Price != dmodel.Price)
                {
                    LogContent += "，价格由【" + gModel.Price + "】修改为【" + dmodel.Price + "】";
                }
                gModel.Price = dmodel.Price;

                if (gModel.StudyRemark != dmodel.StudyRemark)
                {
                    LogContent += "，备注由【" + gModel.StudyRemark + "】修改为【" + dmodel.StudyRemark + "】";
                }
                gModel.StudyRemark = dmodel.StudyRemark;

                gModel.UpdateTime = dmodel.UpdateTime;
                flag = order_GuestRepository.Update(gModel);
                if (flag)
                {
                    //记录日志
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 2,
                        CreateBy = dmodel.CreateBy,
                        CreateTime = DateTime.Now,
                        Group_Id = dmodel.Group_Id,
                        LogContent = LogContent,
                        School_Id = dmodel.School_Id,
                        SourceId = gModel.OrderId
                    });
                }
            }
            else
            {
                var ordermodel = orderRepository.GetEntity(dmodel.OrderId);
                if (ordermodel == null)
                {
                    message= "订单不存在";
                    return flag;
                }
                dmodel.ClassId = ordermodel.ClassId;
                dmodel.SourceId = ordermodel.SourceId;
                int GuestNum = order_GuestRepository.GetGuestNum(new RB_Order_Guest_ViewModel() { OrderId = dmodel.OrderId, GuestState = 1 });
                if (GuestNum >= ordermodel.GuestNum)
                {
                    message = "学生名单已录入完毕";
                    return flag;
                }
                int Id = order_GuestRepository.Insert(dmodel);
                flag = Id > 0;
                if (flag)
                {
                    var classmodel = classRepository.GetEntity(ordermodel.ClassId);
                    //验证账号是否存在
                    var accmodel = accountRepository.GetAccountListRepository(new RB_Account_ViewModel() { Group_Id = dmodel.Group_Id, AccountType = Common.Enum.User.AccountTypeEnum.Student, Account = dmodel.Mobile }).FirstOrDefault();
                    string LogContent = "新增学生名单【" + Id + "】";
                    if (dmodel.ClassId > 0)
                    {
                        if (accmodel != null)
                        {
                            student_OrderGuestRepository.Insert(new Model.Entity.User.RB_Student_OrderGuest()
                            {
                                Id = 0,
                                Account_Id = accmodel.Id,
                                ClassId = ordermodel.ClassId,
                                CreateBy = dmodel.CreateBy,
                                CreateTime = DateTime.Now,
                                GuestId = Id,
                                OrderId = dmodel.OrderId,
                                Status = DateStateEnum.Normal,
                                Student_Id = accmodel.AccountId
                            });
                            LogContent += ",添加学生账号关联【" + accmodel.Id + "】";
                        }
                        else
                        {
                            //创建学生账号
                            int StudentId = studentRepository.Insert(new Model.Entity.User.RB_Student()
                            {
                                StuId = 0,
                                AreaId = 0,
                                CityId = 0,
                                CreateBy = dmodel.CreateBy,
                                CreateTime = DateTime.Now,
                                Group_Id = dmodel.Group_Id,
                                IsDisable = 1,
                                ProviceId = 0,
                                School_Id = classmodel.School_Id,
                                Status = DateStateEnum.Normal,
                                StuBirth = null,
                                StuIcon = "",
                                StuName = dmodel.GuestName,
                                StuSex = dmodel.Sex - 1,
                                StuTel = dmodel.Mobile,
                                UpdateBy = dmodel.CreateBy,
                                UpdateTime = DateTime.Now
                            });
                            int AccountId = accountRepository.Insert(new Model.Entity.User.RB_Account()
                            {
                                Id = 0,
                                Account = dmodel.Mobile,
                                AccountId = StudentId,
                                AccountType = Common.Enum.User.AccountTypeEnum.Student,
                                AnnualLeaveDay = 0,
                                CreateBy = dmodel.CreateBy,
                                CreateTime = DateTime.Now,
                                Group_Id = dmodel.Group_Id,
                                School_Id = classmodel.School_Id,
                                Status = DateStateEnum.Normal,
                                UpdateBy = dmodel.UpdateBy,
                                UpdateTime = DateTime.Now,
                                Password = Common.DES.Encrypt(Common.Config.DefaultPwd)
                            });
                            student_OrderGuestRepository.Insert(new Model.Entity.User.RB_Student_OrderGuest()
                            {
                                Id = 0,
                                Account_Id = AccountId,
                                ClassId = ordermodel.ClassId,
                                CreateBy = dmodel.CreateBy,
                                CreateTime = DateTime.Now,
                                GuestId = Id,
                                OrderId = dmodel.OrderId,
                                Status = DateStateEnum.Normal,
                                Student_Id = StudentId
                            });
                            LogContent += ",自动创建学生账号【" + AccountId + "】";
                        }
                    }
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 2,
                        CreateBy = dmodel.CreateBy,
                        CreateTime = DateTime.Now,
                        Group_Id = dmodel.Group_Id,
                        LogContent = LogContent,
                        School_Id = dmodel.School_Id,
                        SourceId = dmodel.OrderId
                    });
                }
            }
            return flag;
        }

        /// <summary>
        /// 删除学生名单
        /// </summary>
        /// <param name="guestId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool DelOrderGuestInfo(int guestId, UserInfo userInfo)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Order_Guest_ViewModel.Status),1}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Order_Guest_ViewModel.Id),
                      FiledValue=guestId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = order_GuestRepository.Update(keyValues, wheres);
            if (flag)
            {
                var gmodel = order_GuestRepository.GetEntity(guestId);
                //查询学生账号
                //var sModel = student_OrderGuestRepository.GetStrOrderGuestListRepository(new RB_Student_OrderGuest_ViewModel() { OrderId = gmodel?.OrderId ?? 0, GuestId = guestId }).FirstOrDefault();
                //if (sModel != null) {
                //    //更新账号表 
                //    Dictionary<string, object> valuePairs = new Dictionary<string, object>() {
                //        { nameof(RB_Account_ViewModel.Status),DateStateEnum.Delete}
                //    };
                //    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                //        new WhereHelper(){
                //             FiledName=nameof(RB_Account_ViewModel.Id),
                //              FiledValue=sModel.Account_Id,
                //               OperatorEnum=OperatorEnum.Equal
                //        }
                //    };
                //    accountRepository.Update(valuePairs, wheres1);
                //}
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 2,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = userInfo.Group_Id,
                    LogContent = "删除学生名单【" + guestId + "】",
                    School_Id = userInfo.Id,
                    SourceId = gmodel?.OrderId ?? 0
                });
            }
            return flag;
        }

        #endregion

        #region 销售中心
        /// <summary>
        /// 获取我的订单列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Order_ViewModel> GetMyOrderPageList(int pageIndex, int pageSize, out long count, RB_Order_ViewModel demodel)
        {
            //获取订单列表
            var orderList = orderRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (orderList.Any())
            {
                string orderIds = string.Join(",", orderList.Select(x => x.OrderId));
                //获取备注列表
                var remarkList = order_RemarkRepository.GetList(new RB_Order_Remark_ViewModel() { }, orderIds);
                //获取名单列表
                var guestList = order_GuestRepository.GetList(new RB_Order_Guest_ViewModel() { OrderIds = orderIds });
                //获取合同列表
                var clist = education_ContractRepository.GetList(new RB_Education_Contract_ViewModel() { Group_Id = demodel.Group_Id, OrderIds = orderIds, Status = -1 }).Where(x => x.Status != 4).ToList();
                foreach (var item in orderList)
                {
                    item.SaleRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 1).ToList();
                    item.TeacherRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 2).ToList();
                    item.RectorRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 3).ToList();
                    item.DirectorRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 4).ToList();
                    item.GuestList = guestList.Where(x => x.OrderId == item.OrderId).ToList();
                    item.ContractList = clist.Where(x => x.OrderId == item.OrderId).ToList();
                    if (item.GuestList != null && item.GuestList.Count > 0)
                    {
                        foreach (var subItem in item.GuestList)
                        {
                            var contractModel = clist.Where(x => x.OrderId == item.OrderId && x.GuestId == subItem.Id)?.FirstOrDefault();
                            subItem.ContractId = contractModel?.Id ?? 0;
                            subItem.ContractNo = contractModel?.ContractNo ?? "";
                            subItem.ContractStatus = contractModel?.Status ?? -1;
                            string ContractStatusStr = "";
                            if (subItem.ContractStatus == 0)
                            {
                                ContractStatusStr = "草稿";
                            }
                            else if (subItem.ContractStatus == 1)
                            {
                                ContractStatusStr = "提交审核";
                            }
                            else if (subItem.ContractStatus == 2)
                            {
                                ContractStatusStr = "审核通过";
                            }
                            else if (subItem.ContractStatus == 3)
                            {
                                ContractStatusStr = "驳回";
                            }
                            else if (subItem.ContractStatus == 4)
                            {
                                ContractStatusStr = "取消";
                            }
                            subItem.ContractStatusStr = ContractStatusStr;
                        }
                    }
                }
            }
            return orderList;
        }

        /// <summary>
        /// 获取留学就业订单分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Order_ViewModel> GetStudyOrderPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Order_ViewModel demodel)
        {
            //获取订单列表
            var orderList = orderRepository.GetStudyOrderPageListRepository(pageIndex, pageSize, out rowsCount, demodel);
            if (orderList.Any())
            {
                string orderIds = string.Join(",", orderList.Select(x => x.OrderId));
                //获取备注列表
                var remarkList = order_RemarkRepository.GetList(new RB_Order_Remark_ViewModel() { }, orderIds);
                //获取名单列表
                var guestList = order_GuestRepository.GetList(new RB_Order_Guest_ViewModel() { OrderIds = orderIds });
                //获取合同列表
                var clist = education_ContractRepository.GetList(new RB_Education_Contract_ViewModel() { Group_Id = demodel.Group_Id, OrderIds = orderIds, Status = -1 }).Where(x => x.Status != 4).ToList();
                foreach (var item in orderList)
                {
                    item.SaleRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 1).ToList();
                    item.TeacherRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 2).ToList();
                    item.RectorRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 3).ToList();
                    item.DirectorRemarkList = remarkList.Where(x => x.OrderId == item.OrderId && x.Type == 4).ToList();
                    item.GuestList = guestList.Where(x => x.OrderId == item.OrderId).ToList();
                    item.ContractList = clist.Where(x => x.OrderId == item.OrderId).ToList();
                    var ZList = item.GuestList.Where(x => !item.ContractList.Select(z => z.GuestId).Contains(x.Id)).ToList();
                    if (ZList.Any() && item.ContractList.Any()) {
                        foreach(var qitem in ZList) {
                            item.ContractList.Add(new RB_Education_Contract_ViewModel()
                            {
                                Id = 0,
                                StudentName = qitem.GuestName,
                                ContractNo = "",
                                GuestId = qitem.Id,
                                Status = 0
                            });
                        }
                    }
                }
            }
            return orderList;
        }

        /// <summary>
        /// 获取我的留学就业订单统计
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public RB_Order_ViewModel GetStudyOrderStatisticsModule(RB_Order_ViewModel demodel)
        {
            return orderRepository.GetStudyOrderStatisticsRepository(demodel);
        }

        /// <summary>
        /// 获取我的订单统计
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public RB_Order_ViewModel GetMyOrderStatistics(RB_Order_ViewModel demodel)
        {
            return orderRepository.GetMyOrderStatistics(demodel);
        }
        #endregion

        #region 订单操作
        /// <summary>
        /// 财务 更新订单实收，退款
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="income"></param>
        /// <param name="platformTax"></param>
        /// <param name="refund"></param>
        /// <param name="empModel"></param>
        /// <returns></returns>
        public bool UpdateEduOrderIncome(int orderId, decimal income, decimal platformTax, decimal refund, Employee_ViewModel empModel)
        {
            var orderModel = orderRepository.GetEntity(orderId);
            if (orderModel == null) { return false; }
            if (orderModel.Income == income && orderModel.Refund == refund) { return true; }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
            string LogContent;
            if (income >= 0)
            {
                keyValues.Add(nameof(RB_Order_ViewModel.Income), income);
                keyValues.Add(nameof(RB_Order_ViewModel.PlatformTax), platformTax);
                LogContent = $"，更新订单实收【{income}】平台税金【{platformTax}】";
            }
            else if (refund >= 0)
            {
                keyValues.Add(nameof(RB_Order_ViewModel.Refund), refund);
                LogContent = $"，更新退款【{refund}】";
            }
            else { return false; }
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Order_ViewModel.OrderId),
                      FiledValue=orderId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = orderRepository.Update(keyValues, wheres);
            if (flag) {
                //写入日志
                changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                {
                    Id = 0,
                    Type = 2,
                    CreateBy = empModel.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = empModel.Group_Id,
                    LogContent = $"【{empModel.EmployeeName}({empModel.Id})】单据审核通过{LogContent}",
                    School_Id = empModel.School_Id,
                    SourceId = orderId
                });
            }
            return flag;
        }
        #endregion
    }
}
