using Edu.Model.CacheModel;
using Edu.Model.ViewModel.Course;
using Edu.Repository.Course;
using Edu.Repository.Flow;
using Edu.Repository.User;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Edu.Model.Entity.Course;
using VT.FW.DB;

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_Student_BackRelevanceRepository student_BackRelevanceRepository = new RB_Student_BackRelevanceRepository();

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

        /// <summary>
        /// 学员签到仓储层对象
        /// </summary>
        private readonly RB_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_FlowRepository flowRepository = new RB_FlowRepository();


        /// <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 flowModel = flowRepository.GetFlowRepository(Common.Config.BackClassFlowId);
            if (flowModel == 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 totalBackCount = student_BackClassRepository.GetStudentBackClassNumRepository();
            string backNum;
            if (totalBackCount < 10000)
            {
                backNum = String.Format("{0:00000}", totalBackCount);
            }
            else
            {
                backNum = totalBackCount.ToString();
            }
            var teacherId = teacherModel?.Id ?? 0;
            //基础课时分钟数
            var BasicMinutes = class_ConfigRepository.GetClassConfigRepository(new RB_Class_Config_ViewModel() { Group_Id = userinfo.Group_Id })?.BasicMinutes ?? 45;
            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);
            //预计退款金额
            var backMoney = (classModel.ClassHours - FinishHours) * classHourPrice;

            var backClassModel = new RB_Student_BackClass_ViewModel()
            {
                BackId = 0,
                AuditStatus = Common.Enum.Course.BackClassAuditStatusEnum.InReview,
                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;
            int index = 0;
            foreach (var item in flowModel.FlowNodeList)
            {
                if (item.FlowAduitList != null && item.FlowAduitList.Count > 0)
                {
                    string AuditedId = "";//审核人
                    foreach (var subItem in item.FlowAduitList)
                    {
                        //指定人员
                        if (subItem.AuditType ==  Common.Enum.User.WFTAuditTypeEnum.SpecifiedMember)
                        {
                            AuditedId += subItem.UserId + ",";
                        }
                        //指定角色
                        else if (subItem.AuditType ==  Common.Enum.User.WFTAuditTypeEnum.Role)
                        {
                            //本班教师审核
                            if (subItem.PostType == 1)
                            {
                                AuditedId += teacherId + ",";
                                subItem.UserId = teacherId;
                            }
                            //关联销售审核
                            else if (subItem.PostType == 2)
                            {
                                AuditedId += orderModel.EnterID + ",";
                                subItem.UserId = orderModel.EnterID;
                            }
                            //分区校长审核
                            else if (subItem.PostType == 3)
                            {
                                var headmaster = accountRepository.GetAccountListExtRepository(new Model.ViewModel.User.RB_Account_ViewModel()
                                {
                                    Post_Id = Common.Config.SchoolPostId,
                                    Group_Id = classModel.Group_Id
                                })?.FirstOrDefault();
                                AuditedId += (headmaster?.Id ?? 0) + ",";
                                subItem.UserId = (headmaster?.Id ?? 0);
                            }
                            else if (subItem.PostType == 4)
                            {
                                var headmaster = accountRepository.GetAccountListExtRepository(new Model.ViewModel.User.RB_Account_ViewModel()
                                {
                                    Post_Id = Common.Config.JiaoWuZhang,
                                    Group_Id = classModel.Group_Id
                                })?.FirstOrDefault();
                                AuditedId += (headmaster?.Id ?? 0) + ",";
                                subItem.UserId = (headmaster?.Id ?? 0);
                            }
                        }
                    }

                    var backLevance = new RB_Student_BackRelevance()
                    {
                        ConditionId = backClassModel.BackId,
                        AuditDescription = item.NodeName,
                        AuditedId = "",
                        AuditWay = item.FlowAduitList[0].AuditWay,
                        AuditType = item.FlowAduitList[0].AuditType,
                        OriginalAuditId = 0,
                        RoleOrInitiator = 0,
                        PostIds=string.Join(",",item.FlowAduitList.Where(qitem=>qitem.AuditType==Common.Enum.User.WFTAuditTypeEnum.Role).Select(qitem=>qitem.PostType)),
                        UserIds = string.Join(",", item.FlowAduitList.Where(qitem => qitem.AuditType == Common.Enum.User.WFTAuditTypeEnum.SpecifiedMember).Select(qitem => qitem.UserId)),
                        ToAuditId = AuditedId.TrimEnd(','),
                        Sort = item.SortNum,
                        SpecialNode = item.FlowAduitList[0].IsSpecNode,
                        Stauts =  Common.Enum.User.WFRrocessStatus.NotAudit,
                        WorkFlowId = Common.Config.BackClassFlowId,
                    };
                    var backLevanceId = student_BackRelevanceRepository.Insert(backLevance);
                    backLevance.Id = backLevanceId;
                    flag = backLevanceId > 0;
                    if (index == 0)
                    {
                        foreach (var subItem in item.FlowAduitList)
                        {
                            var recordModel = new RB_Student_BackRecord_ViewModel()
                            {
                                ConditionId = backClassModel.BackId,
                                AuditStatus =  Common.Enum.User.WFRrocessStatus.NotAudit,
                                AuditId = backLevance.Id,
                                AuditEmId = subItem.UserId,
                                CreateBy = userinfo.Id,
                                CreateTime = DateTime.Now,
                                UpdateBy = userinfo.Id,
                                UpdateTime = DateTime.Now,
                                Description = "",
                                BackrelevanceId = backLevance.Id,
                            };
                            flag = student_BackRecordRepository.Insert(recordModel) > 0;
                        }
                    }
                }
                index++;
            }
            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;
        }
    }
}
