using Edu.AOP.CustomerAttribute;
using Edu.Cache.User;
using Edu.Common;
using Edu.Common.API;
using Edu.Common.Enum;
using Edu.Common.Enum.Course;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.Entity.Finance;
using Edu.Model.Entity.Sell;
using Edu.Model.ViewModel.Contract;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.Finance;
using Edu.Model.ViewModel.Grade;
using Edu.Model.ViewModel.Sell;
using Edu.Model.ViewModel.User;
using Edu.Repository.BackClass;
using Edu.Repository.Contract;
using Edu.Repository.Course;
using Edu.Repository.Finance;
using Edu.Repository.Grade;
using Edu.Repository.Sell;
using Edu.Repository.User;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using VT.FW.DB;

namespace Edu.Module.Course
{
    /// <summary>
    /// 教育合同处理类
    /// </summary>
    public class EducationContractModule
    {
        /// <summary>
        /// 教育合同
        /// </summary>
        private readonly RB_Education_ContractRepository education_ContractRepository = new RB_Education_ContractRepository();

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

        /// <summary>
        /// 集团仓储对象
        /// </summary>
        private readonly RB_GroupRepository groupRepository = new RB_GroupRepository();

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

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

        /// <summary>
        /// 班级仓储层对象
        /// </summary>
        private readonly RB_ClassRepository classRepository = new RB_ClassRepository();

        /// <summary>
        /// 班级仓储层对象
        /// </summary>
        private readonly RB_Finance_OrderRecordRepository financeOrderRecordRepository = new RB_Finance_OrderRecordRepository();


        /// <summary>
        /// 班级仓储层对象
        /// </summary>
        private readonly RB_Online_Trade_DetailRepository OnlineTradeDetailRepository = new RB_Online_Trade_DetailRepository();

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

        /// <summary>
        /// 课程处理类对象
        /// </summary>
        private readonly RB_CourseRepository courseRepository = new RB_CourseRepository();

        /// <summary>
        /// 退课协议仓储层
        /// </summary>
        private readonly RB_BackClass_ProtocolRepository backClass_ProtocolRepository = new RB_BackClass_ProtocolRepository();

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

        /// <summary>
        /// 学员单据处理类
        /// </summary>
        private readonly StudentBillModule studentBillModule = new StudentBillModule();

        private readonly RB_Order_ReturnComissionRepository returnComissionRepository = new RB_Order_ReturnComissionRepository();

        private readonly RB_User_ReturnComissionRepository userReturnComissionRepository = new RB_User_ReturnComissionRepository();

        private readonly RB_Student_OrderGuestRepository student_OrderGuestRepository = new RB_Student_OrderGuestRepository();

        /// <summary>
        /// 获取学员信息
        /// </summary>
        /// <param name="OrderId"></param>
        /// <param name="GuestId"></param>
        /// <returns></returns>
        public object GetStudentInfoModule(int OrderId, int GuestId)
        {
            var obj = new object();
            var orderModel = orderRepository.GetEntity(OrderId);
            var guestModel = order_GuestRepository.GetEntity<RB_Order_Guest_ViewModel>(GuestId);
            var classModel = new RB_Class_ViewModel();
            var courseModel = new RB_Course_ViewModel();
            decimal PreferPrice = 0;//总金额
            decimal DiscountMoney = 0;//优惠金额
            decimal Money = 0;//实际金额
            if (orderModel != null && orderModel.OrderId > 0)
            {
                if (orderModel.OrderType == Common.Enum.Sale.OrderTypeEnum.CourseOrder)
                {
                    classModel = classRepository.GetClassAndCourseListRepository(new RB_Class_ViewModel() { ClassId = orderModel.ClassId, ClassScrollType = 0 })?.FirstOrDefault();
                    courseModel = courseRepository.GetEntity<RB_Course_ViewModel>(orderModel.CourseId);
                }
            }
            var qids = (classModel?.ManagerId ?? 0).ToString() + "," + (orderModel?.EnterID ?? 0).ToString();
            var empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { QIds = qids });

            PreferPrice = orderModel.PreferPrice / orderModel.GuestNum;
            DiscountMoney = orderModel.PerDiscountMoney;
            Money = (orderModel.PreferPrice - orderModel.DiscountMoney) / orderModel.GuestNum;//平均每人费用

            string dxMoney = StringHelper.MoneyToUpper(Money.ToString());
            obj = new
            {
                StudentName = guestModel?.GuestName ?? "",
                StuBirth = Common.ConvertHelper.FormatDate(guestModel?.BirthDate),
                StuSex = (guestModel?.Sex ?? 0) == 1 ? 0 : 1,
                StuAddress = guestModel?.ContactAddress ?? "",
                StuTel = guestModel?.Mobile ?? "",
                StuEmail = "",
                CourseName = courseModel?.CourseName ?? "",
                SchoolName = classModel?.SchoolName ?? "",
                SchoolPrincipal = empList?.Where(qitem => qitem.Id == (classModel?.ManagerId ?? 0))?.FirstOrDefault()?.EmployeeName ?? "",
                StartLevel = guestModel?.Basics ?? "",
                CourseConsultant = empList?.Where(qitem => qitem.Id == (orderModel?.EnterID ?? 0))?.FirstOrDefault()?.EmployeeName ?? "",
                Payee = empList?.Where(qitem => qitem.Id == (orderModel?.EnterID ?? 0))?.FirstOrDefault()?.EmployeeName ?? "",
                FirstClassHours = (courseModel?.ClassHours ?? 0)-(orderModel?.StartClassHours ?? 0),
                FirstCourseFee = PreferPrice,
                FirstBookFee = 0,
                FirstClassFee = 0,
                FirstDiscountMoney = DiscountMoney,
                FirstMoney = Money,
                CNYCaps = dxMoney,
                Money,
            };
            return obj;
        }


        /// <summary>
        /// 获取合同分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Education_Contract_ViewModel> GetEducationContractPageListModule(int pageIndex, int pageSize, out long count, RB_Education_Contract_ViewModel dmodel)
        {
            var list = education_ContractRepository.GetEducationContractPageListRepository(pageIndex, pageSize, out count, dmodel);
            if (list != null && list.Count > 0)
            {
                var userIds = string.Join(",", list.Select(x => x.CreateBy).Distinct());
                var alist = accountRepository.GetAccountListExtRepository(new Model.ViewModel.User.RB_Account_ViewModel() { QIds = userIds });
                foreach (var item in list)
                {
                    var amodel = alist.Where(x => x.Id == item.CreateBy).FirstOrDefault();
                    item.CreateByName = amodel?.AccountName ?? "";
                    item.CreateByPhoto = amodel?.UserIcon ?? "";

                    if (item.Status == 0)
                    {
                        item.SchoolStatusStr = "草稿";
                        item.AdminStatusStr = "草稿";
                    }
                    else if (item.Status == 1)
                    {
                        item.SchoolStatusStr = "待审核";
                        item.AdminStatusStr = "待审核";
                    }
                    else if (item.Status == 2)
                    {
                        item.SchoolStatusStr = "审核通过";
                        item.AdminStatusStr = "审核通过";
                    }
                    else if (item.Status == 3)
                    {
                        if (item.AuditEmpId > 0 && item.SchoolManageEmpId > 0)
                        {
                            if (item.SchoolManageAuditDate.HasValue)
                            {
                                item.SchoolStatusStr = "审核通过";
                                item.AdminStatusStr = "驳回";
                            }
                            else
                            {
                                if (item.AuditDate > item.SchoolManageAuditDate)
                                {
                                    item.SchoolStatusStr = "审核通过";
                                    item.AdminStatusStr = "驳回";
                                }
                                else
                                {
                                    item.SchoolStatusStr = "驳回";
                                    item.AdminStatusStr = "";
                                }
                            }

                        }
                        else if (item.SchoolManageEmpId > 0)
                        {
                            item.SchoolStatusStr = "驳回";
                            item.AdminStatusStr = "";
                        }
                        else
                        {
                            item.SchoolStatusStr = "";
                            item.AdminStatusStr = "驳回";
                        }
                    }
                    else if (item.Status == 4)
                    {
                        item.SchoolStatusStr = "合同已取消";
                        item.AdminStatusStr = "合同已取消";
                    }
                    else if (item.Status == 5)
                    {
                        item.SchoolStatusStr = "审核通过";
                        item.AdminStatusStr = "待审核";
                    }
                }
            }
            return list;
        }


        /// <summary>
        /// 获取合同分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Education_Contract_ViewModel> GetEducationContractPageListModule_V3(int pageIndex, int pageSize, out long count, RB_Education_Contract_ViewModel dmodel)
        {
            var list = education_ContractRepository.GetEducationContractPageListRepository(pageIndex, pageSize, out count, dmodel);
            if (list != null && list.Count > 0)
            {
                var userIds = string.Join(",", list.Select(x => x.CreateBy).Distinct());
                var alist = accountRepository.GetAccountListExtRepository(new Model.ViewModel.User.RB_Account_ViewModel() { QIds = userIds });
                foreach (var item in list)
                {
                    var amodel = alist.Where(x => x.Id == item.CreateBy).FirstOrDefault();
                    item.CreateByName = amodel?.AccountName ?? "";
                    item.CreateByPhoto = amodel?.UserIcon ?? "";
                    if (item.Status == 0)
                    {
                        item.SchoolStatusStr = "草稿";
                        item.AdminStatusStr = "草稿";
                    }
                    else if (item.Status == 1)
                    {
                        item.SchoolStatusStr = "待审核";
                        item.AdminStatusStr = "待审核";
                    }
                    else if (item.Status == 2)
                    {
                        item.SchoolStatusStr = "审核通过";
                        item.AdminStatusStr = "审核通过";
                    }
                    else if (item.Status == 3)
                    {
                        if (item.AuditEmpId > 0 && item.SchoolManageEmpId > 0)
                        {
                            if (item.SchoolManageAuditDate.HasValue)
                            {
                                item.SchoolStatusStr = "审核通过";
                                item.AdminStatusStr = "驳回";
                            }
                            else
                            {
                                if (item.AuditDate > item.SchoolManageAuditDate)
                                {
                                    item.SchoolStatusStr = "审核通过";
                                    item.AdminStatusStr = "驳回";
                                }
                                else
                                {
                                    item.SchoolStatusStr = "驳回";
                                    item.AdminStatusStr = "";
                                }
                            }

                        }
                        else if (item.SchoolManageEmpId > 0)
                        {
                            item.SchoolStatusStr = "驳回";
                            item.AdminStatusStr = "";
                        }
                        else
                        {
                            item.SchoolStatusStr = "";
                            item.AdminStatusStr = "驳回";
                        }
                    }
                    else if (item.Status == 4)
                    {
                        item.SchoolStatusStr = "合同已取消";
                        item.AdminStatusStr = "合同已取消";
                    }
                    else if (item.Status == 5)
                    {
                        item.SchoolStatusStr = "审核通过";
                        item.AdminStatusStr = "待审核";
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="demodel"></param>
        /// <param name="orderIds"></param>
        /// <returns></returns>
        public List<RB_Education_Contract_ViewModel> GetEducationContractPageList_V2(int pageIndex, int pageSize, out long rowsCount, RB_Education_Contract_ViewModel demodel)
        {
            var list = education_ContractRepository.GetEducationContractPageList_V2(pageIndex, pageSize, out rowsCount, demodel);
            if (list != null && list.Count > 0)
            {
                var userIds = string.Join(",", list.Select(x => x.CreateBy).Distinct());
                var alist = accountRepository.GetAccountListExtRepository(new Model.ViewModel.User.RB_Account_ViewModel() { QIds = userIds });
                foreach (var item in list)
                {
                    var amodel = alist.Where(x => x.Id == item.CreateBy).FirstOrDefault();
                    item.CreateByName = amodel?.AccountName ?? "";
                    item.CreateByPhoto = amodel?.UserIcon ?? "";
                    if (item.Status == 0)
                    {
                        item.SchoolStatusStr = "草稿";
                        item.AdminStatusStr = "草稿";
                    }
                    else if (item.Status == 1)
                    {
                        item.SchoolStatusStr = "待审核";
                        item.AdminStatusStr = "待审核";
                    }
                    else if (item.Status == 2)
                    {
                        item.SchoolStatusStr = "审核通过";
                        item.AdminStatusStr = "审核通过";
                    }
                    else if (item.Status == 3)
                    {
                        if (item.AuditEmpId > 0 && item.SchoolManageEmpId > 0)
                        {
                            if (item.SchoolManageAuditDate.HasValue)
                            {
                                item.SchoolStatusStr = "审核通过";
                                item.AdminStatusStr = "驳回";
                            }
                            else
                            {
                                if (item.AuditDate > item.SchoolManageAuditDate)
                                {
                                    item.SchoolStatusStr = "审核通过";
                                    item.AdminStatusStr = "驳回";
                                }
                                else
                                {
                                    item.SchoolStatusStr = "驳回";
                                    item.AdminStatusStr = "";
                                }
                            }

                        }
                        else if (item.SchoolManageEmpId > 0)
                        {
                            item.SchoolStatusStr = "驳回";
                            item.AdminStatusStr = "";
                        }
                        else
                        {
                            item.SchoolStatusStr = "";
                            item.AdminStatusStr = "驳回";
                        }
                    }
                    else if (item.Status == 4)
                    {
                        item.SchoolStatusStr = "合同已取消";
                        item.AdminStatusStr = "合同已取消";
                    }
                    else if (item.Status == 5)
                    {
                        item.SchoolStatusStr = "审核通过";
                        item.AdminStatusStr = "待审核";
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 单独新增/修改合同
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public bool SetEducationContractModule(RB_Education_Contract_ViewModel model)
        {
            bool flag;
            if (model.Id > 0)
            {
                model.CNYCaps = StringHelper.MoneyToUpper(model.Money.ToString());
                Dictionary<string, object> keyValues = new Dictionary<string, object>()
                {
                    { nameof(RB_Education_Contract_ViewModel.StudentName),model.StudentName},
                    { nameof(RB_Education_Contract_ViewModel.StuBirth),model.StuBirth},
                    { nameof(RB_Education_Contract_ViewModel.StuSex),model.StuSex},
                    { nameof(RB_Education_Contract_ViewModel.StuAddress),model.StuAddress},
                    { nameof(RB_Education_Contract_ViewModel.StuTel),model.StuTel},
                    { nameof(RB_Education_Contract_ViewModel.StuEmail),model.StuEmail},
                    { nameof(RB_Education_Contract_ViewModel.ParentName),model.ParentName},
                    { nameof(RB_Education_Contract_ViewModel.ParentRelation),model.ParentRelation},
                    { nameof(RB_Education_Contract_ViewModel.ParentTel),model.ParentTel},
                    { nameof(RB_Education_Contract_ViewModel.ParentEmail),model.ParentEmail},
                    { nameof(RB_Education_Contract_ViewModel.UrgentName),model.UrgentName},
                    { nameof(RB_Education_Contract_ViewModel.UrgentRelation),model.UrgentRelation},
                    { nameof(RB_Education_Contract_ViewModel.UrgentTel),model.UrgentTel},
                    { nameof(RB_Education_Contract_ViewModel.UrgentEmail),model.UrgentEmail},
                    { nameof(RB_Education_Contract_ViewModel.GuardianIDCard),model.GuardianIDCard},
                    { nameof(RB_Education_Contract_ViewModel.CourseName),model.CourseName},
                    { nameof(RB_Education_Contract_ViewModel.SchoolName),model.SchoolName},
                    { nameof(RB_Education_Contract_ViewModel.SchoolPrincipal),model.SchoolPrincipal},
                    { nameof(RB_Education_Contract_ViewModel.StartLevel),model.StartLevel},
                    { nameof(RB_Education_Contract_ViewModel.CourseConsultant),model.CourseConsultant},
                    { nameof(RB_Education_Contract_ViewModel.Payee),model.Payee},
                    { nameof(RB_Education_Contract_ViewModel.FirstClassHours),model.FirstClassHours},
                    { nameof(RB_Education_Contract_ViewModel.FirstCourseFee),model.FirstCourseFee},
                    { nameof(RB_Education_Contract_ViewModel.FirstBookFee),model.FirstBookFee},
                    { nameof(RB_Education_Contract_ViewModel.FirstClassFee),model.FirstClassFee},
                    { nameof(RB_Education_Contract_ViewModel.FirstDiscountMoney),model.FirstDiscountMoney},
                    { nameof(RB_Education_Contract_ViewModel.FirstMoney),model.FirstMoney},
                    { nameof(RB_Education_Contract_ViewModel.FirstPayDate),model.FirstPayDate},
                    { nameof(RB_Education_Contract_ViewModel.SecondClassHours),model.SecondClassHours},
                    { nameof(RB_Education_Contract_ViewModel.SecondCourseFee),model.SecondCourseFee},
                    { nameof(RB_Education_Contract_ViewModel.SecondBookFee),model.SecondBookFee},
                    { nameof(RB_Education_Contract_ViewModel.SecondClassFee),model.SecondClassFee},
                    { nameof(RB_Education_Contract_ViewModel.SecondDiscountMoney),model.SecondDiscountMoney},
                    { nameof(RB_Education_Contract_ViewModel.SecondMoney),model.SecondMoney},
                    { nameof(RB_Education_Contract_ViewModel.SecondPayDate),model.SecondPayDate},
                    { nameof(RB_Education_Contract_ViewModel.ThirdClassHours),model.ThirdClassHours},
                    { nameof(RB_Education_Contract_ViewModel.ThirdCourseFee),model.ThirdCourseFee},
                    { nameof(RB_Education_Contract_ViewModel.ThirdBookFee),model.ThirdBookFee},
                    { nameof(RB_Education_Contract_ViewModel.ThirdClassFee),model.ThirdClassFee},
                    { nameof(RB_Education_Contract_ViewModel.ThirdDiscountMoney),model.ThirdDiscountMoney},
                    { nameof(RB_Education_Contract_ViewModel.ThirdMoney),model.ThirdMoney},
                    { nameof(RB_Education_Contract_ViewModel.ThirdPayDate),model.ThirdPayDate},
                    { nameof(RB_Education_Contract_ViewModel.CNYCaps),model.CNYCaps},
                    { nameof(RB_Education_Contract_ViewModel.Money),model.Money},
                    { nameof(RB_Education_Contract_ViewModel.Exam),model.Exam},
                    { nameof(RB_Education_Contract_ViewModel.IsSupplement),model.IsSupplement},
                    { nameof(RB_Education_Contract_ViewModel.StuIDCard),model.StuIDCard},
                };
                flag = education_ContractRepository.Update(keyValues, new WhereHelper(nameof(RB_Education_Contract_ViewModel.Id), model.Id));
            }
            else
            {
                var orderModel = orderRepository.GetEntity(model.OrderId);
                var classModel = new RB_Class_ViewModel();
                if (orderModel != null && orderModel.ClassId > 0)
                {
                    classModel = classRepository.GetClassAndCourseListRepository(new RB_Class_ViewModel() { ClassId = orderModel.ClassId, ClassScrollType = 0 })?.FirstOrDefault();
                }
                model.School_Id = classModel?.School_Id ?? 0;
                //生成合同编码
                model.ContractNo = education_ContractRepository.CreateContractNumRepository(model.Group_Id, model.School_Id);
                model.IsSystemUse = 1;
                model.SourceContractId = 0;
                var newId = education_ContractRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }



        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="contractId"></param>
        /// <returns></returns>
        public RB_Education_Contract_ViewModel GetEducationContractModule(int contractId)
        {
            var model = education_ContractRepository.GetEntity<RB_Education_Contract_ViewModel>(contractId);
            if (model != null)
            {
                var gmodel = groupRepository.GetEntity(model.Group_Id);
                model.GroupSealImg = gmodel?.SealImage ?? "";
                if (model.OrderId > 0)
                {
                   var orderModel=  orderRepository.GetEntity(model.OrderId);
                    if (orderModel.CourseId > 0)
                    {
                        model.CourseContracrInfo = courseRepository.GetEntity(orderModel.CourseId)?.ContractInfo ?? "";
                    }
                }
            }
            return model;
        }



        /// <summary>
        /// 合同审核
        /// </summary>
        /// <param name="contractId"></param>
        /// <param name="state"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool SetEducationContractAuditModule(int contractId, int state, UserInfo userInfo)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>();
            if (state == 5)
            {
                keyValues.Add(nameof(RB_Education_Contract_ViewModel.IsCompanySeal), 1);
                keyValues.Add(nameof(RB_Education_Contract_ViewModel.SealDate), DateTime.Now);
            }
            else
            {
                keyValues.Add(nameof(RB_Education_Contract_ViewModel.Status), state);
                if (state == 1 || state == 4)
                {
                    keyValues.Add(nameof(RB_Education_Contract_ViewModel.UpdateBy), userInfo.Id);
                    keyValues.Add(nameof(RB_Education_Contract_ViewModel.UpdateTime), DateTime.Now);
                }
                else
                {
                    keyValues.Add(nameof(RB_Education_Contract_ViewModel.AuditEmpId), userInfo.Id);
                    keyValues.Add(nameof(RB_Education_Contract_ViewModel.AuditDate), DateTime.Now);
                }
            }
            #region 企业消息推送
            var model = education_ContractRepository.GetEntity(contractId);
            if (state == 1)
            {
                var notifyList = accountRepository.GetWorkUserIdByFunctionNameRepository("'EducationContractSchool','EducationContractAdmin'");
                if (notifyList != null && notifyList.Any())
                {
                    notifyList.ForEach(x =>
                    {
                        var recipientPath = HttpUtility.UrlEncode($"/sale/contractAudit?no={model.ContractNo}");
                        var content = $"合同通知 你收到了一份需要审批的合同\n>**概要信息** \n>申  领  人：<font color='comment'>{userInfo.AccountName}</font>\n>合同编号：<font color='comment'>{model.ContractNo}</font>\n>合同类型：<font color='warning'>{EnumHelper.ToName(model.CType)}合同</font> \n>订单编号：<font color='comment'>{model.OrderId}</font>\n>合同金额：<font color='info'>{model.Money:C}</font>\n>请点击：[查看合同详情]({Config.ErpUrl}/autologin?loginId={x.Id}&target={recipientPath})";
                        PushWorkChatHelper.PushToWorkChat(content, x.WorkUserId, "合同审批通知");
                    });
                }
            }
            else if (state == 2 || state == 3 || state==6)
            {
                var notifyObj = accountRepository.GetEntity(model.CreateBy);
                if (notifyObj != null && !string.IsNullOrEmpty(notifyObj.WorkUserId))
                {
                    var recipientPath = HttpUtility.UrlEncode($"/sale/contractManage?no={model.ContractNo}");
                    var content = $"{((state == 2 || state == 6) ? "<font color='info'>合同审核通过</font>" : "`合同审核驳回`")} 你收到了一份合同审批结果通知\n>**概要信息** \n>审  批  人：<font color='comment'>{userInfo.AccountName}</font>\n>合同编号：<font color='comment'>{model.ContractNo}</font>\n>合同类型：<font color='warning'>{EnumHelper.ToName(model.CType)}合同</font> \n>订单编号：<font color='comment'>{model.OrderId}</font>\n>合同金额：<font color='info'>{model.Money:C}</font>\n>请点击：[查看合同]({Config.ErpUrl}/autologin?loginId={notifyObj.Id}&target={recipientPath})";
                    PushWorkChatHelper.PushToWorkChat(content, notifyObj.WorkUserId, "合同审批通知");
                }
            }
            else if (state == 5)
            {
                var notifyObj = accountRepository.GetEntity(model.CreateBy);
                if (notifyObj != null && !string.IsNullOrEmpty(notifyObj.WorkUserId))
                {
                    var recipientPath = HttpUtility.UrlEncode($"/sale/contractManage?no={model.ContractNo}");
                    var content = $"<font color='info'>合同已盖章</font> 你收到了一份合同加盖公章通知\n>**概要信息** \n>盖  章  人：<font color='comment'>{userInfo.AccountName}</font>\n>合同编号：<font color='comment'>{model.ContractNo}</font>\n>合同类型：<font color='warning'>{EnumHelper.ToName(model.CType)}合同</font> \n>订单编号：<font color='comment'>{model.OrderId}</font>\n>合同金额：<font color='info'>{model.Money:C}</font>\n>请点击：[查看合同]({Config.ErpUrl}/autologin?loginId={notifyObj.Id}&target={recipientPath})";
                    PushWorkChatHelper.PushToWorkChat(content, notifyObj.WorkUserId, "合同审批通知");
                }
            }
            #endregion
            return education_ContractRepository.Update(keyValues, new WhereHelper(nameof(RB_Education_Contract_ViewModel.Id), contractId));
        }


        /// <summary>
        /// 合同审核
        /// </summary>
        /// <param name="contractId"></param>
        /// <param name="state"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool SetEducationContractAuditModule_V2(int contractId, int state, int type, UserInfo userInfo)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>();
            if (state == 5 && type == 2)
            {
                keyValues.Add(nameof(RB_Education_Contract_ViewModel.IsCompanySeal), 1);
                keyValues.Add(nameof(RB_Education_Contract_ViewModel.SealDate), DateTime.Now);
            }
            else
            {
                keyValues.Add(nameof(RB_Education_Contract_ViewModel.Status), (state == 6 ? 5 : state));
                if (state == 1 || state == 4)
                {
                    keyValues.Add(nameof(RB_Education_Contract_ViewModel.UpdateBy), userInfo.Id);
                    keyValues.Add(nameof(RB_Education_Contract_ViewModel.UpdateTime), DateTime.Now);
                }
                else
                {
                    if (type == 1)//学管审核
                    {
                        keyValues.Add(nameof(RB_Education_Contract_ViewModel.SchoolManageEmpId), userInfo.Id);
                        keyValues.Add(nameof(RB_Education_Contract_ViewModel.SchoolManageAuditDate), DateTime.Now);
                    }
                    else if (type == 2)//行政审核
                    {
                        keyValues.Add(nameof(RB_Education_Contract_ViewModel.AuditEmpId), userInfo.Id);
                        keyValues.Add(nameof(RB_Education_Contract_ViewModel.AuditDate), DateTime.Now);
                    }

                }
            }
            #region 企业消息推送
            var model = education_ContractRepository.GetEntity(contractId);
            if (state == 1)
            {
                var notifyList = accountRepository.GetWorkUserIdByFunctionNameRepository("'EducationContractSchool','EducationContractAdmin'");
                if (notifyList != null && notifyList.Any())
                {
                    notifyList.ForEach(x =>
                    {
                        var recipientPath = HttpUtility.UrlEncode($"/sale/contractAudit?no={model.ContractNo}");
                        var content = $"合同通知 你收到了一份需要审批的合同\n>**概要信息** \n>申  领  人：<font color='comment'>{userInfo.AccountName}</font>\n>合同编号：<font color='comment'>{model.ContractNo}</font>\n>合同类型：<font color='warning'>{EnumHelper.ToName(model.CType)}合同</font> \n>订单编号：<font color='comment'>{model.OrderId}</font>\n>合同金额：<font color='info'>{model.Money:C}</font>\n>请点击：[查看合同详情]({Config.ErpUrl}/autologin?loginId={x.Id}&target={recipientPath})";
                        PushWorkChatHelper.PushToWorkChat(content, x.WorkUserId, "合同审批通知");
                    });
                }
            }
            else if (state == 2 || state == 3 || state==6)
            {
                var notifyObj = accountRepository.GetEntity(model.CreateBy);
                if (notifyObj != null && !string.IsNullOrEmpty(notifyObj.WorkUserId))
                {
                    var recipientPath = HttpUtility.UrlEncode($"/sale/contractManage?no={model.ContractNo}");
                    var content = $"{((state == 2||state==6) ? "<font color='info'>合同审核通过</font>" : "`合同审核驳回`")} 你收到了一份合同审批结果通知\n>**概要信息** \n>审  批  人：<font color='comment'>{userInfo.AccountName}</font>\n>合同编号：<font color='comment'>{model.ContractNo}</font>\n>合同类型：<font color='warning'>{EnumHelper.ToName(model.CType)}合同</font> \n>订单编号：<font color='comment'>{model.OrderId}</font>\n>合同金额：<font color='info'>{model.Money:C}</font>\n>请点击：[查看合同]({Config.ErpUrl}/autologin?loginId={notifyObj.Id}&target={recipientPath})";
                    PushWorkChatHelper.PushToWorkChat(content, notifyObj.WorkUserId, "合同审批通知");
                }
            }
            else if (state == 5)
            {
                var notifyObj = accountRepository.GetEntity(model.CreateBy);
                if (notifyObj != null && !string.IsNullOrEmpty(notifyObj.WorkUserId))
                {
                    var recipientPath = HttpUtility.UrlEncode($"/sale/contractManage?no={model.ContractNo}");
                    var content = $"<font color='info'>合同已盖章</font> 你收到了一份合同加盖公章通知\n>**概要信息** \n>盖  章  人：<font color='comment'>{userInfo.AccountName}</font>\n>合同编号：<font color='comment'>{model.ContractNo}</font>\n>合同类型：<font color='warning'>{EnumHelper.ToName(model.CType)}合同</font> \n>订单编号：<font color='comment'>{model.OrderId}</font>\n>合同金额：<font color='info'>{model.Money:C}</font>\n>请点击：[查看合同]({Config.ErpUrl}/autologin?loginId={notifyObj.Id}&target={recipientPath})";
                    PushWorkChatHelper.PushToWorkChat(content, notifyObj.WorkUserId, "合同审批通知");
                }
            }
            #endregion
            return education_ContractRepository.Update(keyValues, new WhereHelper(nameof(RB_Education_Contract_ViewModel.Id), contractId));
        }


        /// <summary>
        /// 合同签名
        /// </summary>
        /// <param name="contractId"></param>
        /// <param name="sign"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool SetEducationContractSignModule(int contractId, string sign,string StuIDCard)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>()
            {
                { nameof(RB_Education_Contract_ViewModel.Sign),sign},
                { nameof(RB_Education_Contract_ViewModel.SignDate),DateTime.Now},
            };
            if (!string.IsNullOrEmpty(StuIDCard))
            {
                keyValues.Add(nameof(RB_Education_Contract_ViewModel.StuIDCard), StuIDCard);
            }
            var model = education_ContractRepository.GetEntity(contractId);
            var notifyObj = accountRepository.GetEntity(model.CreateBy);
            if (notifyObj != null && !string.IsNullOrEmpty(notifyObj.WorkUserId))
            {
                var recipientPath = HttpUtility.UrlEncode($"/sale/contractManage?no={model.ContractNo}");
                var content = $"<font color='info'>合同签字确认</font> 你的一份合同用户已签字确认\n>**概要信息** \n>合同编号：<font color='comment'>{model.ContractNo}</font>\n>合同类型：<font color='warning'>{EnumHelper.ToName(model.CType)}合同</font> \n>订单编号：<font color='comment'>{model.OrderId}</font>\n>合同金额：<font color='info'>{model.Money:C}</font>\n>请点击：[查看合同]({Config.ErpUrl}/autologin?loginId={notifyObj.Id}&target={recipientPath})";
                PushWorkChatHelper.PushToWorkChat(content, notifyObj.WorkUserId, "合同审批通知");
            }
            return education_ContractRepository.Update(keyValues, new WhereHelper(nameof(RB_Education_Contract_ViewModel.Id), contractId));
        }

        /// <summary>
        /// 修改学员身份证
        /// </summary>
        /// <param name="contractId">合同编号</param>
        /// <param name="StuIDCard">学员身份证</param>
        /// <returns></returns>
        public bool SetEducationContractIDCardModule(int contractId, string StuIDCard)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>()
            {
                { nameof(RB_Education_Contract_ViewModel.StuIDCard),StuIDCard},
            };
            return education_ContractRepository.Update(keyValues, new WhereHelper(nameof(RB_Education_Contract_ViewModel.Id), contractId));
        }


        #region 合同订单信息


        /// <summary>
        /// 获取财务配置列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Finance_Config_ViewModel> GetFinanceConfigList(RB_Finance_Config_ViewModel dmodel)
        {
            return finance_ConfigRepository.GetList(dmodel);
        }


        /// <summary>
        /// 新增合同的付款记录
        /// </summary>
        /// <param name="model"></param>
        /// <param name="orderRecordModel"></param>
        /// <returns></returns>
        public bool SetEducationContractFinance(RB_Online_Trade_Detail model, RB_Finance_OrderRecord orderRecordModel)
        {
            bool flag = false;
            if (orderRecordModel != null)
            {
                flag = financeOrderRecordRepository.Insert(orderRecordModel) > 0;
                if (flag && model != null && !string.IsNullOrWhiteSpace(model.Trade_Order))
                {
                    OnlineTradeDetailRepository.Insert(model);
                }
            }
            return flag;
        }


        // <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public List<RB_Finance_OrderRecord> GetOrderRecordList(RB_Finance_OrderRecord model)
        {
            return financeOrderRecordRepository.GetOrderRecordList(model);
        }
        #endregion

        /// <summary>
        /// 获取退课协议分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="query"></param>
        /// <param name="rowsCount"></param>
        /// <returns></returns>
        public List<RB_BackClass_Protocol_ViewModel> GetBackClassProtocolPageModule(int pageIndex, int pageSize, RB_BackClass_Protocol_ViewModel query, out long rowsCount)
        {
            return backClass_ProtocolRepository.GetBackClassProtocolPageRepository(pageIndex, pageSize, query, out rowsCount);
        }

        /// <summary>
        /// 获取退课协议详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_BackClass_Protocol_ViewModel GetBackClassProtocolModule(object Id)
        {
            var extModel = backClass_ProtocolRepository.GetEntity<RB_BackClass_Protocol_ViewModel>(Id);
            if (extModel == null)
            {
                extModel = new RB_BackClass_Protocol_ViewModel();
            }
            if (extModel != null && extModel.Id > 0)
            {
                var backModel = student_BackClassRepository.GetEntity(extModel.BackId);
                extModel.BackAccountName = backModel?.BackAccountName ?? "";
                extModel.BackAccount = backModel?.BackAccount ?? "";
                var gmodel = groupRepository.GetEntity(extModel.Group_Id);
                extModel.GroupSealImg = gmodel?.SealImage ?? "";
            }
            return extModel;
        }

        /// <summary>
        /// 退课协议，学员签字
        /// </summary>
        /// <param name="Id">协议编号</param>
        /// <param name="sign"></param>
        /// <returns></returns>
        public bool SetBackClassProtocolSignModule(int Id, string sign)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>()
            {
                { nameof(RB_BackClass_Protocol_ViewModel.PartyASign),sign},
                { nameof(RB_BackClass_Protocol_ViewModel.PartyASignDate),DateTime.Now},
                { nameof(RB_BackClass_Protocol_ViewModel.SignDate),DateTime.Now},
            };
            UpdateReturnMoneyStatus(Id);
            return backClass_ProtocolRepository.Update(keyValues, new WhereHelper(nameof(RB_BackClass_Protocol_ViewModel.Id), Id));
        }

        /// <summary>
        /// 追回佣金
        /// </summary>
        /// <param name="id"></param>
        private void UpdateReturnMoneyStatus(int id)
        {
            var guestModel = student_OrderGuestRepository.GetModelByBackId(id);
            var model = returnComissionRepository.GetModelByOrderIdStuId(guestModel.OrderId, guestModel.Student_Id);
            if (model != null && (model.Status==0 || model.Status==1)) 
            {
                var userModel = userReturnComissionRepository.GetModelBySourceId((int)model.OrderSourceType, model.OrderSourceId,model.CommissionType);
                userModel.SttlementMoney -= model.CommissionMoeny;
                if (model.Status == 1) 
                {
                    userModel.CanCashOutMoney -= model.CommissionMoeny;
                }
                Dictionary<string, object> userKeyValues = new Dictionary<string, object>()
                {
                    { nameof(RB_User_ReturnComission_ViewModel.SttlementMoney),userModel.SttlementMoney},
                    { nameof(RB_User_ReturnComission_ViewModel.CanCashOutMoney),userModel.CanCashOutMoney}
                };
                List<WhereHelper> userWheres = new List<WhereHelper>()
                {
                    new WhereHelper()
                    {
                        FiledName=nameof(RB_User_ReturnComission_ViewModel.UserType),
                        FiledValue=model.OrderSourceType,
                        OperatorEnum= OperatorEnum.Equal
                    },
                    new WhereHelper()
                    {
                        FiledName=nameof(RB_User_ReturnComission_ViewModel.UserId),
                        FiledValue=model.OrderSourceId,
                        OperatorEnum= OperatorEnum.Equal
                    },
                    new WhereHelper()
                    {
                        FiledName=nameof(RB_User_ReturnComission_ViewModel.CommissionType),
                        FiledValue=model.CommissionType,
                        OperatorEnum= OperatorEnum.Equal
                    }
                };
                userReturnComissionRepository.Update(userKeyValues, userWheres);

                Dictionary<string, object> keyValues = new Dictionary<string, object>()
                {
                    { nameof(RB_Order_ReturnComission.Status),-1}
                };
                List<WhereHelper> wheres = new List<WhereHelper>()
                {
                    new WhereHelper()
                    {
                        FiledName=nameof(RB_Order_ReturnComission.StuId),
                        FiledValue=guestModel.Student_Id,
                        OperatorEnum= OperatorEnum.Equal
                    },
                    new WhereHelper()
                    {
                        FiledName=nameof(RB_Order_ReturnComission.OrderId),
                        FiledValue=guestModel.OrderId,
                        OperatorEnum= OperatorEnum.Equal
                    }
                };
                returnComissionRepository.Update(keyValues, wheres);

                
            }
            
        }

        /// <summary>
        /// 退课协议，销售确认【0826新增生成财务单据】
        /// </summary>
        /// <param name="Id">协议编号</param>
        /// <param name="IsSure">是否销售确认(1-是)</param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetBackClassProtocolSureModule(int Id, int IsSure,int ClientId, UserInfo user,out string message)
        {
            bool flag = false;
            message = "";
            var extModel = backClass_ProtocolRepository.GetEntity<RB_BackClass_Protocol_ViewModel>(Id);
            if (extModel != null && extModel.Id > 0)
            {
                var backModel = student_BackClassRepository.GetEntity(extModel.BackId);
                var orderModel = orderRepository.GetEntity(backModel.OrderId);
                #region 销售退课确认，重新计算订单应收：订单应收-学员合同费用总计 （实收-应退）
                var newPreferPrice = orderModel.PreferPrice - backModel.RealityBackMoney;
                Dictionary<string, object> orderFileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Order_ViewModel.PreferPrice),newPreferPrice },
                    {nameof(RB_Order_ViewModel.OrderState),(int)OrderStateEnum.DropOut  },
                };
                flag = orderRepository.Update(orderFileds, new WhereHelper(nameof(RB_Order_ViewModel.OrderId), backModel.OrderId));
                #endregion
            }
            if (flag)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>()
                {
                    { nameof(RB_BackClass_Protocol_ViewModel.IsSure),IsSure},
                };
                flag = backClass_ProtocolRepository.Update(keyValues, new WhereHelper(nameof(RB_BackClass_Protocol_ViewModel.Id), Id));
            }
            if (flag)
            {
                message= studentBillModule.SetStudentBackFinance(Convert.ToInt32(extModel.BackId), ClientId, user);
                if (!string.IsNullOrEmpty(message))
                {
                    flag = false;
                }
            }
            return flag;
        }

        /// <summary>
        /// 根据学生id获取学生的有效合同信息
        /// </summary>
        /// <param name="teacherIds"></param>
        /// <returns></returns>
        public List<RB_Education_Contract_ViewModel> GetStudentContractInfo(int Student_Id, int Group_Id)
        {
            return education_ContractRepository.GetStudentContractInfo(Student_Id, Group_Id);
        }

        /// <summary>
        /// 根据学生id获取学生的退课合同信息
        /// </summary>
        /// <param name="teacherIds"></param>
        /// <returns></returns>
        public List<Model.ViewModel.BackClass.RB_Student_BackClass_ViewModel> GetStudentBackClassInfo(int Student_Id, int Group_Id)
        {
            return student_BackClassRepository.GetStudentBackClassInfo(Student_Id, Group_Id);
        }
        }
}