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;

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();
        #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.Content,
                x.ImageList,
                x.ReplyNum,
                Deadline = x.Deadline.ToString("yyyy-MM-dd"),
                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;
            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("请重新选择报名截止日期");
            }
            demodel.ImageList ??= new List<string>();
            demodel.Images = JsonConvert.SerializeObject(demodel.ImageList);
            demodel.Deadline = Convert.ToDateTime(demodel.Deadline.ToString("yyyy-MM-dd") + " 23:59:59");
            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.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;
            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("请传递内容");
            }
            
            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);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.UserId,
                x.UserName,
                x.Photo,
                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");
            }

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

        #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.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("请上传身份证国徽面");
            }
            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)
            {
                if (miaiModule.SetMiAiBaseInfo(baseInfo))
                {
                    return ApiResult.Success("基础资料填写成功");
                }
                else
                {
                    return ApiResult.Failed("基础资料填写失败");
                }
            }
            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 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);
                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
    }
}