using Edu.Model.ViewModel.Customer;
using Edu.Repository.Customer;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using VT.FW.DB;
using Edu.Common.Enum;
using Edu.Repository.Course;
using Edu.Model.ViewModel.Course;

namespace Edu.Module.Customer
{
    /// <summary>
    /// 同行任务处理类
    /// </summary>
    public class CustomerTaskModule
    {
        /// <summary>
        /// 任务仓储层对象
        /// </summary>
        private readonly RB_TaskRepository customer_TaskRepository = new RB_TaskRepository();

        /// <summary>
        /// 任务详情仓储层对象
        /// </summary>
        private readonly RB_TaskDetailsRepository detailsRepository = new RB_TaskDetailsRepository();

        /// <summary>
        /// 课程仓储层对象
        /// </summary>
        private readonly RB_CourseRepository courseRepository = new RB_CourseRepository();

        /// <summary>
        /// 课程系列仓储层对象
        /// </summary>
        private readonly RB_Course_CategoryRepository course_CategoryRepository = new RB_Course_CategoryRepository();

        /// <summary>
        /// 科目仓储层对象
        /// </summary>
        private readonly RB_Course_SubjectRepository course_SubjectRepository = new RB_Course_SubjectRepository();

        /// <summary>
        /// 客户完成任务仓储层对象
        /// </summary>
        private readonly RB_Customer_FinishtaskRepository customer_FinishtaskRepository = new RB_Customer_FinishtaskRepository();

        /// <summary>
        /// 客户任务完成详情仓储层对象
        /// </summary>
        private readonly RB_Customer_FinishdetailsRepository customer_FinishdetailsRepository = new RB_Customer_FinishdetailsRepository();

        /// <summary>
        /// 获取任务分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Task_Extend> GetTaskPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Task_Extend query)
        {
            var list = customer_TaskRepository.GetTaskPageRepository(pageIndex, pageSize, out rowsCount, query);
            if (list != null && list.Count > 0)
            {
                string Ids = string.Join(",", list.Select(qitem => qitem.Id));
                var detailsList = new List<RB_TaskDetails_Extend>();
                if (!string.IsNullOrEmpty(Ids))
                {
                    detailsList = detailsRepository.GetTaskDetailsListRepository(new RB_TaskDetails_Extend()
                    {
                        QTaskIds = Ids
                    });
                    ParsingSubTaskTarget(detailsList);
                }
                foreach (var item in list)
                {
                    item.DetailsList = detailsList?.Where(qitem => qitem.TaskId == item.Id)?.ToList();
                }
            }
            return list;
        }

        /// <summary>
        /// 处理子任务
        /// </summary>
        /// <param name="detailsList"></param>
        private void ParsingSubTaskTarget(List<RB_TaskDetails_Extend> detailsList)
        {
            if (detailsList != null && detailsList.Count > 0)
            {
                var groupList = detailsList.GroupBy(qitem => new { qitem.TaskType }).Select(qitem => new { qitem.Key.TaskType });
                var courseList = new List<RB_Course_ViewModel>();
                var cateList = new List<RB_Course_Category_ViewModel>();
                var subjectList = new List<RB_Course_Subject_ViewModel>();
                foreach (var item in groupList)
                {
                    if (item.TaskType == Common.Enum.Customer.TaskTypeEnum.Course)
                    {
                        string courseIds = string.Join(",", detailsList.Where(qitem => qitem.TaskType == item.TaskType).Select(qitem => qitem.TargetId));
                        courseList = courseRepository.GetCourseListRepository(new RB_Course_ViewModel()
                        {
                            QCourseIds = courseIds
                        });
                    }
                    else if (item.TaskType == Common.Enum.Customer.TaskTypeEnum.CourseCate)
                    {
                        string catdIds = string.Join(",", detailsList.Where(qitem => qitem.TaskType == item.TaskType).Select(qitem => qitem.TargetId));
                        cateList = course_CategoryRepository.GetCourseCategoryListRepository(new RB_Course_Category_ViewModel() { QCateIds = catdIds });
                    }
                    else if (item.TaskType == Common.Enum.Customer.TaskTypeEnum.CourseSuject)
                    {
                        string subjectIds = string.Join(",", detailsList.Where(qitem => qitem.TaskType == item.TaskType).Select(qitem => qitem.TargetId));
                        subjectList = course_SubjectRepository.GetCourseSubjectListRepository(new RB_Course_Subject_ViewModel()
                        {
                            QIds = subjectIds
                        });
                    }
                }

                foreach (var item in detailsList)
                {
                    item.TargetList = new List<object>();
                    if (item.TargetIdList != null && item.TargetIdList.Count > 0)
                    {
                        foreach (var subItem in item.TargetIdList)
                        {
                            switch (item.TaskType)
                            {
                                case Common.Enum.Customer.TaskTypeEnum.Course:
                                    var courseModel = courseList.Where(qitem => qitem.CourseId == subItem)?.FirstOrDefault();
                                    if (courseModel != null)
                                    {
                                        item.TargetList.Add(new
                                        {
                                            TargetId = courseModel.CourseId,
                                            TargetName = courseModel.CourseName
                                        });
                                    }
                                    break;
                                case Common.Enum.Customer.TaskTypeEnum.CourseCate:
                                    var cateModel = cateList.Where(qitem => qitem.CateId == subItem)?.FirstOrDefault();
                                    if (cateModel != null)
                                    {
                                        item.TargetList.Add(new
                                        {
                                            TargetId = cateModel.CateId,
                                            TargetName = cateModel.CateName
                                        });
                                    }
                                    break;
                                case Common.Enum.Customer.TaskTypeEnum.CourseSuject:
                                    var subjectModel = subjectList.Where(qitem => qitem.Id == subItem)?.FirstOrDefault();
                                    if (subjectModel != null)
                                    {
                                        item.TargetList.Add(new
                                        {
                                            TargetId = subjectModel.Id,
                                            TargetName = subjectModel.SubjectName
                                        });
                                    }
                                    break;
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 新增修改任务信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetCustomerTaskModule(RB_Task_Extend model)
        {
            bool flag = false;
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Task_Extend.TaskName),model.TaskName },
                    {nameof(RB_Task_Extend.TaskSubTitle),model.TaskSubTitle },
                    {nameof(RB_Task_Extend.TaskImage),model.TaskImage },
                    {nameof(RB_Task_Extend.TaskStartTime),model.TaskStartTime },
                    {nameof(RB_Task_Extend.TaskEndTime),model.TaskEndTime },
                    {nameof(RB_Task_Extend.TaskDesc),model.TaskDesc },
                    {nameof(RB_Task_Extend.UpdateBy),model.UpdateBy },
                    {nameof(RB_Task_Extend.UpdateTime),model.UpdateTime },
                    {nameof(RB_Task_Extend.ExchangeEndTime),model.ExchangeEndTime },
                    {nameof(RB_Task_Extend.TaskFinishType),model.TaskFinishType },
                };
                flag = customer_TaskRepository.Update(fileds, new WhereHelper(nameof(RB_Task_Extend.Id), model.Id));
            }
            else
            {
                var newId = customer_TaskRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }


            if (model.DetailsList != null && model.DetailsList.Count > 0)
            {
                var oldList = detailsRepository.GetTaskDetailsListRepository(new RB_TaskDetails_Extend()
                {
                    TaskId = model.Id
                });
                //以前没有任务详情信息【直接新增】
                if (oldList == null || (oldList != null && oldList.Count == 0))
                {
                    if (model.DetailsList != null && model.DetailsList.Count > 0)
                    {
                        foreach (var item in model.DetailsList)
                        {
                            item.TaskId = model.Id;
                            detailsRepository.Insert(item);
                        }
                    }
                }
                else
                {
                    //现在没有任务详情了【直接删除以前的任务详情】
                    if (model.DetailsList == null || (model.DetailsList != null && model.DetailsList.Count == 0))
                    {
                        detailsRepository.DeleteByTaskIdRepository(model.Id);
                    }
                    //找出差异的数据
                    var deleteList = oldList.Where(qitem => !model.DetailsList.Any(oldItem => qitem.DetailId == oldItem.DetailId)).ToList();
                    foreach (var dItem in deleteList)
                    {
                        if (dItem.DetailId > 0)
                        {
                            detailsRepository.Delete(dItem.DetailId);
                        }
                    }
                    foreach (var item in model.DetailsList)
                    {
                        item.TaskId = model.Id;
                        if (item.DetailId == 0)
                        {
                            detailsRepository.Insert(item);
                        }
                        else
                        {
                            Dictionary<string, object> subFileds = new Dictionary<string, object>()
                            {
                                {nameof(RB_TaskDetails_Extend.TaskId),item.TaskId },
                                {nameof(RB_TaskDetails_Extend.DetailsName),item.DetailsName },
                                {nameof(RB_TaskDetails_Extend.TaskType),item.TaskType },
                                {nameof(RB_TaskDetails_Extend.TargetId),item.TargetId },
                                {nameof(RB_TaskDetails_Extend.TaskFinishValue),item.TaskFinishValue },
                                {nameof(RB_TaskDetails_Extend.TaskKudo),item.TaskKudo },
                                {nameof(RB_TaskDetails_Extend.TaskKudoImg),item.TaskKudoImg },
                                {nameof(RB_TaskDetails_Extend.KudoDescription),item.KudoDescription },
                            };
                            detailsRepository.Update(subFileds, new WhereHelper(nameof(RB_TaskDetails_Extend.DetailId), item.DetailId));
                        }
                    }
                }
            }
            else
            {
                detailsRepository.DeleteByTaskIdRepository(model.Id);
            }
            return flag;
        }

        /// <summary>
        /// 根据任务编号删除任务
        /// </summary>
        /// <param name="CustomerId"></param>
        /// <returns></returns>
        public bool RemoveCustomerTaskModule(object Id)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
               {nameof(RB_Task_Extend.Status),(int)DateStateEnum.Delete},
            };
            var flag = customer_TaskRepository.Update(fileds, new WhereHelper(nameof(RB_Task_Extend.Id), Id));
            return flag;
        }


        /// <summary>
        /// 根据任务编号获取任务实体类
        /// </summary>
        /// <param name="CustomerId"></param>
        /// <returns></returns>
        public RB_Task_Extend GetCustomerTaskModule(object Id)
        {
            var extModel = customer_TaskRepository.GetEntity<RB_Task_Extend>(Id);
            if (extModel != null)
            {
                var detailsList = detailsRepository.GetTaskDetailsListRepository(new RB_TaskDetails_Extend()
                {
                    TaskId = extModel.Id
                });
                ParsingSubTaskTarget(detailsList);
                extModel.DetailsList = detailsList;
            }
            return extModel;
        }

        /// <summary>
        /// 获取客户完成任务分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Customer_Finishtask_Extend> GetCustomerFinishtaskPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Customer_Finishtask_Extend query)
        {
            var list = customer_FinishtaskRepository.GetCustomerFinishtaskPageRepository(pageIndex, pageSize, out rowsCount, query);
            return list;
        }

        /// <summary>
        /// 获取任务和订单关联列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Customer_Finishdetails_Extend> GetCustomerFinishdetailsPageModule(int pageIndex, int pageSize,out long rowsCount, RB_Customer_Finishdetails_Extend query)
        {
            var list = customer_FinishdetailsRepository.GetCustomerFinishdetailsPageRepository(pageIndex, pageSize, out rowsCount, query);
            return list;
        }

        /// <summary>
        /// 客户兑换奖品
        /// </summary>
        /// <returns></returns>
        public virtual bool ExchangeKudoModule(int Id,  out string message)
        {
            message = "";
            bool flag = false;
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
               {nameof(RB_Customer_Finishtask_Extend.ExchangeStatus),2 } ,
               {nameof(RB_Customer_Finishtask_Extend.ExchangeTime),DateTime.Now },
            };
            List<WhereHelper> where = new List<WhereHelper>()
            {
                new WhereHelper(nameof(RB_Customer_Finishtask_Extend.Id),Id),
            };
            flag = customer_FinishtaskRepository.Update(fileds, where);
            return flag;
        }
    }
}
