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;

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();


        #region 活动版块
        /// <summary>
        /// 获取活动版块列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetForumList()
        {
            var req = base.RequestParm;
            var userInfo = AppletUserInfo;
            RB_Miai_Forum_Extend demodel = JsonConvert.DeserializeObject<RB_Miai_Forum_Extend>(req.msg.ToString());

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.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]
        public ApiResult GetActivityPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Miai_Activity_Extend demodel = JsonConvert.DeserializeObject<RB_Miai_Activity_Extend>(parms.msg.ToString());
            if (demodel.ForumId <= 0)
            {
                return ApiResult.ParamIsNull("请传递版块id");
            }
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.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,
                Deadline = x.Deadline.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]
        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();
            }

            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.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 });
                    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);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <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]
        public ApiResult GetActivityDiscussPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            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.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.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]
        public ApiResult GetActivityReplyPageList()
        {

            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            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.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.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 });
                    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")
            });
            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,
                    Deadline = x.ActivityModel?.Deadline.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>
        /// <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 (string.IsNullOrWhiteSpace(baseInfo.IDCardNo))
            {
                return ApiResult.Failed("请填写身份证号");
            }
            if (string.IsNullOrWhiteSpace(baseInfo.RealName))
            {
                return ApiResult.Failed("请填写姓名");
            }
            if (string.IsNullOrWhiteSpace(baseInfo.IDCard))
            {
                return ApiResult.Failed("请上传身份证头像面");
            }
            if (string.IsNullOrWhiteSpace(baseInfo.IDCardBack))
            {
                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("基础资料填写失败");
            }
        }

        /// <summary>
        /// 生肖
        /// </summary>
        /// <param name="birthday"></param>
        /// <returns></returns>
        public string GetShengXiao(DateTime birthday)
        {
            System.Globalization.ChineseLunisolarCalendar chinseCaleander = new System.Globalization.ChineseLunisolarCalendar();

            string TreeYear = "鼠牛虎兔龙蛇马羊猴鸡狗猪";

            int intYear = chinseCaleander.GetSexagenaryYear(birthday);

            string Tree = TreeYear.Substring(chinseCaleander.GetTerrestrialBranch(intYear) - 1, 1);

            return Tree;
        }

        /// <summary>
        /// 获取星座
        /// </summary>
        /// <param name="birthday"></param>
        /// <returns></returns>
        public string GetAtomFromBirthday(DateTime birthday)
        {
            float birthdayF = 0.00F;

            if (birthday.Month == 1 && birthday.Day < 20)
            {
                birthdayF = float.Parse(string.Format("13.{0}", birthday.Day));
            }
            else
            {
                birthdayF = float.Parse(string.Format("{0}.{1}", birthday.Month, birthday.Day));
            }
            float[] atomBound = { 1.20F, 2.20F, 3.21F, 4.21F, 5.21F, 6.22F, 7.23F, 8.23F, 9.23F, 10.23F, 11.21F, 12.22F, 13.20F };
            string[] atoms = { "水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "魔羯座" };

            string ret = "靠！外星人啊。";
            for (int i = 0; i < atomBound.Length - 1; i++)
            {
                if (atomBound[i] <= birthdayF && atomBound[i + 1] > birthdayF)
                {
                    ret = atoms[i];
                    break;
                }
            }
            return ret;
        }


        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-互相关注
            if (userId == 0)
            {
                userId = userInfo.UserId;
                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 (oldList != null && oldList.Any() && oldOtherList != null && oldOtherList.Any())
                {
                    isFollow = 3;
                }
                else if (oldList != null && oldList.Any())
                {
                    isFollow = 1;
                }
                else if (oldOtherList != null && oldOtherList.Any())
                {
                    isFollow = 2;
                }
                else
                {
                    isFollow = 0;
                }
            }
            var oldBaseInfo = miaiModule.GetBaseInfoList(new RB_MiAi_BaseInfo_Extend { UserId = userId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            if (oldBaseInfo != null && oldBaseInfo.Id > 0)
            {
                oldBaseInfo.AlbumList = new List<string>();
                if (!string.IsNullOrWhiteSpace(oldBaseInfo.Album))
                {
                    oldBaseInfo.AlbumList = JsonConvert.DeserializeObject<List<string>>(oldBaseInfo.Album);
                }
                var result = new
                {
                    IsFollow = isFollow,
                    oldBaseInfo.Sex,
                    oldBaseInfo.IDCardNo,
                    oldBaseInfo.RealName,
                    oldBaseInfo.IDCard,
                    oldBaseInfo.IDCardBack,
                    SexStr = oldBaseInfo.Sex == 1 ? "男" : "女",
                    oldBaseInfo.Birthday,
                    Age = string.IsNullOrWhiteSpace(oldBaseInfo.Birthday) ? "" : StringHelper.GetAge(oldBaseInfo.Birthday),//年纪
                    ShenXiao = string.IsNullOrWhiteSpace(oldBaseInfo.Birthday) ? "" : GetShengXiao(Convert.ToDateTime((oldBaseInfo.Birthday))),//生肖
                    ConoldBaseInfostellation = string.IsNullOrWhiteSpace(oldBaseInfo.Birthday) ? "" : GetAtomFromBirthday(Convert.ToDateTime((oldBaseInfo.Birthday))),//星座
                    oldBaseInfo.Height,
                    oldBaseInfo.Weight,
                    Marriage = (oldBaseInfo.Marriage.HasValue && oldBaseInfo.Marriage.Value > 0) ? EnumHelper.GetEnumName(oldBaseInfo.Marriage) : "",
                    EducationType = (oldBaseInfo.EducationType.HasValue && oldBaseInfo.EducationType.Value > 0) ? EnumHelper.GetEnumName(oldBaseInfo.EducationType) : "",
                    YearMoney = oldBaseInfo.YearMoney ?? "",
                    HuKou = oldBaseInfo.HuKou ?? "",
                    NativePlace = oldBaseInfo.NativePlace ?? "",
                    HouseInfo = oldBaseInfo.HouseInfo ?? "",
                    SchoolInfo = oldBaseInfo.SchoolInfo ?? "",
                    MotherInfo = oldBaseInfo.MotherInfo ?? "",
                    FatherInfo = oldBaseInfo.FatherInfo ?? "",
                    Job = oldBaseInfo.Job ?? "",
                    OtherPople = oldBaseInfo.OtherPople ?? "",
                    MajorInfo = oldBaseInfo.MajorInfo ?? "",
                    CarInfo = oldBaseInfo.CarInfo ?? "",
                    About = oldBaseInfo.About ?? "",
                    IdealLove = oldBaseInfo.IdealLove ?? "",
                    oldBaseInfo.AlbumList
                };
                return ApiResult.Success("", result);
            }
            else
            {
                return ApiResult.Failed("用户暂未认证");
            }
        }



        /// <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
            {

                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("文字和文件不能同时为空");
            }
            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("发布失败");
            }
        }
        #endregion

     
    }
}