using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Mall.Common.API;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Mall.Common.Plugin;
using Mall.CacheManager.User;
using Newtonsoft.Json.Linq;
using Mall.Common;
using Mall.AOP;
using Mall.Module.Miai;
using Mall.Model.Extend.Miai;
using Mall.Model.Entity.Education;
using Mall.Model.Extend.Education;
using Mall.Module.User;
using Microsoft.AspNetCore.Authorization;

namespace Mall.WebApi.Controllers.MallBase
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class AppletMiaiController : BaseController
    {
        private readonly MiaiModule miaiModule = new MiaiModule();
        private readonly Module.Education.DynamicModule dynamicModule = new Module.Education.DynamicModule();
        private readonly MiniProgramModule programModule = new MiniProgramModule();
        private readonly MiniProgramMsgModule programMsgModule = new MiniProgramMsgModule();
        private readonly Module.Education.EducationModule educationModule = new Module.Education.EducationModule();
        /// <summary>
        /// 通用方法
        /// </summary>
        private readonly MiaiCommonModule miaiCommonModule = new MiaiCommonModule();

        #region 活动版块
        /// <summary>
        /// 获取活动版块列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetForumList()
        {
            var req = base.RequestParm;
            RB_Miai_Forum_Extend demodel = JsonConvert.DeserializeObject<RB_Miai_Forum_Extend>(req.msg.ToString());
            demodel.MallBaseId = req.MallBaseId;
            demodel.IsShow = 1;
            var list = miaiModule.GetForumList(demodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Icon,
                x.Sort,
                x.IsShow,
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss")
            }));
        }

        /// <summary>
        /// 获取活动分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetActivityPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Miai_Activity_Extend demodel = JsonConvert.DeserializeObject<RB_Miai_Activity_Extend>(parms.msg.ToString());
            demodel.MallBaseId = parms.MallBaseId;
            var list = miaiModule.GetActivityPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.ActivityTitle,
                x.UserId,
                x.UserName,
                x.Photo,
                x.Sex,
                x.Content,
                x.ImageList,
                x.ReplyNum,
                x.EnrollNum,
                x.IsOpenEnroll,
                x.Label,
                StartTime = x.StartTime.ToString("yyyy-MM-dd HH:mm"),
                EndTime = x.EndTime.ToString("yyyy-MM-dd HH:mm"),
                x.ManNum,
                x.WoManNum,
                x.LonLat,
                x.LocationName,
                x.ForumId,
                x.ForumName,
                x.ForumIcon,
                Deadline = x.IsOpenEnroll == 1 ? x.Deadline.Value.ToString("yyyy-MM-dd HH:mm") : "",
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss")
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取活动信息（包含报名人数）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetActivityInfo()
        {
            var userInfo = AppletUserInfo;
            var parms = JObject.Parse(RequestParm.msg.ToString());
            int ActivityId = parms.GetInt("ActivityId", 0);
            if (ActivityId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            if (userInfo == null)
            {
                userInfo = new AppletUserInfo
                {
                    UserId = 0,
                    MallBaseId = RequestParm.MallBaseId
                };
            }
            var obj = miaiModule.GetActivityInfo(ActivityId, userInfo);
            return ApiResult.Success("", obj);
        }

        /// <summary>
        /// 发布招募贴
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetActivityInfo()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            AppletUserInfo uInfo = UserReidsCache.GetAppletUserBlacklistInfo(userInfo.UserId);
            if ((uInfo?.Blacklist ?? 0) == 1)
            {
                return ApiResult.Failed("已进入黑名单，无法访问");
            }
            RB_Miai_Activity_Extend demodel = JsonConvert.DeserializeObject<RB_Miai_Activity_Extend>(parms.msg.ToString());
            if (demodel.ForumId <= 0)
            {
                return ApiResult.ParamIsNull("请传递版块id");
            }
            if (string.IsNullOrEmpty(demodel.ActivityTitle))
            {
                return ApiResult.ParamIsNull("请传递标题名称");
            }
            if (string.IsNullOrEmpty(demodel.Content))
            {
                return ApiResult.ParamIsNull("请传递内容");
            }
            if (demodel.IsOpenEnroll == 1)
            {
                if (demodel.Deadline < DateTime.Now)
                {
                    return ApiResult.ParamIsNull("请重新选择报名截止日期");
                }
            }

            #region 内容是否违规
            try
            {
                var miniModel = programModule.GetMiniProgramModule(new Model.Extend.User.RB_MiniProgram_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
                int violationNum = programMsgModule.CheckViolation(miniModel, demodel.ActivityTitle);
                int violationNum2 = programMsgModule.CheckViolation(miniModel, demodel.Content);
                if (violationNum == 0 || violationNum2 == 0)
                {
                    return ApiResult.Failed("评论内容检测失败，请稍后再试");
                }
                else if (violationNum == 1 || violationNum2 == 1)
                {
                    var violationLogList = programMsgModule.GetViolationLogList(new RB_Education_ViolationLog { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId });
                    if (violationLogList != null && violationLogList.Any() && violationLogList.Count() >= 1)
                    {
                        userInfo = new AppletUserInfo
                        {
                            MallBaseId = uInfo.MallBaseId,
                            UserId = uInfo.UserId,
                            TenantId = uInfo.TenantId,
                            Name = uInfo.Name,
                            SuperiorId = uInfo.SuperiorId,
                            Blacklist = 1
                        };
                        CacheManager.User.UserReidsCache.AppletUserInfoSet(CacheKey.UserModuleCacheKeyConfig.Applet_Blacklist_Info + uInfo.UserId, userInfo, Config.JwtExpirTime);
                        programMsgModule.UpdateUserBlacklist(userInfo.TenantId, userInfo.MallBaseId, userInfo.UserId);
                    }
                    programMsgModule.SetEducationViolationLog(new RB_Education_ViolationLog { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId, ViolationType = 3, CreateDate = System.DateTime.Now });
                    miaiCommonModule.SetMessage(new RB_Miai_Message_Extend()
                    {
                        Id = 0,
                        Type = Common.Enum.MiAi.MessageTypeEnum.ViolationNotice,
                        UserId = userInfo.UserId,
                        SourceId = 0,
                        Content = "拼拼Plus发帖内容存在违规，若多次发布违规内容将被拉黑",
                        Status = 0,
                        TenantId = userInfo.TenantId,
                        MallBaseId = userInfo.MallBaseId,
                        CreateBy = userInfo.UserId,
                        CreateDate = DateTime.Now,
                        UpdateDate = DateTime.Now
                    });
                    return ApiResult.Failed("评论存在违规内容，若多次发布违规内容将被拉黑");
                }
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SetActivityInfo");
                return ApiResult.Failed("评论内容检测失败，请稍后再试");
            }
            #endregion

            demodel.ImageList ??= new List<string>();
            demodel.Images = JsonConvert.SerializeObject(demodel.ImageList);
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.Status = 0;
            demodel.UserId = userInfo.UserId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            bool flag = miaiModule.SetActivityInfo(demodel, out string msg);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 删除招募贴
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelActivityInfo()
        {
            var userInfo = AppletUserInfo;
            var parms = JObject.Parse(RequestParm.msg.ToString());
            int ActivityId = parms.GetInt("ActivityId", 0);
            if (ActivityId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            string msg = miaiModule.DelActivityInfo(ActivityId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取活动评论分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetActivityDiscussPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Miai_ActivityDiscuss_Extend demodel = JsonConvert.DeserializeObject<RB_Miai_ActivityDiscuss_Extend>(parms.msg.ToString());
            if (demodel.ActivityId <= 0)
            {
                return ApiResult.ParamIsNull("请传递活动id");
            }
            demodel.MallBaseId = parms.MallBaseId;
            var list = miaiModule.GetActivityDiscussPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.UserId,
                x.UserName,
                x.Photo,
                x.Sex,
                x.Content,
                x.ImageList,
                ReplyList = x.ReplyList.Select(z => new
                {
                    z.Id,
                    z.UserId,
                    z.UserName,
                    z.Photo,
                    z.Content,
                    z.ImageList,
                    z.ReplyUserId,
                    z.ReplyUserName,
                    CreateDate = z.CreateDate.ToString("yyyy-MM-dd HH:mm:ss")
                }),
                x.ReplyNum,
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss")
            });
            return ApiResult.Success("", pagelist);
        }



        /// <summary>
        /// 获取活动评论分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetActivityDiscussCount()
        {
            var parms = RequestParm;

            RB_Miai_ActivityDiscuss_Extend demodel = JsonConvert.DeserializeObject<RB_Miai_ActivityDiscuss_Extend>(parms.msg.ToString());
            if (demodel.ActivityId <= 0)
            {
                return ApiResult.ParamIsNull("请传递活动id");
            }
            demodel.MallBaseId = parms.MallBaseId;
            var list = miaiModule.GetActivityDiscussList(demodel);

            return ApiResult.Success("", new { totalCount = list.Count() });
        }



        /// <summary>
        /// 获取活动回复分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetActivityReplyPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Miai_ActivityDiscuss_Extend demodel = JsonConvert.DeserializeObject<RB_Miai_ActivityDiscuss_Extend>(parms.msg.ToString());
            if (demodel.ParentId <= 0)
            {
                return ApiResult.ParamIsNull("请传递上级id");
            }
            demodel.MallBaseId = parms.MallBaseId;
            var list = miaiModule.GetActivityReplyPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.UserId,
                x.UserName,
                x.Photo,
                x.Content,
                x.ImageList,
                x.ReplyUserId,
                x.ReplyUserName,
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss")
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 设置评论
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SgetActivityDiscussInfo()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            AppletUserInfo uInfo = UserReidsCache.GetAppletUserBlacklistInfo(userInfo.UserId);
            if ((uInfo?.Blacklist ?? 0) == 1)
            {
                return ApiResult.Failed("已进入黑名单，无法访问");
            }
            RB_Miai_ActivityDiscuss_Extend demodel = JsonConvert.DeserializeObject<RB_Miai_ActivityDiscuss_Extend>(parms.msg.ToString());
            if (demodel.ActivityId <= 0)
            {
                return ApiResult.ParamIsNull("请传递活动id");
            }
            if (string.IsNullOrEmpty(demodel.Content))
            {
                return ApiResult.ParamIsNull("请传递内容");
            }

            #region 内容是否违规
            try
            {
                var miniModel = programModule.GetMiniProgramModule(new Model.Extend.User.RB_MiniProgram_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
                int violationNum = programMsgModule.CheckViolation(miniModel, demodel.Content);
                if (violationNum == 0)
                {
                    return ApiResult.Failed("评论内容检测失败，请稍后再试");
                }
                else if (violationNum == 1)
                {
                    var violationLogList = programMsgModule.GetViolationLogList(new RB_Education_ViolationLog { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId });
                    if (violationLogList != null && violationLogList.Any() && violationLogList.Count() >= 1)
                    {
                        userInfo = new AppletUserInfo
                        {
                            MallBaseId = uInfo.MallBaseId,
                            UserId = uInfo.UserId,
                            TenantId = uInfo.TenantId,
                            Name = uInfo.Name,
                            SuperiorId = uInfo.SuperiorId,
                            Blacklist = 1
                        };
                        CacheManager.User.UserReidsCache.AppletUserInfoSet(CacheKey.UserModuleCacheKeyConfig.Applet_Blacklist_Info + uInfo.UserId, userInfo, Config.JwtExpirTime);
                        programMsgModule.UpdateUserBlacklist(userInfo.TenantId, userInfo.MallBaseId, userInfo.UserId);
                    }
                    programMsgModule.SetEducationViolationLog(new RB_Education_ViolationLog { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId, ViolationType = 3, CreateDate = System.DateTime.Now });
                    miaiCommonModule.SetMessage(new RB_Miai_Message_Extend()
                    {
                        Id = 0,
                        Type = Common.Enum.MiAi.MessageTypeEnum.ViolationNotice,
                        UserId = userInfo.UserId,
                        SourceId = 0,
                        Content = "拼拼Puls评论内容存在违规，若多次发布违规内容将被拉黑",
                        Status = 0,
                        TenantId = userInfo.TenantId,
                        MallBaseId = userInfo.MallBaseId,
                        CreateBy = userInfo.UserId,
                        CreateDate = DateTime.Now,
                        UpdateDate = DateTime.Now
                    });
                    return ApiResult.Failed("评论存在违规内容，若多次发布违规内容将被拉黑");
                }
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SetActivityInfo");
                return ApiResult.Failed("评论内容检测失败，请稍后再试");
            }
            #endregion

            demodel.ImageList ??= new List<string>();
            demodel.Images = JsonConvert.SerializeObject(demodel.ImageList);
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.Status = 0;
            demodel.UserId = userInfo.UserId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            bool flag = miaiModule.SetActivityDiscussInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除评论
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelActivityDiscussInfo()
        {
            var userInfo = AppletUserInfo;
            var parms = JObject.Parse(RequestParm.msg.ToString());
            int DiscussId = parms.GetInt("DiscussId", 0);
            if (DiscussId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            string msg = miaiModule.DelActivityDiscussInfo(DiscussId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取活动报名分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetActivityEnrollPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Miai_ActivityEnroll_Extend demodel = JsonConvert.DeserializeObject<RB_Miai_ActivityEnroll_Extend>(parms.msg.ToString());
            if (demodel.ActivityId <= 0)
            {
                return ApiResult.ParamIsNull("请传递活动id");
            }
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = miaiModule.GetActivityEnrollPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel, userInfo);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.UserId,
                x.UserName,
                x.Photo,
                x.Sex,
                x.Name,
                x.Mobile,
                x.PeopleNum,
                x.Remark,
                x.IsFocus,
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                x.MyFollowId,
                x.OtherFollowId
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 设置报名
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetActivityEnrollInfo()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Miai_ActivityEnroll_Extend demodel = JsonConvert.DeserializeObject<RB_Miai_ActivityEnroll_Extend>(parms.msg.ToString());
            if (demodel.ActivityId <= 0)
            {
                return ApiResult.ParamIsNull("请传递活动id");
            }
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请传递姓名");
            }
            if (string.IsNullOrEmpty(demodel.Mobile))
            {
                return ApiResult.ParamIsNull("请传递手机号码");
            }

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.Status = 0;
            demodel.UserId = userInfo.UserId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            string msg = miaiModule.SetActivityEnrollInfo(demodel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 取消报名
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult CancelActivityEnrollInfo()
        {
            var userInfo = AppletUserInfo;
            var parms = JObject.Parse(RequestParm.msg.ToString());
            int EnrollId = parms.GetInt("EnrollId", 0);
            if (EnrollId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            string msg = miaiModule.CancelActivityEnrollInfo(EnrollId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取我的帖子报名列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMyEnrollPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Miai_ActivityEnroll_Extend demodel = JsonConvert.DeserializeObject<RB_Miai_ActivityEnroll_Extend>(parms.msg.ToString());
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            var list = miaiModule.GetMyEnrollPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.UserId,
                x.Name,
                x.Mobile,
                x.PeopleNum,
                x.Remark,
                x.Status,
                ActivityModel = new
                {
                    x.ActivityModel?.Id,
                    x.ActivityModel?.ActivityTitle,
                    x.ActivityModel?.UserId,
                    x.ActivityModel?.UserName,
                    x.ActivityModel?.Photo,
                    x.ActivityModel?.Sex,
                    x.ActivityModel?.Content,
                    x.ActivityModel?.ImageList,
                    x.ActivityModel?.EnrollNum,
                    x.ActivityModel?.IsOpenEnroll,
                    Deadline = x.ActivityModel?.IsOpenEnroll == 1 ? x.ActivityModel?.Deadline.Value.ToString("yyyy-MM-dd") : "",
                    x.ActivityModel?.Status
                },
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss")
            });
            return ApiResult.Success("", pagelist);
        }

        #endregion

        #region 通知消息

        /// <summary>
        /// 获取消息分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMiaiMessagePageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Miai_Message_Extend demodel = JsonConvert.DeserializeObject<RB_Miai_Message_Extend>(parms.msg.ToString());
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            var list = miaiModule.GetMiaiMessagePageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Type,
                TypeName = x.Type.GetEnumName(),
                x.SourceId,
                x.Content,
                x.Name,
                x.Photo,
                x.Sex,
                x.ReplyContent,
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:mm")
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取消息中心
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMiaiMessageCenter()
        {
            var userInfo = AppletUserInfo;
            var list = miaiModule.GetMiaiMessageCenter(userInfo.UserId, userInfo.TenantId, userInfo.MallBaseId);
            return ApiResult.Success("", list);
        }

        /// <summary>
        /// 获取访客统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMiaiMessageVisitorStatistics()
        {
            var userInfo = AppletUserInfo;
            var parms = JObject.Parse(RequestParm.msg.ToString());
            int Type = parms.GetInt("Type", 1);// 类型  1谁看过我   2我看过谁

            var list = miaiModule.GetMiaiMessageVisitorStatistics(userInfo.UserId, Type, userInfo.TenantId, userInfo.MallBaseId);
            return ApiResult.Success("", list);
        }

        /// <summary>
        /// 获取访客分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMiaiMessageVisitorPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Miai_Message_Extend demodel = JsonConvert.DeserializeObject<RB_Miai_Message_Extend>(parms.msg.ToString());
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.SelectType = 3;
            if (demodel.VsisitorType == 1)
            {
                demodel.UserId = userInfo.UserId;
            }
            else
            {
                demodel.CreateBy = userInfo.UserId;
            }
            var list = miaiModule.GetMiaiMessageVisitorPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            //根据日期分组
            //List<string> DateList = list.Select(x => x.CreateDate.ToString("yyyy-MM-dd")).Distinct().ToList();
            //List<object> RList = new List<object>();
            //foreach (var item in DateList) {
            //    RList.Add(new
            //    {
            //        DateStr = item,
            //        List = list.Where(x => x.CreateDate.ToString("yyyy-MM-dd") == item).Select(x => new
            //        {
            //            x.Id,
            //            x.Type,
            //            TypeName = x.Type.GetEnumName(),
            //            UserId = demodel.VsisitorType == 1 ? x.CreateBy : x.UserId,
            //            UserName = x.Name,
            //            x.RealName,
            //            x.Photo,
            //            x.Sex,
            //            x.Status,
            //            CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:mm"),
            //            CreateDateDay = x.CreateDate.ToString("yyyy-MM-dd"),
            //            CreateDateHour = x.CreateDate.ToString("HH:mm")
            //        })
            //    });
            //}
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Type,
                TypeName = x.Type.GetEnumName(),
                UserId = demodel.VsisitorType == 1 ? x.CreateBy : x.UserId,
                UserName = x.Name,
                x.Photo,
                x.Sex,
                x.Status,
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:mm"),
                CreateDateDay = x.CreateDate.ToString("yyyy-MM-dd"),
                CreateDateHour = x.CreateDate.ToString("HH:mm")
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 删除单条消息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelMiaiMessageInfo()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            int MessageId = parms.GetInt("MessageId", 0);
            if (MessageId <= 0)
            {
                return ApiResult.Failed();
            }
            bool flag = miaiModule.DelMiaiMessageInfo(MessageId);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 批量删除消息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelMiaiMessageInfoBatch()
        {
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            string Type = parms.GetStringValue("TypeIds");// 0表示 清除所有的
            if (string.IsNullOrEmpty(Type)) { return ApiResult.ParamIsNull(); }
            bool flag = miaiModule.DelMiaiMessageInfoBatch(Type, userInfo);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        #endregion

        #region 相亲约会

        /// <summary>
        /// 获取我的相亲约会记录分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMiaiMyDatingPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Miai_Dating_Extend demodel = JsonConvert.DeserializeObject<RB_Miai_Dating_Extend>(parms.msg.ToString());
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            if (demodel.UserId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            var list = miaiModule.GetMiaiDatingPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.ManId,
                x.ManName,
                x.ManPhoto,
                x.WoManId,
                x.WoManName,
                x.WoManPhoto,
                Time = x.Time.ToString("yyyy-MM-dd HH:mm"),
                x.Address,
                x.Remark,
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss")
            });
            return ApiResult.Success("", pagelist);
        }

        #endregion

        #region 基础信息

        /// <summary>
        /// 填写个人基础信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSetMiAiBaseInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            AppletUserInfo uInfo = UserReidsCache.GetAppletUserBlacklistInfo(userInfo.UserId);
            if ((uInfo?.Blacklist ?? 0) == 1)
            {
                return ApiResult.Failed("已进入黑名单，无法访问");
            }

            RB_MiAi_BaseInfo_Extend baseInfo = JsonConvert.DeserializeObject<RB_MiAi_BaseInfo_Extend>(req.msg.ToString());
            baseInfo.Status = 0;
            baseInfo.CreateDate = DateTime.Now;
            baseInfo.UserId = userInfo.UserId;
            baseInfo.TenantId = userInfo.TenantId;
            baseInfo.MallBaseId = userInfo.MallBaseId;
            if (baseInfo.Sex == 0)
            {
                return ApiResult.Failed("请选择性别");
            }
            if (string.IsNullOrWhiteSpace(baseInfo.Birthday))
            {
                return ApiResult.Failed("请选择生日");
            }
            if (baseInfo.Weight == 0)
            {
                return ApiResult.Failed("请选择体重");
            }
            if (baseInfo.Height == 0)
            {
                return ApiResult.Failed("请选择身高");
            }

            if (!baseInfo.EducationType.HasValue || (int)baseInfo.EducationType == 0)
            {
                return ApiResult.Failed("请选择学历");
            }
            if (!baseInfo.Marriage.HasValue || (int)baseInfo.Marriage == 0)
            {
                return ApiResult.Failed("请选择婚姻状况");
            }

            if (baseInfo.AlbumList != null && baseInfo.AlbumList.Any())
            {
                baseInfo.Album = JsonConvert.SerializeObject(baseInfo.AlbumList);
            }
            else
            {
                baseInfo.Album = "";
            }
            var oldBaseInfo = miaiModule.GetBaseInfoList(new RB_MiAi_BaseInfo_Extend { UserId = baseInfo.UserId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            if (oldBaseInfo != null && oldBaseInfo.Id > 0)
            {
                baseInfo.Id = oldBaseInfo.Id;
            }
            if (miaiModule.SetMiAiBaseInfo(baseInfo))
            {
                return ApiResult.Success("基础资料填写成功");
            }
            else
            {
                return ApiResult.Failed("基础资料填写失败");
            }
        }

        [AllowAnonymous]
        [HttpPost]
        public ApiResult GetMiAiBaseIfo()
        {
            var req = RequestParm;
            JObject parm = JObject.Parse(req.msg.ToString());
            var userInfo = AppletUserInfo;
            int userId = parm.GetInt("UserId");
            int isFollow = -1;//-1 自己， 0-未关注,1-已关注，2-别人关注了你，3-互相关注

            int MyFollowId = 0;
            int OtherFollowId = 0;
            if (userInfo == null)
            {
                userInfo = new AppletUserInfo
                {
                    UserId = RequestParm.UserId,
                    MallBaseId = RequestParm.MallBaseId,
                    TenantId = RequestParm.TenantId
                };
            }
            if (userInfo != null && userInfo.UserId > 0)
            {
                var oldList = miaiModule.GetFollowMemberList(new RB_MiAi_FollowMember_Extend { Status = 0, UserId = userId, CreateBy = userInfo.UserId, MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId });
                var oldOtherList = miaiModule.GetFollowMemberList(new RB_MiAi_FollowMember_Extend { Status = 0, UserId = userInfo.UserId, CreateBy = userId, MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId });

                if (userId != userInfo.UserId)
                {
                    if (oldList != null && oldList.Any() && oldOtherList != null && oldOtherList.Any())
                    {
                        isFollow = 3;
                        MyFollowId = oldList.FirstOrDefault()?.ID ?? 0;
                        OtherFollowId = oldOtherList.FirstOrDefault()?.ID ?? 0;
                    }
                    else if (oldList != null && oldList.Any())
                    {
                        isFollow = 1;
                        MyFollowId = oldList.FirstOrDefault()?.ID ?? 0;
                    }
                    else if (oldOtherList != null && oldOtherList.Any())
                    {
                        isFollow = 2;
                        OtherFollowId = oldOtherList.FirstOrDefault()?.ID ?? 0;
                    }
                    else
                    {
                        isFollow = 0;
                    }

                    //设置消息推送
                    miaiCommonModule.SetMessage(new RB_Miai_Message_Extend()
                    {
                        Id = 0,
                        Type = Common.Enum.MiAi.MessageTypeEnum.Look,
                        UserId = userId,
                        SourceId = userId,
                        Content = "用户访问了您的自画像",
                        Status = 0,
                        TenantId = RequestParm.TenantId,
                        MallBaseId = RequestParm.MallBaseId,
                        CreateBy = userInfo.UserId,
                        CreateDate = DateTime.Now,
                        UpdateDate = DateTime.Now
                    });

                }
            }

            var oldUserInfo = miaiModule.GetMemberUserInfo(userId);
            var oldBaseInfo = miaiModule.GetBaseInfoModel(new RB_MiAi_BaseInfo_Extend { UserId = userId, TenantId = RequestParm.TenantId, MallBaseId = RequestParm.MallBaseId });



            if (oldUserInfo != null && oldUserInfo.Id > 0)
            {
                int IsAttestation = 0;
                if (oldBaseInfo != null && oldBaseInfo.Id > 0)
                {
                    oldBaseInfo.AlbumList = new List<string>();
                    if (!string.IsNullOrWhiteSpace(oldBaseInfo.Album))
                    {
                        oldBaseInfo.AlbumList = JsonConvert.DeserializeObject<List<string>>(oldBaseInfo.Album);
                    }
                    else
                    {
                        oldBaseInfo.AlbumList = new List<string>();
                    }
                    IsAttestation = 1;//已认证
                }
                else
                {
                    oldBaseInfo = new RB_MiAi_BaseInfo_Extend();
                }

                var result = new
                {
                    MyFollowId,
                    OtherFollowId,
                    oldUserInfo.Id,
                    oldUserInfo.Name,
                    oldUserInfo.Photo,
                    IsAttestation,
                    IsFollow = isFollow,
                    SexStr = (oldBaseInfo != null && oldBaseInfo.Id > 0) ? (oldBaseInfo.Sex == 1 ? "男" : "女") : "",
                    Birthday = oldBaseInfo.Birthday ?? "",
                    Sex = oldBaseInfo?.Sex ?? 0,
                    oldBaseInfo?.Height,
                    oldBaseInfo?.Weight,
                    EducationType = oldBaseInfo.EducationType ?? 0,
                    EducationTypeStr = (oldBaseInfo.EducationType.HasValue && oldBaseInfo.EducationType.Value > 0) ? EnumHelper.GetEnumName(oldBaseInfo.EducationType) : "",
                    SchoolInfo = oldBaseInfo.SchoolInfo ?? "",
                    Age = string.IsNullOrWhiteSpace(oldBaseInfo.Birthday) ? "" : StringHelper.GetAge(oldBaseInfo.Birthday),//年纪
                    ShenXiao = string.IsNullOrWhiteSpace(oldBaseInfo.Birthday) ? "" : StringHelper.GetShengXiao(Convert.ToDateTime((oldBaseInfo.Birthday))),//生肖
                    ConoldBaseInfostellation = string.IsNullOrWhiteSpace(oldBaseInfo.Birthday) ? "" : StringHelper.GetAtomFromBirthday(Convert.ToDateTime((oldBaseInfo.Birthday))),//星座
                    MarriageStr = (oldBaseInfo.Marriage.HasValue && oldBaseInfo.Marriage.Value > 0) ? EnumHelper.GetEnumName(oldBaseInfo.Marriage) : "",
                    Marriage = oldBaseInfo.Marriage ?? 0,
                    Job = oldBaseInfo.Job ?? "",
                    WorkUnit = oldBaseInfo?.WorkUnit ?? "",
                    YearMoney = oldBaseInfo.YearMoney ?? "",
                    CName = oldBaseInfo.CName ?? "",
                    DName = oldBaseInfo.DName ?? "",
                    PName = oldBaseInfo.PName ?? "",
                    Province = oldBaseInfo.Province ?? 0,
                    City = oldBaseInfo.City ?? 0,
                    District = oldBaseInfo.District ?? 0,
                    HouseInfo = oldBaseInfo.HouseInfo ?? "",
                    FamilyInfo = oldBaseInfo?.FamilyInfo ?? "",
                    Hobby = oldBaseInfo?.Hobby ?? "",
                    LikeFood = oldBaseInfo?.LikeFood ?? "",
                    LikeBook = oldBaseInfo.LikeBook ?? "",
                    LikeTV = oldBaseInfo.LikeTV ?? "",
                    LikeSong = oldBaseInfo.LikeSong ?? "",
                    IdealLove = oldBaseInfo.IdealLove ?? "",
                    LoveTalk = oldBaseInfo.LoveTalk ?? "",
                    SingleReason = oldBaseInfo.SingleReason ?? "",
                    HopeYou = oldBaseInfo.HopeYou ?? "",
                    About = oldBaseInfo.About ?? "",
                    Appointment = oldBaseInfo.Appointment ?? "",
                    AppointmentAddress = oldBaseInfo.AppointmentAddress ?? "",
                    oldBaseInfo.AlbumList
                };
                return ApiResult.Success("", result);
            }
            else
            {
                return ApiResult.Failed("用户信息不存在");
            }
        }




        /// <summary>
        /// 获取会员基础信息
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ApiResult GetBaseInfoPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_MiAi_BaseInfo_Extend demodel = JsonConvert.DeserializeObject<RB_MiAi_BaseInfo_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.UserId = parms.UserId;

            int Sex = 0;
            int Age = 0;
            if (demodel.UserId > 0)//说明用户登录了的
            {
                //查看用户的
                var baseInfo = miaiModule.GetBaseInfoList(new Model.Extend.Miai.RB_MiAi_BaseInfo_Extend { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserId = demodel.UserId }).FirstOrDefault();
                if (baseInfo != null)
                {
                    Sex = baseInfo.Sex;
                    if (!string.IsNullOrWhiteSpace(baseInfo.Birthday))
                    {
                        try
                        {
                            Age = Convert.ToInt32(Common.Plugin.StringHelper.GetAge(baseInfo.Birthday));
                        }
                        catch (Exception)
                        {

                            Age = 0;
                        }
                    }
                }
                if (demodel.Sex > 0)
                {
                    demodel.Sex = demodel.Sex == 1 ? 2 : (demodel.Sex == 2 ? 1 : 0);
                }
            }
            var list = miaiModule.GetFirstBaseInfoPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);

            List<Model.Extend.MarketingCenter.miaiUserDetail> newGoodsList = new List<Model.Extend.MarketingCenter.miaiUserDetail>();
            foreach (var tempGood in list)
            {
                var lastItem = new Model.Extend.MarketingCenter.miaiUserDetail();
                //  var tempGood = tempGoodsList?.Where(qitem => qitem.UserId == goodItem.id)?.FirstOrDefault();
                if (tempGood != null && tempGood.Id > 0)
                {
                    lastItem.id = tempGood.UserId;
                    lastItem.name = tempGood.Name;
                    lastItem.Photo = tempGood.Photo;
                    lastItem.SexStr = tempGood.Sex == 1 ? "男" : "女";
                    lastItem.Age = tempGood.Age.ToString();
                    lastItem.Marriage = (tempGood.Marriage.HasValue && tempGood.Marriage.Value > 0) ? Common.Plugin.EnumHelper.GetEnumName(tempGood.Marriage) : "";
                    lastItem.Education = (tempGood.EducationType.HasValue && tempGood.EducationType.Value > 0) ? Common.Plugin.EnumHelper.GetEnumName(tempGood.EducationType) : "";

                    if (demodel.UserId > 0 && Age > 0)
                    {
                        if (Age == tempGood.Age)
                        {
                            lastItem.MatchingRate = 90;
                        }
                        else if (Age > tempGood.Age)
                        {
                            lastItem.MatchingRate = ((Age - tempGood.Age) + 90) > 100 ? 100 : ((Age - tempGood.Age) + 90);
                        }
                        else if (Age < tempGood.Age)
                        {
                            lastItem.MatchingRate = (90 - (tempGood.Age - Age)) < 0 ? 0 : (90 - (tempGood.Age - Age));
                        }
                        else
                        {
                            lastItem.MatchingRate = 0;
                        }
                    }
                    else
                    {
                        lastItem.MatchingRate = 0;
                    }
                    lastItem.Score = 0;
                    lastItem.Album = tempGood.Album;
                    if (!string.IsNullOrWhiteSpace(lastItem.Album))
                    {
                        lastItem.AlbumList = JsonConvert.DeserializeObject<List<string>>(lastItem.Album);
                    }
                    newGoodsList.Add(lastItem);
                }
            }
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = newGoodsList;
            return ApiResult.Success("", pagelist);
        }
        /// <summary>
        /// 获取教育枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetEducationTypeEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.MiAi.EducationTypeEnum));
            return ApiResult.Success("", list.OrderBy(x => Convert.ToInt32(x.Value)).Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 获取婚姻枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMarriageEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.MiAi.MarriageEnum));
            return ApiResult.Success("", list.OrderBy(x => Convert.ToInt32(x.Value)).Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }
        #endregion


        #region 我的粉丝/我的关注
        /// <summary>
        /// 我的关注
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetFollowTeacherPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_MiAi_FollowMember_Extend demodel = JsonConvert.DeserializeObject<RB_MiAi_FollowMember_Extend>(req.msg.ToString());
            demodel.CreateBy = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = miaiModule.GetFollowMemberPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.UserId,
                x.Name,
                x.Photo,
                x.CreateBy,
                x.IsMutualFollow,
                x.MutualFollowId,
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:ss:mm"),

            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 我的粉丝
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetFollowFansPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_MiAi_FollowMember_Extend demodel = JsonConvert.DeserializeObject<RB_MiAi_FollowMember_Extend>(req.msg.ToString());
            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = miaiModule.GetFollowFansPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.UserId,
                x.Name,
                x.Photo,
                x.CreateBy,
                x.IsMutualFollow,
                x.MutualFollowId,
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:ss:mm"),

            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 关注会员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetFollowMember()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            var query = JsonConvert.DeserializeObject<RB_MiAi_FollowMember>(RequestParm.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            query.CreateBy = userInfo.UserId;

            bool isUpdate = true;

            if (query == null)
            {
                return ApiResult.Failed("请传入我关注的会员信息");
            }
            else
            {
                if (query.UserId == userInfo.UserId)
                {
                    return ApiResult.Failed("关注对象不能是自己");
                }

                var oldBaseInfo = miaiModule.GetBaseInfoList(new RB_MiAi_BaseInfo_Extend { UserId = query.CreateBy, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
                if (oldBaseInfo == null || oldBaseInfo.Id == 0)
                {
                    return ApiResult.Failed("您未实名认证，无法关注");
                }

                oldBaseInfo = miaiModule.GetBaseInfoList(new RB_MiAi_BaseInfo_Extend { UserId = query.UserId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
                if (oldBaseInfo == null || oldBaseInfo.Id == 0)
                {
                    return ApiResult.Failed("会员未实名认证，无法关注");
                }


                //判断是否已经关注过
                var oldList = miaiModule.GetFollowMemberList(new RB_MiAi_FollowMember_Extend { Status = -1, UserId = query.UserId, CreateBy = query.CreateBy, MallBaseId = query.MallBaseId, TenantId = query.TenantId }); ;
                if (query.ID == 0)
                {
                    isUpdate = false;
                    query.CreateDate = System.DateTime.Now;
                    query.UpdateDate = System.DateTime.Now;
                    if (query.UserId <= 0)
                    {
                        return ApiResult.Failed("请传入我关注的会员信息");
                    }
                    if (oldList != null && oldList.Any(x => x.Status == 0))
                    {
                        return ApiResult.Failed("您已关注，请勿重复操作");
                    }
                    else
                    {
                        if (oldList != null && oldList.Any())
                        {
                            query.ID = oldList.OrderByDescending(x => x.CreateDate).FirstOrDefault().ID;
                        }
                        query.Status = 0;
                    }
                }
                else
                {
                    query.Status = 1;
                }

                bool result = miaiModule.AddOrUpdateFollowMember(query, oldBaseInfo);
                if (isUpdate)
                {
                    if (result)
                    {
                        return ApiResult.Success("取消关注成功");
                    }
                    else
                    {
                        return ApiResult.Failed("取消关注成功");
                    }
                }
                else
                {
                    if (result)
                    {
                        return ApiResult.Success("关注成功");
                    }
                    else
                    {
                        return ApiResult.Failed("关注成功");
                    }
                }
            }
        }
        #endregion

        #region 发布朋友圈
        /// <summary>
        /// 发布动态
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPublishDynamic()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            if (userInfo == null)
            {
                return ApiResult.Failed("请重新登录");
            }

            Rb_Education_Dynamic_Extend article = JsonConvert.DeserializeObject<Rb_Education_Dynamic_Extend>(req.msg.ToString());
            article.Content = StringHelper.UrlDecode(article.Content);
            if (string.IsNullOrWhiteSpace(article.Content) && (article.FileList == null || !article.FileList.Any()))
            {
                return ApiResult.Failed("文字和文件不能同时为空");
            }

            #region 内容是否违规
            if (!string.IsNullOrWhiteSpace(article.Content))
            {
                try
                { //获取订阅消息
                    var miniModel = programModule.GetMiniProgramModule(new Model.Extend.User.RB_MiniProgram_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
                    int violationNum = new MiniProgramMsgModule().CheckViolation(miniModel, article.Content);
                    if (violationNum == 0)
                    {
                        return ApiResult.Failed("发布内容检测失败，请稍后再试");
                    }
                    else if (violationNum == 1)
                    {
                        var violationLogList = educationModule.GetViolationLogList(new RB_Education_ViolationLog { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId });
                        if (violationLogList != null && violationLogList.Any() && (violationLogList.Count() + 1) >= miniModel.ViolationNum)
                        {
                            userInfo = new AppletUserInfo
                            {
                                MallBaseId = userInfo.MallBaseId,
                                UserId = userInfo.UserId,
                                TenantId = userInfo.TenantId,
                                Name = userInfo.Name,
                                SuperiorId = userInfo.SuperiorId,
                                Blacklist = 1
                            };
                            CacheManager.User.UserReidsCache.AppletUserInfoSet(CacheKey.UserModuleCacheKeyConfig.Applet_Blacklist_Info + userInfo.UserId, userInfo, Config.JwtExpirTime);
                            educationModule.UpdateUserBlacklist(userInfo.TenantId, userInfo.MallBaseId, userInfo.UserId);
                        }
                        educationModule.SetEducationViolationLog(new RB_Education_ViolationLog { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId, ViolationType = 1, CreateDate = System.DateTime.Now });
                        return ApiResult.Failed("发布内容存在违规信息，若多次发布违规内容将被拉黑");
                    }
                }
                catch (Exception ex)
                {
                    Common.Plugin.LogHelper.Write(ex, "InsertOrderPayInfo");
                    return ApiResult.Failed("发布内容检测失败，请稍后再试");
                }
            }

            #endregion
            article.CreateTime = DateTime.Now;
            article.CreateBy = userInfo.UserId;
            article.TenantId = userInfo.TenantId;
            article.MallBaseId = userInfo.MallBaseId;
            article.UserTeacher = userInfo.UserTeacher;
            article.CoverPhoto = "";
            if (article.FileList != null && article.FileList.Count() > 0)
            {
                article.Files = JsonConvert.SerializeObject(article.FileList);
                article.CoverPhoto = article.FileList[0];
            }
            else
            {
                article.FileType = 0;
            }
            article.Content = StringHelper.ToUnicodeString(article.Content);

            article.Status = 0;
            if (dynamicModule.PublishDynamic(article))
            {
                return ApiResult.Success("发布成功");
            }
            else
            {
                return ApiResult.Failed("发布失败");
            }
        }


        /// <summary>
        /// 动态列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMiAiDynamicDetial()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parm = JObject.Parse(req.msg.ToString());
            int articleId = parm.GetInt("articleId");
            if (articleId == 0)
            {
                return ApiResult.Failed("动态id不为空");
            }
            Rb_Education_Dynamic_Extend articele = dynamicModule.GetMiAiDynamicDetial(new Rb_Education_Dynamic_Extend { UserId = userInfo.UserId, Id = articleId });
            if (articele != null)
            {
                var data = DecoratorDynameicResult(articele);
                return ApiResult.Success(data: data);
            }
            else
            {
                return ApiResult.Failed("动态不存在");
            }
        }


        /// <summary>
        /// 返回动态详情
        /// </summary>
        /// <param name="article">动态内容</param>
        /// <returns></returns>

        public object DecoratorDynameicResult(Rb_Education_Dynamic_Extend article)
        {
            List<string> fileList = new List<string>();
            if (!string.IsNullOrEmpty(article.Files))
            {
                fileList = JsonConvert.DeserializeObject<List<string>>(article.Files);
            }
            //StringHelper.UrlEncode(StringHelper.FromUnicodeString(article.Content))
            var resultData = new { id = article.Id, createEmpId = article.CreateBy, article.TalkContent, article.TalkId, createEmName = article.CreateByName, crearteEmPhoto = article.CrearteByPhoto, YearTime = article.CreateTime.HasValue ? (article.CreateTime.Value.Year == System.DateTime.Now.Year ? "" : article.CreateTime.Value.ToString("yyyy")) : "", MonthTime = article.CreateTime.HasValue ? article.CreateTime.Value.ToString("MM") : "", DayTime = article.CreateTime.HasValue ? article.CreateTime.Value.ToString("dd") : "", createTime = article.CreateTime.HasValue ? StringHelper.DateFormatToString(article.CreateTime.Value) : "", content = StringHelper.FromUnicodeString(article.Content), coverPhoto = article.CoverPhoto, fileType = article.FileType, latAndLong = article.LatAndLong, address = article.Address, files = fileList, hasLike = article.HasLike, likeList = article.LikeList.Select(t => new { empId = t.UserId, empName = t.EmName, t.Id }), commentList = article.CommentList.Select(t => new { commentId = t.Id, empId = t.UserId, empName = t.UserName, byReplayEmpId = t.ByReplyEmpId, byReplayEmpName = t.ByReplyEmName, content = StringHelper.FromUnicodeString(t.Content) }) };
            return resultData;
        }
        #endregion


    }
}