using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mall.Common;
using Mall.Common.Plugin;
using Newtonsoft.Json;
using Mall.Common.API;
using Newtonsoft.Json.Linq;
using VT.FW.DB;
using Mall.Repository.Miai;
using Mall.Model.Extend.Miai;
using Mall.Model.Entity.Education;

namespace Mall.Module.Miai
{
    /// <summary>
    /// 相亲处理层
    /// </summary>
    public class MiaiModule
    {
        private readonly RB_Miai_ForumRepository miai_ForumRepository = new RB_Miai_ForumRepository();
        private readonly RB_Miai_ActivityRepository miai_ActivityRepository = new RB_Miai_ActivityRepository();
        private readonly RB_Miai_ActivityEnrollRepository miai_ActivityEnrollRepository = new RB_Miai_ActivityEnrollRepository();
        private readonly RB_Miai_ActivityDiscussRepository miai_ActivityDiscussRepository = new RB_Miai_ActivityDiscussRepository();
        private readonly RB_Miai_LogRepository miai_LogRepository = new RB_Miai_LogRepository();


        private readonly RB_MiAi_BaseInfoRepository miai_BaseInfoRepository = new RB_MiAi_BaseInfoRepository();


        private readonly RB_MiAi_FollowMemberRepository miai_FollowMemberRepository = new RB_MiAi_FollowMemberRepository();

        /// <summary>
        /// 用户管理
        /// </summary>
        private readonly Repository.User.RB_Member_UserRepository member_UserRepository = new Repository.User.RB_Member_UserRepository();

        #region 会员信息
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public Model.Extend.User.RB_Member_User_Extend GetMemberUserInfo(int userId)
        {
            return member_UserRepository.GetEntity(userId).RefMapperTo<Model.Extend.User.RB_Member_User_Extend>();
        }
        #endregion


        #region 活动版块
        /// <summary>
        /// 获取活动版本分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Miai_Forum_Extend> GetForumPageList(int pageIndex, int pageSize, out long count, RB_Miai_Forum_Extend dmodel)
        {
            return miai_ForumRepository.GetPageList(pageIndex, pageSize, out count, dmodel);
        }

        /// <summary>
        /// 获取活动版块列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Miai_Forum_Extend> GetForumList(RB_Miai_Forum_Extend demodel)
        {
            return miai_ForumRepository.GetList(demodel);
        }

        /// <summary>
        /// 保存活动版块
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetForumInfo(RB_Miai_Forum_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Miai_Forum_Extend.Name),demodel.Name},
                    { nameof(RB_Miai_Forum_Extend.Icon),demodel.Icon},
                    { nameof(RB_Miai_Forum_Extend.Sort),demodel.Sort},
                    { nameof(RB_Miai_Forum_Extend.IsShow),demodel.IsShow},
                    { nameof(RB_Miai_Forum_Extend.UpdateDate),demodel.UpdateDate},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Miai_Forum_Extend.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = miai_ForumRepository.Update(keyValues, wheres);
                return flag;
            }
            else
            {
                bool flag = miai_ForumRepository.Insert(demodel) > 0;
                return flag;
            }
        }

        /// <summary>
        /// 设置版块状态
        /// </summary>
        /// <param name="forumId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public bool SetForumState(int forumId, int type)
        {
            if (type == 1)
            {
                var model = miai_ForumRepository.GetEntity(forumId);
                if (model == null) { return false; }
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Miai_Forum_Extend.IsShow),model.IsShow==1?2:1},
                    { nameof(RB_Miai_Forum_Extend.UpdateDate),DateTime.Now},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Miai_Forum_Extend.Id),
                          FiledValue=forumId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = miai_ForumRepository.Update(keyValues, wheres);
                return flag;
            }
            else
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Miai_Forum_Extend.Status),1},
                    { nameof(RB_Miai_Forum_Extend.UpdateDate),DateTime.Now},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Miai_Forum_Extend.Id),
                          FiledValue=forumId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = miai_ForumRepository.Update(keyValues, wheres);
                return flag;
            }
        }

        /// <summary>
        /// 获取活动分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Miai_Activity_Extend> GetActivityPageList(int pageIndex, int pageSize, out long count, RB_Miai_Activity_Extend demodel)
        {
            var list = miai_ActivityRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                string ActivityIds = string.Join(",", list.Select(x => x.Id));
                //查询活动回复数量
                var rlist = miai_ActivityDiscussRepository.GetActivityReplyNumList(ActivityIds);
                //查询活动报名数量
                var elist = miai_ActivityEnrollRepository.GetActivityEnrollNumList(ActivityIds);
                //查询版本信息
                string ForumIds = string.Join(",", list.Select(x => x.ForumId).Distinct());
                var flist = miai_ForumRepository.GetList(new RB_Miai_Forum_Extend() { ForumIds = ForumIds });
                foreach (var item in list)
                {
                    item.ImageList = new List<string>();
                    if (!string.IsNullOrEmpty(item.Images) && item.Images != "[]")
                    {
                        item.ImageList = JsonConvert.DeserializeObject<List<string>>(item.Images);
                    }
                    item.ReplyNum = rlist.Where(x => x.ActivityId == item.Id).FirstOrDefault()?.ReplyNum ?? 0;
                    item.EnrollNum = elist.Where(x => x.ActivityId == item.Id).FirstOrDefault()?.Number ?? 0;
                    var fmodel = flist.Where(x => x.Id == item.ForumId).FirstOrDefault();
                    item.ForumName = fmodel?.Name ?? "";
                    item.ForumIcon = fmodel?.Icon ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 获取活动信息
        /// </summary>
        /// <param name="activityId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetActivityInfo(int activityId, AppletUserInfo userInfo)
        {
            var model = miai_ActivityRepository.GetEntity(activityId);
            if (model == null) { return ""; }
            //获取活动报名人数
            int PeopleNum = miai_ActivityEnrollRepository.GetActivityEnrollNum(activityId);
            //获取当前用户是否已报名
            bool IsEnroll = miai_ActivityEnrollRepository.GetList(new RB_Miai_ActivityEnroll_Extend() { TenantId = model.TenantId, ActivityId = activityId, UserId = userInfo.UserId }).Any();
            //查询活动回复数量
            var rlist = miai_ActivityDiscussRepository.GetActivityReplyNumList(activityId.ToString());
            var umodel = CacheManager.User.UserReidsCache.GetAppletUserLoginInfo(model.UserId);
            //查询用户性别
            int Sex = miai_BaseInfoRepository.GetBaseInfoList(new RB_MiAi_BaseInfo_Extend() { TenantId = userInfo.TenantId, UserId = model.UserId }).FirstOrDefault()?.Sex ?? 0;
            //查询当前用户是否已关注
            var myFollowList = miai_FollowMemberRepository.GetFollowMemberList(new RB_MiAi_FollowMember_Extend() { TenantId = userInfo.TenantId, UserId = model.UserId, CreateBy = userInfo.UserId });
            bool IsFocus = myFollowList.Any();
            var otherFollowList = miai_FollowMemberRepository.GetFollowMemberList(new RB_MiAi_FollowMember_Extend() { TenantId = userInfo.TenantId, UserId = userInfo.UserId, CreateBy = model.UserId });
            //查询是否已关注我
            bool IsFocus2 = otherFollowList.Any();
            return new
            {
                model.Id,
                model.ActivityTitle,
                model.Content,
                ImageList = !string.IsNullOrEmpty(model.Images) ? JsonConvert.DeserializeObject<List<string>>(model.Images) : new List<string>() { },
                model.UserId,
                UserName = umodel.Name,
                umodel.Photo,
                Sex,
                model.IsOpenEnroll,
                Deadline = model.IsOpenEnroll == 1 ? model.Deadline.Value.ToString("yyyy-MM-dd HH:mm") : "",
                CreateDate = model.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                PeopleNum,
                IsEnroll,
                IsFocus = IsFocus == true && IsFocus2 == true ? 2 : IsFocus == true ? 1 : 0,
                ReplyNum = rlist.FirstOrDefault()?.ReplyNum ?? 0,
                MyFollowId = (myFollowList != null && myFollowList.Any()) ? myFollowList.FirstOrDefault()?.ID : 0,
                OtherFollowId = (otherFollowList != null && otherFollowList.Any()) ? otherFollowList.FirstOrDefault()?.ID : 0
            };
        }

        /// <summary>
        /// 后台获取活动信息
        /// </summary>
        /// <param name="activityId"></param>
        /// <returns></returns>
        public object GetActivityInfo_V2(int activityId)
        {
            var model = miai_ActivityRepository.GetEntity(activityId);
            if (model == null) { return ""; }
            //获取活动报名人数
            int PeopleNum = miai_ActivityEnrollRepository.GetActivityEnrollNum(activityId);
            //查询活动回复数量
            var rlist = miai_ActivityDiscussRepository.GetActivityReplyNumList(activityId.ToString());
            var umodel = CacheManager.User.UserReidsCache.GetAppletUserLoginInfo(model.UserId);
            return new
            {
                model.Id,
                model.ActivityTitle,
                model.Content,
                ImageList = !string.IsNullOrEmpty(model.Images) ? JsonConvert.DeserializeObject<List<string>>(model.Images) : new List<string>() { },
                model.UserId,
                UserName = umodel.Name,
                umodel.Photo,
                model.IsOpenEnroll,
                Deadline = model.IsOpenEnroll == 1 ? model.Deadline.Value.ToString("yyyy-MM-dd HH:mm") : "",
                CreateDate = model.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                PeopleNum,
                ReplyNum = rlist.FirstOrDefault()?.ReplyNum ?? 0
            };
        }

        /// <summary>
        /// 发帖招募
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetActivityInfo(RB_Miai_Activity_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                var model = miai_ActivityRepository.GetEntity(demodel.Id);
                if (model == null || model.Status == 1) { return false; }
                if (model.UserId != demodel.UserId) { return false; }
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Miai_Activity_Extend.ActivityTitle),demodel.ActivityTitle},
                    { nameof(RB_Miai_Activity_Extend.Content),demodel.Content},
                    { nameof(RB_Miai_Activity_Extend.Images),demodel.Images},
                    { nameof(RB_Miai_Activity_Extend.IsOpenEnroll),demodel.IsOpenEnroll},
                    { nameof(RB_Miai_Activity_Extend.Deadline),demodel.Deadline},
                    { nameof(RB_Miai_Activity_Extend.UpdateDate),demodel.UpdateDate}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Miai_Activity_Extend.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return miai_ActivityRepository.Update(keyValues, wheres);
            }
            else
            {
                return miai_ActivityRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 删除招募贴
        /// </summary>
        /// <param name="activityId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string DelActivityInfo(int activityId, AppletUserInfo userInfo)
        {
            var model = miai_ActivityRepository.GetEntity(activityId);
            if (model == null || model.Status == 1) { return "帖子不存在或已被删除"; }
            if (model.UserId != userInfo.UserId) { return "没有权限删除"; }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Miai_Activity_Extend.Status),1},
                { nameof(RB_Miai_Activity_Extend.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Miai_Activity_Extend.Id),
                        FiledValue=activityId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = miai_ActivityRepository.Update(keyValues, wheres);
            if (flag)
            {
                miai_LogRepository.Insert(new Model.Entity.Miai.RB_Miai_Log()
                {
                    Id = 0,
                    Type = 1,
                    SourceId = activityId,
                    UserId = userInfo.UserId,
                    Content = "用户自行删除招募贴",
                    EmpId = 0,
                    TenantId = userInfo.TenantId,
                    MallBaseId = userInfo.MallBaseId,
                    CreateDate = DateTime.Now
                });
            }
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 后台删除帖子
        /// </summary>
        /// <param name="activityId"></param>
        /// <param name="empId"></param>
        /// <returns></returns>
        public string DelActivityInfo_V2(int activityId, int empId, int TenantId, int MallBaseId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Miai_Activity_Extend.Status),1},
                { nameof(RB_Miai_Activity_Extend.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Miai_Activity_Extend.Id),
                        FiledValue=activityId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = miai_ActivityRepository.Update(keyValues, wheres);
            if (flag)
            {
                miai_LogRepository.Insert(new Model.Entity.Miai.RB_Miai_Log()
                {
                    Id = 0,
                    Type = 1,
                    SourceId = activityId,
                    UserId = 0,
                    Content = "后台删除招募贴",
                    EmpId = empId,
                    TenantId = TenantId,
                    MallBaseId = MallBaseId,
                    CreateDate = DateTime.Now
                });
            }
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 获取活动评论分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Miai_ActivityDiscuss_Extend> GetActivityDiscussPageList(int pageIndex, int pageSize, out long count, RB_Miai_ActivityDiscuss_Extend demodel)
        {
            demodel.ParentId = -1;//查询主评论
            var list = miai_ActivityDiscussRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                //查询评论下  前几条回复记录
                List<int> PidsList = list.Select(x => x.Id).ToList();
                var clist = miai_ActivityDiscussRepository.GetActivityDiscussChildList(PidsList, 4);
                //查询评论回复数量
                var rlist = miai_ActivityDiscussRepository.GetDiscussReplyNumList(string.Join(",", PidsList));
                foreach (var item in list)
                {
                    item.ReplyList = clist.Where(x => x.ParentId == item.Id).OrderBy(x => x.Id).ToList();
                    item.ReplyNum = rlist.Where(x => x.ParentId == item.Id).FirstOrDefault()?.ReplyNum ?? 0;
                    item.ImageList = new List<string>();
                    if (!string.IsNullOrEmpty(item.Images) && item.Images != "[]")
                    {
                        item.ImageList = JsonConvert.DeserializeObject<List<string>>(item.Images);
                    }
                    foreach (var qitem in item.ReplyList)
                    {
                        qitem.ImageList = new List<string>();
                        if (!string.IsNullOrEmpty(qitem.Images) && qitem.Images != "[]")
                        {
                            qitem.ImageList = JsonConvert.DeserializeObject<List<string>>(qitem.Images);
                        }
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取评论回复分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Miai_ActivityDiscuss_Extend> GetActivityReplyPageList(int pageIndex, int pageSize, out long count, RB_Miai_ActivityDiscuss_Extend demodel)
        {
            var list = miai_ActivityDiscussRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            foreach (var qitem in list)
            {
                qitem.ImageList = new List<string>();
                if (!string.IsNullOrEmpty(qitem.Images) && qitem.Images != "[]")
                {
                    qitem.ImageList = JsonConvert.DeserializeObject<List<string>>(qitem.Images);
                }
            }
            return list;
        }

        /// <summary>
        /// 设置评论
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetActivityDiscussInfo(RB_Miai_ActivityDiscuss_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                var model = miai_ActivityDiscussRepository.GetEntity(demodel.Id);
                if (model == null || model.Status == 1) { return false; }
                if (model.UserId != demodel.UserId) { return false; }
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Miai_ActivityDiscuss_Extend.Content),demodel.Content},
                    { nameof(RB_Miai_ActivityDiscuss_Extend.Images),demodel.Images},
                    { nameof(RB_Miai_ActivityDiscuss_Extend.UpdateDate),demodel.UpdateDate}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Miai_ActivityDiscuss_Extend.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return miai_ActivityDiscussRepository.Update(keyValues, wheres);
            }
            else
            {
                return miai_ActivityDiscussRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 删除回复
        /// </summary>
        /// <param name="discussId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string DelActivityDiscussInfo(int discussId, AppletUserInfo userInfo)
        {
            var model = miai_ActivityDiscussRepository.GetEntity(discussId);
            if (model == null || model.Status == 1) { return "回复不存在或已被删除"; }
            if (model.UserId != userInfo.UserId) { return "没有权限删除"; }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Miai_ActivityDiscuss_Extend.Status),1},
                { nameof(RB_Miai_ActivityDiscuss_Extend.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Miai_ActivityDiscuss_Extend.Id),
                        FiledValue=discussId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = miai_ActivityDiscussRepository.Update(keyValues, wheres);
            if (flag)
            {
                miai_LogRepository.Insert(new Model.Entity.Miai.RB_Miai_Log()
                {
                    Id = 0,
                    Type = 2,
                    SourceId = discussId,
                    UserId = userInfo.UserId,
                    Content = "用户自行删除评论",
                    EmpId = 0,
                    TenantId = userInfo.TenantId,
                    MallBaseId = userInfo.MallBaseId,
                    CreateDate = DateTime.Now
                });
            }
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 后台删除回复
        /// </summary>
        /// <param name="discussId"></param>
        /// <param name="empId"></param>
        /// <returns></returns>
        public string DelActivityDiscussInfo_V2(int discussId, int empId, int TenantId, int MallBaseId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Miai_ActivityDiscuss_Extend.Status),1},
                { nameof(RB_Miai_ActivityDiscuss_Extend.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Miai_ActivityDiscuss_Extend.Id),
                        FiledValue=discussId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = miai_ActivityDiscussRepository.Update(keyValues, wheres);
            if (flag)
            {
                miai_LogRepository.Insert(new Model.Entity.Miai.RB_Miai_Log()
                {
                    Id = 0,
                    Type = 2,
                    SourceId = discussId,
                    UserId = 0,
                    Content = "用户自行删除评论",
                    EmpId = empId,
                    TenantId = TenantId,
                    MallBaseId = MallBaseId,
                    CreateDate = DateTime.Now
                });
            }
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 获取报名分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Miai_ActivityEnroll_Extend> GetActivityEnrollPageList(int pageIndex, int pageSize, out long count, RB_Miai_ActivityEnroll_Extend demodel, AppletUserInfo userInfo)
        {
            var list = miai_ActivityEnrollRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                string UserIds = string.Join(",", list.Select(x => x.UserId).Distinct());
                //查询当前用户是否已关注
                var flist = miai_FollowMemberRepository.GetFollowMemberList(new RB_MiAi_FollowMember_Extend() { TenantId = userInfo.TenantId, UserIds = UserIds, CreateBy = userInfo.UserId });
                //查询是否已关注我
                var flist2 = miai_FollowMemberRepository.GetFollowMemberList(new RB_MiAi_FollowMember_Extend() { TenantId = userInfo.TenantId, UserId = userInfo.UserId, CreateByIds = UserIds });
                foreach (var item in list)
                {
                    item.IsFocus = flist.Where(x => x.UserId == item.UserId).Any() ? 1 : 0;
                    if (flist2.Where(x => x.CreateBy == item.UserId).Any() && item.IsFocus == 1)
                    {
                        item.IsFocus = 2;
                    }
                    item.MyFollowId = (flist != null && flist.Any()) ? (flist.FirstOrDefault()?.ID ?? 0) : 0;
                    item.OtherFollowId = (flist2 != null && flist2.Any()) ? (flist2.FirstOrDefault()?.ID ?? 0) : 0;
                }
            }
            return list;
        }

        /// <summary>
        /// 获取报名分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Miai_ActivityEnroll_Extend> GetActivityEnrollPageList_V2(int pageIndex, int pageSize, out long count, RB_Miai_ActivityEnroll_Extend demodel)
        {
            return miai_ActivityEnrollRepository.GetPageList(pageIndex, pageSize, out count, demodel);
        }

        /// <summary>
        /// 活动报名
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetActivityEnrollInfo(RB_Miai_ActivityEnroll_Extend demodel)
        {
            var list = miai_ActivityEnrollRepository.GetList(new RB_Miai_ActivityEnroll_Extend() { TenantId = demodel.TenantId, ActivityId = demodel.ActivityId, UserId = demodel.UserId });
            if (list.Any()) { return "已存在报名信息"; }
            var model = miai_ActivityRepository.GetEntity(demodel.ActivityId);
            if (model == null || model.Status == 1) { return "活动不存在"; }
            if (model.IsOpenEnroll != 1) { return "无法报名"; }
            if (model.Deadline <= DateTime.Now)
            {
                return "已过了报名时间，无法报名";
            }
            bool flag = miai_ActivityEnrollRepository.Insert(demodel) > 0;
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 取消报名
        /// </summary>
        /// <param name="enrollId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string CancelActivityEnrollInfo(int enrollId, AppletUserInfo userInfo)
        {
            var model = miai_ActivityEnrollRepository.GetEntity(enrollId);
            if (model == null || model.Status == 1) { return "已取消报名"; }
            if (model.UserId != userInfo.UserId) { return "没有取消权限"; }
            var amodel = miai_ActivityRepository.GetEntity(model.ActivityId);
            if (amodel == null || amodel.Status == 1) { return "帖子已被删除"; }
            if (amodel.IsOpenEnroll != 1) { return "无法取消报名"; }
            if (amodel.Deadline <= DateTime.Now)
            {
                return "已过了报名时间，无法报名";
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Miai_ActivityEnroll_Extend.Status),1 },
                { nameof(RB_Miai_ActivityEnroll_Extend.UpdateDate),DateTime.Now },
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Miai_ActivityEnroll_Extend.Id),
                      FiledValue=enrollId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };

            bool flag = miai_ActivityEnrollRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 获取招募贴我的报名记录
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Miai_ActivityEnroll_Extend> GetMyEnrollPageList(int pageIndex, int pageSize, out long count, RB_Miai_ActivityEnroll_Extend demodel)
        {
            var list = miai_ActivityEnrollRepository.GetMyEnrollPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                string ActivityIds = string.Join(",", list.Select(x => x.ActivityId).Distinct());
                //查询活动帖子
                var alist = miai_ActivityRepository.GetList(new RB_Miai_Activity_Extend() { TenantId = demodel.TenantId, ActivityIds = ActivityIds }, true);
                //查询活动报名数量
                var elist = miai_ActivityEnrollRepository.GetActivityEnrollNumList(ActivityIds);
                foreach (var item in alist)
                {
                    item.ImageList = new List<string>();
                    if (!string.IsNullOrEmpty(item.Images) && item.Images != "[]")
                    {
                        item.ImageList = JsonConvert.DeserializeObject<List<string>>(item.Images);
                    }
                    item.EnrollNum = elist.Where(x => x.ActivityId == item.Id).FirstOrDefault()?.Number ?? 0;
                }
                foreach (var item in list)
                {
                    item.ActivityModel = alist.Where(x => x.Id == item.ActivityId).FirstOrDefault();
                }
            }
            return list;
        }
        #endregion

        #region 会员基础信息


        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public List<RB_MiAi_BaseInfo_Extend> GetBaseInfoList(RB_MiAi_BaseInfo_Extend where)
        {
            return miai_BaseInfoRepository.GetBaseInfoList(where);
        }


        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="where"></param>
        /// <returns></returns>
        public List<RB_MiAi_BaseInfo_Extend> GetBaseInfoPageList(int pageIndex, int pageSize, out long rowsCount, RB_MiAi_BaseInfo_Extend where)
        {
            return miai_BaseInfoRepository.GetBaseInfoPageList(pageIndex, pageSize, out rowsCount, where);
        }

        /// <summary>
        /// 新增用户的基础信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetMiAiBaseInfo(RB_MiAi_BaseInfo_Extend model)
        {
            bool flag = false;
            if (model.Id == 0)
            {
                flag = miai_BaseInfoRepository.Insert(model) > 0;
            }
            else
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        //{ nameof(RB_MiAi_BaseInfo_Extend.Sex),model.Sex},
                        { nameof(RB_MiAi_BaseInfo_Extend.Birthday),model.Birthday},
                        { nameof(RB_MiAi_BaseInfo_Extend.Weight),model.Weight},
                        { nameof(RB_MiAi_BaseInfo_Extend.Height),model.Height},
                        { nameof(RB_MiAi_BaseInfo_Extend.EducationType),model.EducationType},
                        { nameof(RB_MiAi_BaseInfo_Extend.Marriage),model.Marriage},
                        //{ nameof(RB_MiAi_BaseInfo_Extend.RealName),model.RealName},
                        //{ nameof(RB_MiAi_BaseInfo_Extend.IDCardNo),model.IDCardNo},
                        //{ nameof(RB_MiAi_BaseInfo_Extend.IDCard),model.IDCard},
                        //{ nameof(RB_MiAi_BaseInfo_Extend.IDCardBack),model.IDCardBack},
                        { nameof(RB_MiAi_BaseInfo_Extend.HuKou),model.HuKou},
                        { nameof(RB_MiAi_BaseInfo_Extend.NativePlace),model.NativePlace},
                        { nameof(RB_MiAi_BaseInfo_Extend.HouseInfo),model.HouseInfo},
                        { nameof(RB_MiAi_BaseInfo_Extend.SchoolInfo),model.SchoolInfo},
                        { nameof(RB_MiAi_BaseInfo_Extend.YearMoney),model.YearMoney},
                        { nameof(RB_MiAi_BaseInfo_Extend.Job),model.Job},
                        { nameof(RB_MiAi_BaseInfo_Extend.OtherPople),model.OtherPople},
                        { nameof(RB_MiAi_BaseInfo_Extend.MajorInfo),model.MajorInfo},
                        { nameof(RB_MiAi_BaseInfo_Extend.CarInfo),model.CarInfo},
                        { nameof(RB_MiAi_BaseInfo_Extend.FatherInfo),model.FatherInfo},
                        { nameof(RB_MiAi_BaseInfo_Extend.MotherInfo),model.MotherInfo},
                        { nameof(RB_MiAi_BaseInfo_Extend.About),model.About},
                        { nameof(RB_MiAi_BaseInfo_Extend.IdealLove),model.IdealLove},
                          { nameof(RB_MiAi_BaseInfo_Extend.Album),model.Album}
                    };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_MiAi_BaseInfo_Extend.Id),
                              FiledValue=model.Id,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };

                flag = miai_BaseInfoRepository.Update(keyValues, wheres);
            }
            return flag;
        }


        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="where"></param>
        /// <returns></returns>
        public List<RB_MiAi_BaseInfo_Extend> GetFirstBaseInfoPageList(int pageIndex, int pageSize, out long rowsCount, RB_MiAi_BaseInfo_Extend where)
        {
            return miai_BaseInfoRepository.GetFirstBaseInfoPageList(pageIndex, pageSize, out rowsCount, where);
        }
        #endregion

        #region 我的粉丝/我的关注
        /// <summary>
        /// 新增/修改我关注的会员配置
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddOrUpdateFollowMember(RB_MiAi_FollowMember model, RB_MiAi_BaseInfo_Extend baseInfo)
        {
            bool flag = false;
            try
            {
                if (model.ID == 0)
                {
                    flag = miai_FollowMemberRepository.Insert(model) > 0;
                    baseInfo.FollowNum += 1;
                }
                else
                {
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Education_FollowTeacher.UpdateDate),System.DateTime.Now},
                        { nameof(RB_Education_FollowTeacher.Status),model.Status}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_MiAi_FollowMember.ID),
                              FiledValue=model.ID,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    if (model.Status == 1)//取消关注
                    {
                        baseInfo.FollowNum -= 1;
                    }
                    else
                    {
                        baseInfo.FollowNum += 1;
                    }
                    flag = miai_FollowMemberRepository.Update(keyValues, wheres);
                }
                if (flag)
                {

                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_MiAi_BaseInfo_Extend.FollowNum),baseInfo.FollowNum}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_MiAi_BaseInfo_Extend.Id),
                              FiledValue=baseInfo.Id,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    miai_BaseInfoRepository.Update(keyValues, wheres);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "AddOrUpdateFollowMember");
                return false;
            }
            return flag;
        }


        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public List<RB_MiAi_FollowMember_Extend> GetFollowMemberList(RB_MiAi_FollowMember_Extend where)
        {
            return miai_FollowMemberRepository.GetFollowMemberList(where);
        }

        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="where"></param>
        /// <returns></returns>
        public List<RB_MiAi_FollowMember_Extend> GetFollowMemberPageList(int pageIndex, int pageSize, out long rowsCount, RB_MiAi_FollowMember_Extend where)
        {
            var list = miai_FollowMemberRepository.GetFollowMemberPageList(pageIndex, pageSize, out rowsCount, where);

            if (list != null && list.Any())
            {
                string createByIds = string.Join(",", list.Select(x => x.UserId));
                var fansList = miai_FollowMemberRepository.GetFollowMemberList(new RB_MiAi_FollowMember_Extend { TenantId = where.TenantId, MallBaseId = where.MallBaseId, UserId = where.CreateBy, CreateByIds = createByIds });
                foreach (var item in list)
                {
                    item.IsMutualFollow = fansList.Where(x => x.CreateBy == item.UserId).Count();
                    if (item.IsMutualFollow > 0)
                    {
                        item.MutualFollowId = fansList.Where(x => x.CreateBy == item.UserId).FirstOrDefault().ID;
                    }

                }
            }
            return list;
        }

        /// <summary>
        /// 我的粉丝分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="where"></param>
        /// <returns></returns>
        public List<RB_MiAi_FollowMember_Extend> GetFollowFansPageList(int pageIndex, int pageSize, out long rowsCount, RB_MiAi_FollowMember_Extend where)
        {
            var list = miai_FollowMemberRepository.GetFollowFansPageList(pageIndex, pageSize, out rowsCount, where);
            if (list != null && list.Any())
            {
                string createByIds = string.Join(",", list.Select(x => x.CreateBy));
                var fansList = miai_FollowMemberRepository.GetFollowMemberList(new RB_MiAi_FollowMember_Extend { TenantId = where.TenantId, MallBaseId = where.MallBaseId, CreateBy = where.UserId, UserIds = createByIds });
                foreach (var item in list)
                {
                    item.IsMutualFollow = fansList.Where(x => x.UserId == item.CreateBy).Count();
                    if (item.IsMutualFollow > 0)
                    {
                        item.MutualFollowId = fansList.Where(x => x.UserId == item.CreateBy).FirstOrDefault().ID;
                    }
                }
            }
            return list;
        }



        #endregion

    }
}
