using Edu.Model.CacheModel;
using Edu.Model.ViewModel.Course;
using Edu.Repository.Course;
using System;
using System.Collections.Generic;
using System.Linq;
using VT.FW.DB;
using Edu.Model.Entity.EduTask;
using Edu.Repository.EduTask;
using Edu.Common.Enum.User;
using Edu.Common.Enum.Sale;
using Edu.Model.ViewModel.BackClass;
using Edu.Model.ViewModel.Sell;
using Edu.Repository.BackClass;
using Edu.Repository.Grade;
using Edu.Repository.Contract;
using Edu.Model.Entity.Contract;
using Edu.Model.Entity.Course;
using Edu.Model.ViewModel.Contract;
using Edu.Common.Enum.Course;
using Edu.Model.ViewModel.User;

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


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

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

        /// <summary>
        /// 教务单据
        /// </summary>
        private readonly RB_Education_ReceiptRepository education_ReceiptRepository = new RB_Education_ReceiptRepository();

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



        /// <summary>
        /// 创建退课流程
        /// </summary>
        /// <param name="GuestId"></param>
        /// <param name="OrderId"></param>
        /// <param name="reason"></param>
        /// <param name="userinfo"></param>
        /// <param name="receiptFile"></param>
        /// <param name="BackAccountName"></param>
        /// <param name="BackAccount"></param>
        /// <param name="StateMent">退课协议申明</param>
        /// <param name="message"></param>
        /// <returns></returns>
        public virtual bool CreateBackClassApplyModule(int GuestId, int OrderId, string reason, UserInfo userinfo, string receiptFile, string BackAccountName, string BackAccount, string StateMent, out string message)
        {
            bool flag;
            message = "";
            var guestModel = order_GuestRepository.GetEntity(GuestId);
            var orderModel = orderRepository.GetEntity(OrderId);
            if (guestModel == null)
            {
                message = "旅客信息不正确!";
                return false;
            }
            if (orderModel == null)
            {
                message = "订单信息不正确!";
                return false;
            }
            //班级实体类
            var classModel = classRepository.GetEntity(orderModel.ClassId);
            if (classModel == null)
            {
                message = "未找到对应的班级信息!";
                return false;
            }

            //获取教师实体信息
            var teacherModel = accountRepository.GetAccountListExtRepository(new Model.ViewModel.User.RB_Account_ViewModel()
            {
                AccountId = classModel.Teacher_Id,
                AccountType = Common.Enum.User.AccountTypeEnum.Teacher
            })?.FirstOrDefault();
            var teacherId = teacherModel?.Id ?? 0;
            var saleMan = accountRepository.GetAccountListExtRepository(new Model.ViewModel.User.RB_Account_ViewModel()
            {
                Id = orderModel.EnterID
            })?.FirstOrDefault();
            var totalBackCount = student_BackClassRepository.GetStudentBackClassNumRepository();
            string backNum;
            if (totalBackCount < 10000)
            {
                backNum = String.Format("{0:00000}", totalBackCount);
            }
            else
            {
                backNum = totalBackCount.ToString();
            }
            var stuCheckList = class_CheckRepository.GetGuestFinishMinutesRepository(GuestId.ToString());
            //完成课时数
            var FinishHours = stuCheckList?.Sum(qitem => qitem.FinishClassHours) ?? 0;
            var courseModel = new RB_Course();
            if (orderModel.CourseId > 0)
            {
                courseModel = courseRepository.GetEntity(orderModel.CourseId);
            }
            else
            {
                courseModel = courseRepository.GetEntity(classModel.CouseId);
            }

            //预计退款金额
            decimal backMoney = 0;

            backMoney = orderRepository.CalcBackMoneyRepository(orderModel, courseModel, FinishHours, out _);

            var backClassModel = new RB_Student_BackClass_ViewModel()
            {
                BackId = 0,
                AuditStatus = WFRrocessStatus.NotAudit,
                BackMoney = Math.Round(backMoney, 2),
                BackNum = "T" + backNum,
                ClassId = orderModel.ClassId,
                CreateBy = userinfo.Id,
                CreateTime = DateTime.Now,
                FinishHours = Convert.ToInt32(FinishHours),
                Group_Id = userinfo.Group_Id,
                GuestId = GuestId,
                SchoolId = guestModel.School_Id,
                StudentId = GuestId,
                TeacherId = teacherId,
                OrderId = OrderId,
                ApplyReason = reason,
                FlowId = Common.Config.BackClassFlowId,
                BackAccountName = BackAccountName,
                BackAccount = BackAccount,
            };
            var newBackId = student_BackClassRepository.Insert(backClassModel);
            backClassModel.BackId = newBackId;
            flag = newBackId > 0;
            if (flag)
            {
                flag = education_ReceiptRepository.SetEducationReceiptRepository(new RB_Education_Receipt()
                {
                    Id = 0,
                    Title = "退课单据",
                    ClassId = orderModel.ClassId,
                    OrderId = orderModel.OrderId,
                    ReceiptType = Common.Enum.Finance.ReceiptTypeEnum.BackClass,
                    RelationId = backClassModel.BackId,
                    Group_Id = orderModel.Group_Id,
                    School_Id = orderModel.School_Id,
                    CreateBy = userinfo.Id,
                    CreateTime = DateTime.Now,
                    UpdateBy = userinfo.Id,
                    UpdateTime = DateTime.Now,
                    RecipientIds = "",
                    VerifyStatus = Common.Enum.EduTask.EduTaskRrocessStatus.NotAudit,
                    ReceiptFile = receiptFile
                }, out message);
                if (flag)
                {
                    Dictionary<string, object> fileds = new Dictionary<string, object>()
                    {
                        {nameof(RB_Order_Guest_ViewModel.GuestState),(int)GuestStateEnum.DropOutApplyIng}
                    };
                    flag = order_GuestRepository.Update(fileds, new WhereHelper(nameof(RB_Order_Guest_ViewModel.Id), GuestId));
                }
            }
            //生成退课协议
            if (flag)
            {
                string FinaceNum = "";
                var flist = financeRepository.GetListSingle(new Model.ViewModel.Finance.RB_Finance_Extend() { RB_Group_Id = orderModel.Group_Id, FinanceType = 2, IsSelectNormal = 1, OrderIdStr = OrderId.ToString(), GuestIdStr = GuestId.ToString() });
                if (flist != null && flist.Count > 0)
                {
                    FinaceNum = string.Join(",", flist.Select(qitem => qitem.FrID));
                }
                var contractModel = education_ContractRepository.GetList(new RB_Education_Contract_ViewModel()
                {
                    OrderId = OrderId,
                    GuestId = GuestId,
                    Status = -1
                })?.FirstOrDefault();
                string ProtocolNum = (contractModel?.ContractNo ?? "") + "-T";
                RB_BackClass_Protocol model = new RB_BackClass_Protocol()
                {
                    Id = 0,
                    BackId = newBackId,
                    ProtocolNum = ProtocolNum,
                    PartyAName = guestModel.GuestName,
                    PartyAGuardian = "",
                    PartyBName = "成都市锦江区甲鹤外语培训学校有限公司",
                    PartyBLegal = "",
                    SignDate = null,
                    OldSaleMan = saleMan?.AccountName ?? "",
                    OldCourseName = courseModel?.CourseName ?? "",
                    OldSellPrice = courseModel?.SellPrice ?? 0,
                    OldDiscountMoney = orderModel?.PerDiscountMoney ?? 0,
                    OldIncome = ((orderModel?.Income ?? 0) + (orderModel?.PlatformTax ?? 0) - (orderModel?.Refund ?? 0)) / orderModel.GuestNum,
                    OldFinaceNum = FinaceNum,
                    OldReceiveMan = saleMan?.AccountName ?? "",
                    TotalClassHours = guestModel.TotalHours,
                    CompleteHours = guestModel.CompleteHours,
                    SurplusHours = guestModel.TotalHours - guestModel.CompleteHours,
                    BackMoney = backClassModel.BackMoney,
                    AuditStatus = (int)Common.Enum.EduTask.EduTaskRrocessStatus.NotAudit,
                    CreateBy = orderModel.EnterID,
                    CreateTime = DateTime.Now,
                    Group_Id = classModel.Group_Id,
                    School_Id = classModel.School_Id,
                    StateMent = StateMent
                };
                flag = backClass_ProtocolRepository.Insert(model) > 0;
            }
            return flag;
        }        

        /// <summary>
        /// 处理订单生效状态
        /// </summary>
        /// <returns></returns>
        public virtual bool DealOrderEffectStatusModule()
        {
            bool flag = false;
            var orderList = orderRepository.GetOrderListRepository(new RB_Order_ViewModel()
            {
                OrderState = Common.Enum.Course.OrderStateEnum.Normal,
                JoinType = OrderJoinTypeEnum.InsertClass,
                Q_EffectTime = Common.ConvertHelper.FormatDate(DateTime.Now)
            });
            if (orderList != null && orderList.Count > 0)
            {
                var tempOrderList = orderList.Where(qitem => qitem.EffectStatus == 0)?.ToList();
                if (tempOrderList != null && tempOrderList.Count > 0)
                {
                    foreach (var item in tempOrderList)
                    {
                        Dictionary<string, object> fileds1 = new Dictionary<string, object>()
                        {
                            { nameof(RB_Order_ViewModel.EffectStatus),1 }
                        };
                        //更新当前订单为“生效中”
                        flag = orderRepository.Update(fileds1, new WhereHelper(nameof(RB_Order_ViewModel.OrderId), item.OrderId));
                        if (item.UpOrderId > 0)
                        {
                            Dictionary<string, object> fileds2 = new Dictionary<string, object>()
                            {
                                { nameof(RB_Order_ViewModel.EffectStatus),2 }
                            };
                            //更新前置订单为“完成”
                            flag = orderRepository.Update(fileds2, new WhereHelper(nameof(RB_Order_ViewModel.OrderId), item.UpOrderId));
                        }
                    }
                }
            }
            return flag;
        }

        /// <summary>
        /// 处理学员状态
        /// </summary>
        /// <returns></returns>
        public virtual bool DealGuestStateModule()
        {
            bool flag = false;
            var guestList = order_GuestRepository.GetCommonOrderGuestListRepository(new RB_Order_Guest_ViewModel()
            {
                QFinishGuest = 1
            });
            if (guestList != null && guestList.Count > 0)
            {
                foreach (var item in guestList.Take(1))
                {
                    Dictionary<string, object> fileds = new Dictionary<string, object>()
                    {
                        { nameof(RB_Order_Guest_ViewModel.GuestState),(int)GuestStateEnum.Graduate},
                        { nameof(RB_Order_Guest_ViewModel.GraduationTime),DateTime.Now},
                    };
                    flag = order_GuestRepository.Update(fileds, new WhereHelper(nameof(RB_Order_Guest_ViewModel.Id), item.Id));
                }
            }
            return flag;
        }

        /// <summary>
        /// 获取客户转订单时客户的续费状态
        /// </summary>
        /// <param name="stuIds"></param>
        /// <param name="userInfo"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public object GetOrderGuestRenewState(string stuIds, UserInfo userInfo, out string message)
        {
            message = "";
            //查询学生列表
            var StuList = studentRepository.GetStudentListRepository(new RB_Student_ViewModel() { Group_Id = userInfo.Group_Id, StuIds = stuIds, School_Id = -1 });
            //根据客人手机号码  验证是否是续费
            if (StuList.Select(x => x.CustomerId).Distinct().Count() > 1)
            {
                message = "只能选择同一同行的客户报名";
                return false;
            }
            int CustomerId = StuList?.FirstOrDefault()?.CustomerId??0;
            var glist = student_OrderGuestRepository.GetStuOrderList(stuIds, userInfo.Group_Id);
            if (glist.Any())
            {
                foreach (var item in StuList)
                {
                    if (glist.Where(x => x.Student_Id == item.StuId).Any())
                    {
                        item.IsRenewGuest = 1;//是续费的
                    }
                }
            }
            int RenewNum = glist.Select(x => x.Student_Id).Distinct().Count();//续费订单数量

            //获取该学生的负责人
            int EnterId = 0;
            string EnterName = "";

            int SaleId = StuList?.FirstOrDefault()?.CreateBy??0;
            if (SaleId >0)
            {
                //自己负责的
                var empModel = accountRepository.GetEmployeeInfo(SaleId);
                if (empModel.UserRole == UserRoleEnum.MarketPersion)
                {
                    EnterId = empModel.Id;
                    EnterName = empModel.EmployeeName;
                }
            }
            //2021-12-24 取消
            //var empModel = accountRepository.GetEmployeeInfo(userInfo.Id);
            //if (empModel.UserRole == UserRoleEnum.MarketPersion)
            //{
            //    EnterId = empModel.Id;
            //    EnterName = empModel.EmployeeName;
            //}
            //else {
            //    int SaleId = StuList.FirstOrDefault().CreateBy;
            //    if (SaleId != userInfo.Id)
            //    {
            //        //自己负责的
            //        empModel = accountRepository.GetEmployeeInfo(SaleId);
            //        if (empModel.UserRole == UserRoleEnum.MarketPersion)
            //        {
            //            EnterId = empModel.Id;
            //            EnterName = empModel.EmployeeName;
            //        }
            //    }
            //}
            return new
            {
                CustomerId,
                RenewNum,
                StuList = StuList?.Select(x => new
                {
                    x.StuId,
                    x.StuName,
                    x.StuTel,
                    x.IsRenewGuest
                }),
                EnterId,
                EnterName
            };
        }

        /// <summary>
        /// 通过我的学生直接转订单客人
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="stuIds"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetMyStudentToGuest(int orderId, string stuIds, UserInfo userInfo)
        {
            var orderModel = orderRepository.GetEntity(orderId);
            var courseModel = courseRepository.GetEntity(orderModel.CourseId);
            //查询学生列表
            var StuList = studentRepository.GetStudentListRepository(new RB_Student_ViewModel() { Group_Id = userInfo.Group_Id, StuIds = stuIds, School_Id = -1 });
            //根据客人手机号码  验证是否是续费
            if (StuList.Select(x => x.CustomerId).Distinct().Count() > 1)
            {
                return "只能选择同一同行的学生";
            }
            if (StuList.FirstOrDefault().CustomerId != orderModel.CustomerId)
            {
                return "同业信息有误";
            }
            //验证数量
            int StuNum = StuList.Count();
            var glist = order_GuestRepository.GetSingleListRepository(new RB_Order_Guest_ViewModel() { Group_Id = userInfo.Group_Id, OrderId = orderModel.OrderId, GuestState = GuestStateEnum.Normal });
            if (glist.Count() + StuNum > orderModel.GuestNum)
            {
                return "学生选择超出" + (glist.Count() + StuNum - orderModel.GuestNum) + "位";
            }
            foreach (var item in StuList) 
            {
                if (glist.Where(x => x.Mobile == item.StuTel).Any()) {
                    return "学生" + item.StuName + "已录入学生名单中，请核实后再试";
                }
            }
            foreach (var item in StuList)
            {
                var guestModel = new RB_Order_Guest_ViewModel()
                {
                    Id = 0,
                    OrderId = orderModel.OrderId,
                    GuestName = item.StuName,
                    GuestState = GuestStateEnum.Normal,
                    Profession = item?.StuProfession ?? "",
                    Sex = (item?.StuSex ?? 1) + 1,
                    Age = item.StuBirth.HasValue ? DateTime.Now.Year - item.StuBirth.Value.Year : 18,
                    Mobile = item?.StuRealMobile ?? "",
                    Basics = "",
                    Education = item?.StuEducation ?? GuestEducationEnum.N2,
                    GuestSource = orderModel.OrderSource,
                    LearningGoals = item?.StuPurpose ?? 0,
                    Contact = item?.StuContract ?? "",
                    ContactMobile = item?.StuContractMobile ?? "",
                    Status = 0,
                    Group_Id = orderModel.Group_Id,
                    School_Id = orderModel.School_Id,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    UpdateBy = userInfo.Id,
                    UpdateTime = DateTime.Now,
                    DropOutRemark = "",
                    IDCard = item?.StuIDCard ?? "",
                    Domicile = item?.StuIDCardAddress ?? "",
                    ContactAddress = item?.StuAddress ?? "",
                    SourceId = 0,
                    GraduatedSchool = "",
                    GraduatedMajor = "",
                    VolunteerMajor = "",
                    Price = 0,
                    StudyRemark = "",
                    CompleteHours = 0,
                    MakeUpHours = 0,
                    StuIcon = item.StuIcon,
                    RenewState = 1,
                    StudentId=item?.StuId??0
                };
                if (orderModel.OrderType == OrderTypeEnum.CourseOrder)
                {
                    guestModel.ClassId = orderModel.ClassId;
                    guestModel.SourceId = 0;
                    guestModel.TotalHours = Convert.ToInt32(courseModel?.ClassHours ?? 0);
                }
                else if (orderModel.OrderType == OrderTypeEnum.StudyabroadOrder)
                {
                    guestModel.ClassId = 0;
                    guestModel.CourseId = 0;
                    guestModel.SourceId = orderModel.SourceId;
                }
                SetOrderGuestInfo(guestModel, out string Nmessage);
            }
            return "";
        }

        #region 小程序个人中心

        /// <summary>
        /// 获取学生的课时 缺课 请假信息
        /// </summary>
        /// <param name="guestId"></param>
        /// <param name="group_Id"></param>
        /// <returns></returns>
        public RB_Order_Guest_Extend GetOrderGusetHoursInfo(int guestId, int classId)
        {
            var gmodel = order_GuestRepository.GetOrderGusetHoursInfo(guestId, classId);
            return gmodel;
        }

        #endregion

        /// <summary>
        /// 验证学生是否已有其他订单
        /// </summary>
        /// <param name="stuIds"></param>
        /// <param name="group_Id"></param>
        /// <returns></returns>
        public List<RB_Student_OrderGuest_ViewModel> ValidataStuOrder(string stuIds, int group_Id)
        {
            return student_OrderGuestRepository.ValidataStuOrder(stuIds, group_Id);
        }
    }
}