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_BaseInfoRepository miai_BaseInfoRepository = new RB_MiAi_BaseInfoRepository();


        private readonly RB_MiAi_FollowMemberRepository miai_FollowMemberRepository = new RB_MiAi_FollowMemberRepository();

        #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);
                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;
                }
            }
            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());
            return new
            {
                model.Id,
                model.ActivityTitle,
                model.Content,
                ImageList = !string.IsNullOrEmpty(model.Images) ? JsonConvert.DeserializeObject<List<string>>(model.Images) : new List<string>() { },
                model.UserId,
                Deadline = model.Deadline.ToString("yyyy-MM-dd"),
                CreateDate = model.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                PeopleNum,
                IsEnroll,
                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.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);
            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;
                }
            }
            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);
            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);
            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)
        {
            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.Deadline <= DateTime.Now) {
                return "已过了报名时间，无法报名";
            }
            return miai_ActivityEnrollRepository.Insert(demodel) > 0;
        }

        /// <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 "没有取消权限"; }
            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 ? "" : "出错了，请联系管理员";
        }
        #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;
            }
            return flag;
        }
        #endregion

        #region 我的粉丝/我的关注
        /// <summary>
        /// 新增/修改我关注的会员配置
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddOrUpdateFollowMember(RB_MiAi_FollowMember model)
        {
            bool flag = false;
            try
            {

                if (model.ID == 0)
                {
                    flag = miai_FollowMemberRepository.Insert(model) > 0;
                }
                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
                        }
                    };
                    flag = miai_FollowMemberRepository.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

    }
}
