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;

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>
        /// <param name="GuestId"></param>
        /// <param name="OrderId"></param>
        /// <param name="reason"></param>
        /// <param name="userinfo"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public virtual bool CreateBackClassApplyModule(int GuestId, int OrderId, string reason, UserInfo userinfo, 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 totalBackCount = student_BackClassRepository.GetStudentBackClassNumRepository();
            string backNum;
            if (totalBackCount < 10000)
            {
                backNum = String.Format("{0:00000}", totalBackCount);
            }
            else
            {
                backNum = totalBackCount.ToString();
            }
       
            //基础课时分钟数
            var BasicMinutes = class_ConfigRepository.GetClassMinutesRepository(orderModel.ClassId);
            var stuCheckList = class_CheckRepository.GetGuestFinishMinutesRepository(GuestId.ToString());
            //总签到上课分钟数
            var totalFinishMinutes = stuCheckList?.Sum(qitem => qitem.FinishMinutes) ?? 0;
            //完成课时数
            var FinishHours = Convert.ToInt32(totalFinishMinutes) / BasicMinutes;

            //课时单价
            var classHourPrice = Math.Round(orderModel.PreferPrice / orderModel.GuestNum / classModel.ClassHours, 2);
            //预计退款金额
            decimal backMoney =0;
            //backMoney = (classModel.ClassHours - FinishHours) * classHourPrice;
            //违约金
            decimal breakContractPrice = (classModel.ClassHours - FinishHours) * classHourPrice * Convert.ToDecimal(0.1);
            backMoney = (orderModel.Income + orderModel.PlatformTax) - FinishHours * classHourPrice - breakContractPrice;

            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 = FinishHours,
                Group_Id = userinfo.Group_Id,
                GuestId = GuestId,
                SchoolId = guestModel.School_Id,
                StudentId = GuestId,
                TeacherId = teacherId,
                OrderId = OrderId,
                ApplyReason = reason,
                FlowId = Common.Config.BackClassFlowId,
            };
            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
                }, out message);
                if (flag)
                {
                    Dictionary<string, object> fileds = new Dictionary<string, object>()
                    {
                        {nameof(RB_Order_Guest_ViewModel.GuestState),3 }
                    };
                    flag = order_GuestRepository.Update(fileds, new WhereHelper(nameof(RB_Order_Guest_ViewModel.Id), GuestId));
                }
            }
            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,
                IsChaBan = 1,
                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;
        }
    }
}
