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.ViewModel.Course;
using Edu.Model.ViewModel.User;
using Edu.Repository.Course;
using Edu.Repository.User;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
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_SchoolRepository schoolRepository = new RB_SchoolRepository();

        /// <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>
        /// <param name="OrderId"></param>
        /// <param name="GuestId"></param>
        /// <returns></returns>
        public object GetStudentInfoModule(int OrderId, int GuestId)
        {
            var obj = new object();
            var glist = order_GuestRepository.GetList(new RB_Order_Guest_ViewModel() { OrderId = OrderId, GuestState = 1 });
            var orderModel = orderRepository.GetEntity(OrderId);
            var guestModel = glist.Where(qitem=>qitem.Id==GuestId)?.FirstOrDefault();
            var classModel =new RB_Class_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 })?.FirstOrDefault();
                }
            }
            var qids = (classModel?.ManagerId ?? 0).ToString() + "," + (orderModel?.EnterID ?? 0).ToString();
            var empList= accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { QIds = qids }) ;
            if (glist != null && glist.Count > 0)
            {
                PreferPrice = orderModel.PreferPrice / glist.Count();
                DiscountMoney = orderModel.DiscountMoney / glist.Count();
                Money = (orderModel.PreferPrice - orderModel.DiscountMoney) / glist.Count();//平均每人费用
            }
            string dxMoney = StringHelper.MoneyToUpper(Money.ToString());
            obj = new
            {
                StudentName=guestModel?.GuestName??"",
                StuBirth="",
                StuSex=(guestModel?.Sex??0)==1?0:1,
                StuAddress=guestModel?.ContactAddress??"",
                StuTel= guestModel?.Mobile??"",
                StuEmail="",
                CourseName=classModel?.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=classModel?.ClassHours??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 ?? "";
                }
            }
            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},
                };
                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 })?.FirstOrDefault();
                }
                model.School_Id = classModel?.School_Id ?? 0;
                //生成合同编码
                model.ContractNo = CreateContractNumModule(model.Group_Id,model.School_Id);
                var newId = education_ContractRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 生成合同编号
        /// </summary>
        /// <param name="GroupId"></param>
        /// <returns></returns>
        public string CreateContractNumModule(int GroupId,int schoolId)
        {
            var schoolModel= schoolRepository.GetEntity(schoolId);
            string newContractNum = Common.Config.ContractDefaultTitle;
            if (schoolModel != null && schoolModel.SId > 0)
            {
                newContractNum = schoolModel?.ContractTitle ?? Common.Config.ContractDefaultTitle;
            }
            var totalCount = education_ContractRepository.GetContractCount(new RB_Education_Contract_ViewModel() { Group_Id = GroupId });
            string num = (totalCount + 1 + 18).ToString("D4");
            return newContractNum + num;
        }

        /// <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 ?? "";
            }
            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);
                }
            }
            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)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() 
            {
                { nameof(RB_Education_Contract_ViewModel.Sign),sign},
                { nameof(RB_Education_Contract_ViewModel.SignDate),DateTime.Now},
            };
            return education_ContractRepository.Update(keyValues, new WhereHelper(nameof(RB_Education_Contract_ViewModel.Id), contractId));
        }
    }
}
