using Edu.AOP.CustomerAttribute;
using Edu.Common.Enum;
using Edu.Common.Enum.System;
using Edu.Common.Enum.User;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.ViewModel.Customer;
using Edu.Model.ViewModel.Mall;
using Edu.Model.ViewModel.User;
using Edu.Repository.Customer;
using Edu.Repository.Mall;
using Edu.Repository.Reserve;
using Edu.Repository.System;
using Edu.Repository.User;
using System;
using System.Collections.Generic;
using System.Linq;
using VT.FW.DB;

namespace Edu.Module.User
{
    /// <summary>
    /// 学生统计处理类
    /// </summary>
    public class StudentStatModule
    {
        /// <summary>
        /// 学生仓储层对象
        /// </summary>
        private readonly RB_StudentRepository studentRepository = new RB_StudentRepository();
        /// <summary>
        /// 学员订单关联表仓储层
        /// </summary>
        private readonly RB_Student_OrderGuestRepository student_OrderGuestRepository = new RB_Student_OrderGuestRepository();
        /// <summary>
        /// 学员跟进
        /// </summary>
        private readonly RB_Student_FollowRepository followRepository = new RB_Student_FollowRepository();
        /// <summary>
        /// 学员续费介绍
        /// </summary>
        private readonly RB_Student_RenewOrderRepository student_RenewOrderRepository = new RB_Student_RenewOrderRepository();
        /// <summary>
        /// 服务人员
        /// </summary>
        private readonly RB_Student_AssistRepository student_AssistRepository = new RB_Student_AssistRepository();
        /// <summary>
        /// 账户
        /// </summary>
        private readonly RB_AccountRepository accountRepository = new RB_AccountRepository();
        /// <summary>
        /// 同业
        /// </summary>
        private readonly RB_CustomerRepository customerRepository = new RB_CustomerRepository();
        /// <summary>
        /// 渠道仓储层对象
        /// </summary>
        private readonly RB_ChannelRepository channelRepository = new RB_ChannelRepository();

        /// <summary>
        /// 学习目的仓储层对象
        /// </summary>
        private readonly RB_LearningGoalsRepository learningGoalsRepository = new RB_LearningGoalsRepository();

        /// <summary>
        /// 课程顾问跟进仓储层对象
        /// </summary>
        private readonly RB_Student_AdvisorRepository student_AdvisorRepository = new RB_Student_AdvisorRepository();


        #region 学员跟进

        /// <summary>
        /// 学员跟进分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public object GetStudentFollowUpPageModule(int pageIndex, int pageSize, out long count, RB_Student_ViewModel demodel)
        {
          
            object Robj = new object();
            var slist = student_OrderGuestRepository.GetStudentFollowUpPageRepository(pageIndex, pageSize, out count, demodel);
            if (slist.Any())
            {
                string stuIds = string.Join(",", slist.Select(x => x.StuId));
                //查询学生每月的跟进情况
                var flist = followRepository.GetStudentFollowUpMonthList(stuIds, demodel.Group_Id);
                //查询续课  学员介绍
                var xlist = followRepository.GetStudentRenewMonthList(stuIds, demodel.Group_Id);//续费
                var zlist = followRepository.GetStudentIntroductionMonthList(stuIds, demodel.Group_Id);//转介绍
                //查询汇总数据
                var TotalData = student_OrderGuestRepository.GetStudentFollowUpStat(demodel);
                //查询每月续费介绍情况
                var ROList = student_RenewOrderRepository.GetStuMonthList(demodel.Group_Id);

                //学习目的
                string goalIds = string.Join(",", slist.Select(qitem => qitem.StuPurpose));
                var goalList = learningGoalsRepository.GetLearningGoalsListRepository(new Model.ViewModel.System.RB_LearningGoals_Extend()
                {
                    QGoalIds = goalIds
                });

                //协助人员列表
                var assistList = student_AssistRepository.GetStudentAssistListRepository(new Model.ViewModel.Customer.RB_Student_Assist_Extend()
                {
                    QStuIds = stuIds
                });
                //内部介绍人
                List<int> empIdList = Common.ConvertHelper.StringToList(string.Join(",", slist.Where(qitem => qitem.CreateType == StuCreateTypeEnum.InternalIntroduction).Select(qitem => qitem.StuSourceId)));
                List<int> aIds = Common.ConvertHelper.StringToList(string.Join(",", assistList.Select(qitem => qitem.AssistId)));
                List<RB_Account_ViewModel> accountList = new List<RB_Account_ViewModel>();
                if (aIds != null && aIds.Count > 0)
                {
                    empIdList.AddRange(aIds);
                }
                List<int> scIds = Common.ConvertHelper.StringToList(string.Join(",", slist.Select(qitem => qitem.CreateBy)));
                if (scIds != null && scIds.Count > 0)
                {
                    empIdList.AddRange(scIds);
                }
                if (empIdList != null && empIdList.Count > 0)
                {
                    accountList = accountRepository.GetAccountListExtRepository(new RB_Account_ViewModel() { QIds = string.Join(",", empIdList) });
                }

                //同业录入列表
                List<RB_Customer_Extend> customerList = new List<Model.ViewModel.Customer.RB_Customer_Extend>();
                List<int> customerIdList = Common.ConvertHelper.StringToList(string.Join(",", slist.Where(qitem => qitem.CreateType == StuCreateTypeEnum.CustomerInput).Select(qitem => qitem.StuSourceId)));
                if (customerIdList != null && customerIdList.Count > 0)
                {
                    customerList = customerRepository.GetCustomerListRepository(new Model.ViewModel.Customer.RB_Customer_Extend()
                    {
                        CustomerIds = string.Join(",", customerIdList)
                    });
                }
                List<RB_Student_ViewModel> transStudentList = new List<RB_Student_ViewModel>();
                //转介人列表
                List<int> transIdList = Common.ConvertHelper.StringToList(string.Join(",", slist.Where(qitem => qitem.CreateType == StuCreateTypeEnum.TransIntroduction).Select(qitem => qitem.StuSourceId)));
                if (transIdList != null && transIdList.Count > 0)
                {
                    transStudentList = studentRepository.GetStudentListRepository(new RB_Student_ViewModel()
                    {
                        StuIds = string.Join(",", transIdList)
                    });
                }

                string channelIds = string.Join(",", slist.Select(qitem => qitem.StuChannel));
                var channelList = channelRepository.GetChannelListRepository(new Model.ViewModel.System.RB_Channel_Extend()
                {
                    QChannelIds = channelIds
                });

                //课程顾问跟进信息
                List<RB_Student_Advisor_Extend> advisorList = student_AdvisorRepository.GetStudentAdvisorListRepository(new RB_Student_Advisor_Extend() { QStuIds = stuIds });
                #region 组装数据
                int MaxMonth = 2;//最大月份
                //数据
                List<object> RList = new List<object>();
                foreach (var item in slist)
                {
                    //组合所有的月份

                    //查询学生首次报名 至 当月的所有月份
                    int month = 1;
                    if (item.FirstEnrollDate.HasValue)
                    {
                        month = ((DateTime.Now.Year - item.FirstEnrollDate.Value.Year) * 12) + DateTime.Now.Month - item.FirstEnrollDate.Value.Month + 1;
                    }
                    else
                    {
                        item.FirstEnrollDate = DateTime.Now;
                    }
                    MaxMonth = MaxMonth < month ? month : MaxMonth;
                    List<object> MonthObjList = new List<object>();
                    for (var i = 0; i < month; i++)
                    {
                        var monthStr = item.FirstEnrollDate.Value.AddMonths(i).ToString("yyyy-MM");
                        var xmodel = xlist.Where(x => x.StuId == item.StuId && x.MonthStr == monthStr).FirstOrDefault();
                        var zmodel = zlist.Where(x => x.StuId == item.StuId && x.MonthStr == monthStr).FirstOrDefault();
                        var teacherModel = flist.Where(x => x.StuId == item.StuId && x.MonthStr == monthStr && x.AssistType == AssistTypeEnum.Teacher).FirstOrDefault();
                        var consultantModel = flist.Where(x => x.StuId == item.StuId && x.MonthStr == monthStr && x.AssistType == AssistTypeEnum.CourseAdviser).FirstOrDefault();
                        MonthObjList.Add(new
                        {
                            Month = monthStr,
                            IsRenew = xmodel != null ? 1 : 2,
                            IntroductionNum = zmodel?.StuNum ?? 0,
                            Teacher = teacherModel?.Remark ?? "",
                            TeacherTime = teacherModel?.CreateTime.ToString("yyyy-MM-dd HH:mm") ?? "",
                            Consultant = consultantModel?.Remark ?? "",
                            ConsultantTime = consultantModel?.CreateTime.ToString("yyyy-MM-dd HH:mm") ?? ""
                        });
                    }

                    var tempAssistList = assistList?.Where(qitem => qitem.StuId == item.StuId)?.ToList();
                    foreach (var sItem in tempAssistList)
                    {
                        sItem.AssistName = accountList?.FirstOrDefault(qitem => qitem.Id == sItem.AssistId)?.AccountName ?? "";
                    }
                    item.AssistList = tempAssistList;
                    if (item.CreateType == StuCreateTypeEnum.InternalIntroduction)
                    {
                        item.StuSourceIdName = accountList?.FirstOrDefault(qitem => qitem.Id == item.StuSourceId)?.AccountName ?? "";
                    }
                    else if (item.CreateType == StuCreateTypeEnum.CustomerInput)
                    {
                        var tempCustomer = customerList?.FirstOrDefault(qitem => qitem.CustomerId == item.StuSourceId);
                        item.StuSourceIdName = tempCustomer?.CustomerName ?? "";
                        if (tempCustomer != null)
                        {
                            if (tempCustomer.CustomerType == Common.Enum.Customer.CatetoryTypeEnum.Other)
                            {
                                item.EnterpriseName = tempCustomer?.CategoryName ?? "";
                            }
                            else
                            {
                                item.EnterpriseName = tempCustomer?.EnterpriseName ?? "";
                            }
                        }
                        else
                        {
                            item.EnterpriseName = "";
                        }
                    }
                    else if (item.CreateType == StuCreateTypeEnum.TransIntroduction)
                    {
                        item.StuSourceIdName = transStudentList?.FirstOrDefault(qitem => qitem.StuId == item.StuSourceId)?.StuName ?? "";
                    }
                    
                    item.CreateByName = accountList?.FirstOrDefault(qitem => qitem.Id == item.CreateBy)?.AccountName ?? "";
                    item.StuChannelName = channelList?.FirstOrDefault(qitem => qitem.Id == item.StuChannel)?.Name ?? "";
                    item.StuPurposeName = goalList?.FirstOrDefault(qitem => qitem.Id == item.StuPurpose)?.Name ?? "";
                    item.AdvisorList = advisorList?.Where(qitem => qitem.StuId == item.StuId)?.ToList();
                    var StuObj = new
                    {
                        item.StuId,
                        item.StuName,
                        item.StuTel,
                        item.StuRealMobile,
                        ContractSTime = item.followUpTime,
                        item.CourseName,
                        JapanBaseInfo = item.JapanBaseInfo.ToName(),
                        item.StuBirthStr,
                        item.StuGuestState,
                        StuGuestStateName = item.StuGuestState.ToName(),
                        MonthList = MonthObjList,
                        item.CreateBy,
                        item.CreateByName,
                        AssistList = item.AssistList.Select(qitem => new
                        {
                            qitem.Id,
                            qitem.StuId,
                            qitem.AssistId,
                            qitem.AssistName,
                            qitem.AssistType,
                            AssistTypeName = qitem.AssistType.ToName()
                        }),
                        item.StuChannel,
                        item.StuChannelName,
                        item.CreateType,
                        CreateTypeName = item.CreateType.ToName(),
                        item.StuSourceId,
                        item.StuSourceIdName,
                        item.EnterpriseName,
                        item.StuPurpose,
                        item.StuPurposeName,
                        item.AdvisorWinRate,
                        item.AdvisorExpectDate,
                        item.AdvisorStatus,
                        item.AdvisorStatusName,
                        item.AdvisorList,
                    };
                    RList.Add(StuObj);
                }
                //续费 学员介绍
                List<object> RList2 = new List<object>();
                List<int> Mlist = ROList.Select(x => x.Month).Distinct().OrderBy(x => x).ToList();
                int MaxRO = ROList.Any() ? ROList.Max(x => x.Month) : 0;
                MaxMonth = MaxMonth < MaxRO ? MaxRO : MaxMonth;
                foreach (var month in Mlist)
                {
                    RList2.Add(new
                    {
                        MonthNum = month,
                        RenewNum = ROList.Where(x => x.Month == month && x.Type == 1).FirstOrDefault()?.OrderNum ?? 0,
                        IntroductionNum = ROList.Where(x => x.Month == month && x.Type == 2).FirstOrDefault()?.OrderNum ?? 0,
                    });
                }
                Robj = new
                {
                    RList,
                    MaxMonth,
                    MonthList = RList2,
                    Stat = new
                    {
                        StuTNum = TotalData.OrderCount,
                        RenewNum = TotalData.RenewOrderCount,
                        NewNum = TotalData.OrderCount - TotalData.RenewOrderCount,
                        TotalData.StudyNum,
                        TotalData.GraduateNum,
                        TotalData.SuspendNum,
                        TotalData.DropOutNum
                    }
                };
                #endregion
            }
            return Robj;
        }

        #endregion

        #region 客人咨询

        /// <summary>
        /// 获取客人咨询分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<object> GetStudentConsultPageList(int pageIndex, int pageSize, out long count, RB_Student_ViewModel demodel)
        {
            List<object> RList = new List<object>();
            var slist = student_OrderGuestRepository.GetStudentConsultPageList(pageIndex, pageSize, out count, demodel);
            if (slist.Any())
            {
                string stuIds = string.Join(",", slist.Select(x => x.StuId));
                //查询学员最近的一条跟进记录
                var flist = followRepository.GetStudentFollowUpLatelyList(stuIds, demodel.Group_Id);
                //查询课程顾问
                var stuAssistList = student_AssistRepository.GetStudentAssistListRepository(new RB_Student_Assist_Extend() { QStuIds = stuIds });

                foreach (var item in slist)
                {
                    var fmodel = flist.Where(x => x.StuId == item.StuId).FirstOrDefault();
                    var AssistId = stuAssistList.Where(x => x.StuId == item.StuId && x.AssistType == AssistTypeEnum.CourseAdviser).FirstOrDefault()?.AssistId ?? 0;
                    string AssistName = "";
                    if (AssistId > 0)
                    {
                        AssistName = accountRepository.GetEmployeeInfo(AssistId)?.EmployeeName ?? "";
                    }
                    RList.Add(new
                    {
                        item.StuId,
                        item.StuName,
                        AssistId,
                        AssistName,
                        item.StuBirthStr,
                        item.StuTel,
                        item.StuRealMobile,
                        item.StuAddress,
                        item.StuChannelName,
                        EnrollState = item.Q_EnrollState,
                        item.CourseId,
                        item.CourseName,
                        ConsultDate = item.ConsultDate.HasValue ? item.ConsultDate.Value.ToString("yyyy-MM-dd") : "",
                        item.PlanPrice,
                        item.BaseCondition,
                        item.DemandPoint,
                        item.ResistPoint,
                        item.ConsultingResults,
                        JapanBaseInfo = item.JapanBaseInfo.ToName(),
                        FUTime = fmodel?.CreateTime.ToString("yyyy-MM-dd HH:mm") ?? "",
                        FURemark = fmodel?.Remark ?? ""
                    });
                }
            }
            return RList;
        }

        #endregion
    }
}
