
using Edu.Cache.User;
using Edu.Common;
using Edu.Common.Enum.Course;
using Edu.Common.Enum.User;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.Entity.Course;
using Edu.Model.ViewModel.Course;
using Edu.Repository.Course;
using Edu.Repository.Flow;
using Edu.Repository.Log;
using Edu.Repository.User;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VT.FW.DB;

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

 
 
        /// <summary>
        /// 旅客表仓储层对象
        /// </summary>
        private readonly RB_Order_GuestRepository order_GuestRepository = new RB_Order_GuestRepository();

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

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

        /// <summary>
        /// 学校
        /// </summary>
        private readonly RB_SchoolRepository schoolRepository = new RB_SchoolRepository();

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

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

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

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

        /// <summary>
        /// 班级处理类
        /// </summary>
        private readonly ClassModule classModule = new ClassModule();

        /// <summary>
        /// 课程优惠信息
        /// </summary>
        private readonly RB_Course_PreferentialRepository   course_PreferentialRepository = new RB_Course_PreferentialRepository();

        /// <summary>
        /// 计算学员退课金额
        /// </summary>
        /// <param name="BackId"></param>
        /// <returns></returns>
        public object GetBackBillMoneyModule(int BackId)
        {
            var backModel = student_BackClassRepository.GetEntity(BackId);
            var guestModel = order_GuestRepository.GetEntity(backModel.GuestId);
            var orderModel = orderRepository.GetEntity(backModel.OrderId);
            //班级实体类
            var classModel = classRepository.GetEntity(backModel.ClassId);
            //基础课时分钟数
            var BasicMinutes = class_ConfigRepository.GetClassMinutesRepository(backModel.ClassId);
            var stuCheckList = class_CheckRepository.GetGuestFinishMinutesRepository(backModel.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 obj = new
            {
                orderModel.PreferPrice,
                orderModel.GuestNum,
                classModel.ClassHours,
                FinishHours,
                classHourPrice,
                backMoney = Math.Round(backMoney, 2)
            };
            return obj;
        }

        /// <summary>
        /// 退课一键制单
        /// </summary>
        /// <param name="backClassId"></param>
        /// <param name="IsPublic"></param>
        /// <param name="CurrencyId"></param>
        /// <param name="clientType"></param>
        /// <param name="clientId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetStudentBackFinance(int backClassId, int IsPublic, int CurrencyId, int clientType, int clientId, UserInfo userInfo)
        {
            var backModel = student_BackClassRepository.GetEntity(backClassId);
            if (backModel == null || backModel.AuditStatus != WFRrocessStatus.AuditThrough) { return "退课流程未审核通过"; }
            if (backModel.FinanceId > 0) { return "已制单，无法再次生成财务单据"; }
            var guestModel = order_GuestRepository.GetEntity(backModel.GuestId);
            if (guestModel == null || guestModel.GuestState != 2) { return "客人名单状态不正确"; }
            var fcmodel = finance_ConfigRepository.GetList(new RB_Finance_Config_ViewModel() { Group_Id = userInfo.Group_Id, Type = FinanceConfigTypeEnum.DropCourse }).FirstOrDefault();
            if (fcmodel == null) { return "未配置制单流程"; }

            string msg = "";
            #region 新增财务单据
            var detailList = new List<object>
            {
                new
                {
                    fcmodel.CostTypeId,
                    Number = 1,
                    OriginalMoney = backModel.RealityBackMoney,
                    UnitPrice = backModel.RealityBackMoney,
                    Remark = "学员【"+guestModel.GuestName+"】退课"
                }
            };
            var classModel = classRepository.GetEntity(backModel.ClassId);
            string Remark = "【" + (classModel?.ClassName ?? "") + "】下,订单" + backModel.OrderId + " 客人退课";
            var financeObj = new
            {
                IsPublic,
                ClientType = clientType,
                ClientID = clientId,
                CurrencyId,
                WBMoney = backModel.RealityBackMoney,
                PayDate = DateTime.Now.ToString("yyyy-MM-dd"),
                TemplateId = fcmodel.TempleteId,
                OrderSource = 17,
                OrderID = backModel.OrderId,
                TCIDList = new List<int>() { backModel.ClassId },
                OtherType = 28,
                ReFinanceId = backModel.BackId,
                Remark,
                detailList,
                CreateBy = userInfo.Id,
                RB_Branch_Id = classModel.School_Id,
                RB_Depart_Id = userInfo.DeptId,
                RB_Group_Id = userInfo.Group_Id,
                RB_CreateByName = userInfo.AccountName,
                RB_DepartName = userInfo.DeptName,
                RB_BranchName = schoolRepository.GetEntity(classModel.School_Id)?.SName ?? "",
                RB_GroupName = userInfo.GroupName,
                FinanceType = 2
            };
            string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.ReadConfigKey("FinanceKey"));
            var resultInfo = new
            {
                msg = sign
            };

            string apiResult = HttpHelper.HttpPost(Config.ReadConfigKey("PaymentFinanceApi"), JsonHelper.Serialize(resultInfo), "");
            JObject parmsJob = JObject.Parse(apiResult);
            string resultCode = parmsJob.GetStringValue("resultCode");
            int frid = parmsJob.GetInt("data", 0);

            if (resultCode == "1" && frid > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Student_BackClass.FinanceId),frid}
                };
                bool flag = student_BackClassRepository.Update(keyValues, new WhereHelper(nameof(RB_Student_BackClass.BackId), backModel.BackId));
                if (flag)
                {
                    //记录日志
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 1,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = "生成学员退课财务单据【" + backModel.BackId + "】",
                        School_Id = userInfo.School_Id,
                        SourceId = 0
                    });
                }
            }
            else
            {
                string message = parmsJob.GetStringValue("message");
                LogHelper.Write("SetStudentBackFinance:" + message);
                msg += backModel.BackId + "创建财务单据失败;";
            }
            #endregion
            return msg;
        }

   
        /// <summary>
        /// 获取续费课程列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<object> GetRenewClassModule(int pageIndex, int pageSize, out long rowsCount, RB_Class_ViewModel query)
        {
            List<object> list = new List<object>();
            var classList = classModule.GetClassPageListModule(pageIndex, pageSize, out rowsCount, query, isGetStepPrice: true);
            List<RB_Course_Preferential_Extend> coursePriceList = new List<RB_Course_Preferential_Extend>();
            if (classList != null && classList.Count > 0)
            {
                string courseIds = string.Join(",", classList.Select(qitem => qitem.CouseId));
                coursePriceList= course_PreferentialRepository.GetCoursePreferentialListRepostory(new RB_Course_Preferential_Extend()
                {
                    QCourseIds = courseIds
                });
            }
            foreach (var item in classList)
            {
                var priceModel = coursePriceList?.Where(qitem => qitem.CourseId == item.CouseId && qitem.PriceDiscountType == CoursePriceDiscountEnum.Renewal)?.FirstOrDefault();
                decimal SellPrice = item.SellPrice;
                decimal OriginalPrice = item.SellPrice;
                if (priceModel != null)
                {
                    if (priceModel.PriceType == 0)
                    {
                        SellPrice = Math.Round(SellPrice * (100 - priceModel.PriceMoney) / 100,2);
                        OriginalPrice = Math.Round(SellPrice * (100 - priceModel.PriceMoney) / 100,2);
                    }
                    else
                    {
                        SellPrice = Math.Round(SellPrice - priceModel.PriceMoney,2);
                        OriginalPrice = Math.Round(SellPrice - priceModel.PriceMoney, 2);
                    }
                }
                var obj = new
                {
                    item.ClassId,
                    item.ClassName,
                    item.CouseId,
                    item.CourseName,
                    item.ClassHours,
                    item.TeacherName,
                    item.RoomName,
                    OpenTime = Common.ConvertHelper.FormatDate(item.OpenTime),
                    OriginalPrice,
                    SellPrice,
                    item.ClassPersion,
                    item.OrderStudentCount,
                    item.ClassStepPriceList,
                    item.InnerRemark
                };
                list.Add(obj);
            }
            return list;
        }
    }
}
