using Edu.AOP.CustomerAttribute;
using Edu.Common.Enum.Sale;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.Course;
using Edu.Repository.Course;
using Edu.Repository.Log;
using Edu.Repository.StudyAbroad;
using Edu.Repository.User;
using System;
using System.Collections.Generic;
using System.Linq;
using VT.FW.DB;

namespace Edu.Module.Course
{
    /// <summary>
    /// 课程报价单处理类
    /// </summary>
    public class CourseOfferModule
    {
        /// <summary>
        /// 课程报价单仓储层对象
        /// </summary>
        private readonly RB_Course_OfferRepository course_OfferRepository = new RB_Course_OfferRepository();

        /// <summary>
        /// 课程报价详情仓储层对象
        /// </summary>
        private readonly RB_Course_OfferDetailsRepository course_OfferDetailsRepository = new RB_Course_OfferDetailsRepository();

        /// <summary>
        /// 订单
        /// </summary>
        private readonly RB_OrderRepository orderRepository = new RB_OrderRepository();
        /// <summary>
        /// 订单备注
        /// </summary>
        private readonly RB_Order_RemarkRepository order_RemarkRepository = new RB_Order_RemarkRepository();
        /// <summary>
        /// 用户日志
        /// </summary>
        private readonly RB_User_ChangeLogRepository changeLogRepository = new RB_User_ChangeLogRepository();
        /// <summary>
        /// 账号
        /// </summary>
        private readonly RB_AccountRepository accountRepository = new RB_AccountRepository();

        /// 课程处理类对象
        /// </summary>
        private readonly CourseModule courseModule = new CourseModule();

        /// <summary>
        /// 留学就业仓储层对象
        /// </summary>
        private readonly RB_StudyAbroadRepository studyAbroadRepository = new RB_StudyAbroadRepository();

        /// <summary>
        /// 留学就业价格仓储层对象
        /// </summary>
        private readonly RB_StudyaBroad_PreferentialRepository studyaBroad_PreferentialRepository = new RB_StudyaBroad_PreferentialRepository();

        /// <summary>
        /// 获取报价单分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Course_Offer_ViewModel> GetCourseOfferPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Course_Offer_ViewModel query)
        {
            var list= course_OfferRepository.GetCourseOfferPageRepository(pageIndex, pageSize, out rowsCount, query);
            if (query.IsGetDetails == 1 && list != null && list.Count > 0)
            {
                //报价单编号
                string offids = string.Join(",", list.Select(qitem => qitem.Id));
                var detailsList = new List<RB_Course_OfferDetails_ViewModel>();
                if (!string.IsNullOrEmpty(offids))
                {
                      detailsList = GetCourseOfferDetailsListModule(new RB_Course_OfferDetails_ViewModel() { QOfferIds = offids });
                }
                foreach (var item in list)
                {
                    item.OfferDetails = detailsList?.Where(qitem => qitem.OfferId == item.Id)?.ToList() ?? new List<RB_Course_OfferDetails_ViewModel>();
                }
            }
            return list;
        }

        /// <summary>
        /// 获取报价单列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Course_Offer_ViewModel> GetCourseOfferListModule(RB_Course_Offer_ViewModel query)
        {
            return course_OfferRepository.GetCourseOfferListRepository(query);
        }

        /// <summary>
        /// 获取报价单详情列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Course_OfferDetails_ViewModel> GetCourseOfferDetailsListModule(RB_Course_OfferDetails_ViewModel query)
        {
            return course_OfferDetailsRepository.GetCourseOfferDetailsListRepository(query);
        }

        /// <summary>
        /// 新增修改课程报价单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetCourseOfferModule(RB_Course_Offer_ViewModel model)
        {
            bool flag = false;
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Course_Offer_ViewModel.Name),model.Name.Trim() },
                    {nameof(RB_Course_Offer_ViewModel.EffectiveStart),model.EffectiveStart },
                    {nameof(RB_Course_Offer_ViewModel.EffectiveEnd),model.EffectiveEnd },
                    {nameof(RB_Course_Offer_ViewModel.CustomerType),model.CustomerType },
                    {nameof(RB_Course_Offer_ViewModel.CustomerSource),model.CustomerSource },
                    {nameof(RB_Course_Offer_ViewModel.TotalOriginalPrice),model.TotalOriginalPrice },
                    {nameof(RB_Course_Offer_ViewModel.TotalPrice),model.TotalPrice },
                    {nameof(RB_Course_Offer_ViewModel.TotalDiscountPrice),model.TotalDiscountPrice },
                    {nameof(RB_Course_Offer_ViewModel.CustomerInfo),model.CustomerInfo },
                    {nameof(RB_Course_Offer_ViewModel.UpdateBy),model.UpdateBy },
                    {nameof(RB_Course_Offer_ViewModel.UpdateTime),model.UpdateTime },
                    {nameof(RB_Course_Offer_ViewModel.CustomerName),model.CustomerName },
                    {nameof(RB_Course_Offer_ViewModel.CustomerTel),model.CustomerTel },
                    {nameof(RB_Course_Offer_ViewModel.JoinNum),model.JoinNum },
                };
                flag = course_OfferRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Offer_ViewModel.Id), model.Id));
            }
            else
            {
                //生成报价单流水号
                model.SerialNum = course_OfferRepository.CreateSerialNumRepository();
                var newId = course_OfferRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }

            #region 报价单详情

            var oldOfferDetailsList = GetCourseOfferDetailsListModule(new RB_Course_OfferDetails_ViewModel() { OfferId = model.Id });
            //以前没有报价单信息【直接新增】
            if (oldOfferDetailsList == null || (oldOfferDetailsList != null && oldOfferDetailsList.Count == 0))
            {
                if (model.OfferDetails != null && model.OfferDetails.Count > 0)
                {
                    foreach (var item in model.OfferDetails)
                    {
                        item.OfferId = model.Id;
                        flag = course_OfferDetailsRepository.Insert(item) > 0;
                    }
                }
            }
            else//以前有报价单详情
            {
                //现在没有报价单详情【直接删除以前的报价报价单详情】
                if (model.OfferDetails == null || (model.OfferDetails != null && model.OfferDetails.Count == 0))
                {
                    course_OfferDetailsRepository.DeleteCourseOfferDetailsRepository(model.Id);
                }
                //找出差异的数据
                var deleteList = oldOfferDetailsList.Where(qitem => !model.OfferDetails.Any(oldItem => qitem.DetailsId == oldItem.DetailsId)).ToList();
                foreach (var dItem in deleteList)
                {
                    if (dItem.DetailsId > 0)
                    {
                        course_OfferDetailsRepository.Delete(dItem.DetailsId);
                    }
                }
                foreach (var offerItem in model.OfferDetails)
                {
                    offerItem.OfferId = model.Id;
                    if (offerItem.DetailsId == 0)
                    {
                        course_OfferDetailsRepository.Insert(offerItem);
                    }
                    else
                    {
                        course_OfferDetailsRepository.Update(offerItem);
                    }
                }
            }
            #endregion
            return flag;
        }

        /// <summary>
        /// 修改报价单价格
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetCourseOfferPriceModule(RB_Course_Offer_ViewModel model)
        {
            bool flag = false;
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_Offer_ViewModel.CustomerStatus) ,(int)CustomerStatusEnum.FinishModifyPrice}
            };
            flag = course_OfferRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Offer_ViewModel.Id), model.Id));
            if (flag)
            {
                foreach (var offerItem in model.OfferDetails)
                {
                    flag = course_OfferDetailsRepository.Update(offerItem);
                }
            }
            return flag;
        }


        /// <summary>
        /// 获取课程报价单实体
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Course_Offer_ViewModel GetCourseOfferModule(object Id)
        {
            var model = course_OfferRepository.GetEntity<RB_Course_Offer_ViewModel>(Id);
            if (model != null)
            {
                model.OfferDetails = GetCourseOfferDetailsListModule(new RB_Course_OfferDetails_ViewModel() { OfferId = model.Id });
                if (model.OfferDetails != null && model.OfferDetails.Count > 0)
                {
                    string ids = string.Join(",", model.OfferDetails.Select(qitem => qitem.CourseId));
                    List<RB_Course_ViewModel> courseList = new List<RB_Course_ViewModel>();
                    if (model.OfferType == OfferTypeEnum.Course)
                    {
                        if (!string.IsNullOrEmpty(ids))
                        {
                            courseList = courseModule.GetCourseListModule(new RB_Course_ViewModel()
                            {
                                IsQPrice = 1,
                                QCourseIds = ids,
                                Group_Id = model.Group_Id,
                            });
                        }
                        foreach (var item in model.OfferDetails)
                        {
                            item.SourceData = courseList?.Where(qitem => qitem.CourseId == item.CourseId)?.FirstOrDefault() ?? new RB_Course_ViewModel();
                        }
                    }
                    else if (model.OfferType == OfferTypeEnum.Studyabroad || model.OfferType == OfferTypeEnum.Employment)
                    {
                        var studyList = studyAbroadRepository.GetStudyAbroadListRepository(new Model.ViewModel.StudyAbroad.RB_StudyAbroad_ViewModel()
                        {
                            QIds = ids
                        });
                        if (studyList != null && studyList.Count > 0)
                        {
                            string studyIds = string.Join(",", studyList.Select(qitem => qitem.Id));
                            var detailsList = studyaBroad_PreferentialRepository.GetStudyaBroadPreferentialListRepostory(new Model.ViewModel.StudyAbroad.RB_StudyaBroad_Preferential_ViewModel()
                            {
                                QStudyabroadIds = studyIds
                            });

                            foreach (var item in studyList)
                            {
                                item.PreferentialList = detailsList?.Where(qitem => qitem.StudyabroadId == item.Id)?.ToList() ?? new List<Model.ViewModel.StudyAbroad.RB_StudyaBroad_Preferential_ViewModel>();
                            }
                        }
                        foreach (var item in model.OfferDetails)
                        {
                            item.SourceData = studyList?.Where(qitem => qitem.Id == item.CourseId)?.FirstOrDefault() ?? new Model.ViewModel.StudyAbroad.RB_StudyAbroad_ViewModel();
                        }
                    }
                }
            }
            return model;
        }

        /// <summary>
        /// 更新报价单删除状态
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        public bool RemoveCourseOfferModule(int Id, int Status)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_Offer_ViewModel.Status),Status },
            };
            var flag = course_OfferRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Offer_ViewModel.Id), Id));
            return flag;
        }

        /// <summary>
        /// 修改报价单客户确认状态
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="CustomerStatus"></param>
        /// <returns></returns>
        public bool SetCourseOfferCustomerStatusModule(int Id, int CustomerStatus)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_Offer_ViewModel.CustomerStatus),CustomerStatus },
            };
            var flag = course_OfferRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Offer_ViewModel.Id), Id));
            return flag;
        }

        /// <summary>
        /// 申请改价
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="ApplyReason"></param>
        /// <returns></returns>
        public bool SetApplyModifyPriceModule(int Id, string ApplyReason)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_Offer_ViewModel.CustomerStatus),(int)CustomerStatusEnum.ApplyModifyPrice },
                {nameof(RB_Course_Offer_ViewModel.ApplyReason),ApplyReason },
            };
            var flag = course_OfferRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Offer_ViewModel.Id), Id));
            return flag;
        }

        #region 报价单创建订单

        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="offerId"></param>
        /// <param name="detailList"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetOfferCreateOrder(int offerId, List<RB_Course_OfferDetails_ViewModel> detailList)
        {
            bool flag = false;
            var offerModel = GetCourseOfferModule(offerId);
            var emModel = accountRepository.GetEmployeeInfo(offerModel.CreateBy);
            string orderIds = "";
            foreach (var item in detailList)
            {
                try
                {
                    decimal uPrice = item.OriginalPrice / item.JoinNum;
                    var orderModel = new Model.Entity.Course.RB_Order()
                    {
                        ClassId = item.ClassId,
                        Class_Price = uPrice,
                        CommissionMoney = -1,
                        CreateBy = offerModel.CreateBy,
                        CreateTime = DateTime.Now,
                        Dept_Id = emModel?.Dept_Id ?? 0,
                        School_Id = emModel?.School_Id ?? 0,
                        Group_Id = emModel?.Group_Id ?? 0,
                        DirectorRemark = "",
                        DiscountMoney = item.DiscountPrice,
                        EnterID = offerModel.CreateBy,
                        ExtraDeductMoney = 0,
                        ExtraRewardMoney = 0,
                        GuestNum = item.JoinNum,
                        Income = 0,
                        IsCommissionGive = 0,
                        OrderForm = Common.Enum.Course.OrderFormEnum.Computer,
                        OrderId = 0,
                        OrderSource = Common.Enum.Course.OrderSourceEnum.Employee,
                        OrderState = Common.Enum.Course.OrderStateEnum.Normal,
                        PlatformTax = 0,
                        PreferPrice = item.OriginalPrice,
                        RectorRemark = "",
                        Refund = 0,
                        RenewOrderId = 0,
                        SaleRemark = item.Remark,
                        TeacherRemark = "",
                        TradeWay = Common.Enum.Course.TradeWayEnum.OnLine,
                        Unit_Price = uPrice,
                        UpdateBy = offerModel.CreateBy,
                        UpdateTime = DateTime.Now,
                        OfferId = offerId,
                    };
                    if (offerModel.OfferType == OfferTypeEnum.Course)
                    {
                        orderModel.OrderType = OrderTypeEnum.CourseOrder;
                        orderModel.SourceId = 0;
                    }
                    else
                    {
                        orderModel.OrderType = OrderTypeEnum.StudyabroadOrder;
                        orderModel.SourceId = item.CourseId;
                    }
                    int OrderId = orderRepository.Insert(orderModel);
                    orderModel.OrderId = OrderId;
                    flag = OrderId > 0;
                    if (flag)
                    {
                        orderIds += "," + OrderId;
                        if (!string.IsNullOrEmpty(item.Remark))
                        {
                            order_RemarkRepository.Insert(new Model.Entity.Course.RB_Order_Remark()
                            {
                                Id = 0,
                                OrderId = OrderId,
                                Type = 1,
                                Content = item.Remark,
                                CreateBy = offerModel.CreateBy,
                                CreateTime = DateTime.Now
                            });
                        }
                        changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                        {
                            Id = 0,
                            AccountType = emModel?.AccountType ?? 0,
                            Type = 2,
                            SourceId = OrderId,
                            LogContent = "由报价单自动创建订单",
                            School_Id = emModel?.School_Id ?? 0,
                            Group_Id = emModel?.Group_Id ?? 0,
                            CreateBy = offerModel.CreateBy,
                            CreateTime = DateTime.Now
                        });
                        //更新报价单详情表订单编号
                        Dictionary<string, object> offerdetailsFileds = new Dictionary<string, object>()
                        {
                          {nameof(RB_Course_OfferDetails_ViewModel.OrderId),OrderId },
                        };
                        flag= course_OfferDetailsRepository.Update(offerdetailsFileds, new WhereHelper(nameof(RB_Course_OfferDetails_ViewModel.DetailsId), item.DetailsId));
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "报价单创建订单失败，offerId:" + offerId + ",DetailsId:" + item.DetailsId + ",ClassId:" + item.ClassId);
                }
            }
            if (!string.IsNullOrEmpty(orderIds))
            {
                //更新报价单订单编号
                Dictionary<string, object> offerFileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Course_Offer_ViewModel.OrderId),orderIds[1..] },
                    {nameof(RB_Course_Offer_ViewModel.CustomerStatus),4 },
                };
                flag = course_OfferRepository.Update(offerFileds, new WhereHelper(nameof(RB_Course_Offer_ViewModel.Id), offerId));
            }
            return flag;
        }

        #endregion
    }
}
