using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Edu.Cache.User;
using Edu.Common.API;
using Edu.Common.Enum;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.LearningGarden;
using Edu.Module.Course;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace Edu.WebApi.Controllers.LearningGarden
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class SchoolGardenController : BaseController
    {
        /// <summary>
        /// 学习园地处理类对象
        /// </summary>
        private readonly LearningGardenModule learningGardenModule = AOP.AOPHelper.CreateAOPObject<LearningGardenModule>();



        #region 学习园地相关接口


        /// <summary>
        /// 获取学习园地分页
        /// </summary>
        /// <returns></returns>
        [HttpPost]

        public ApiResult GeLearningGardenPage()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_LearningGarden_ViewModel()
            {
                Title = base.ParmJObj.GetStringValue("Title"),
                Group_Id = base.ParmJObj.GetInt("Group_Id")
            };
            query.Status = DateStateEnum.Normal;
            query.Group_Id = base.UserInfo.Group_Id;
            var list = learningGardenModule.GetLearningGardenPageModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            List<object> resultList = new List<object>();
            foreach (var item in list)
            {
                string CreateByName = "甲鹤教育";
                if (item.CreateBy > 0)
                {
                    CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                }
                resultList.Add(new
                {
                    item.Id,
                    item.Title,
                    item.Content,
                    item.Img,
                    item.Digest,
                    item.LinkUrl,
                    CreateByName,
                    CreateTime = Common.Plugin.StringHelper.DateFormatToString(item.CreateDate)
                });
            }
            pageModel.Count = rowsCount;
            pageModel.PageData = resultList;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 获取学习园地详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetLearningGarden()
        {
            var Id = base.ParmJObj.GetInt("Id", 0);
            var extModel = learningGardenModule.GetLearningGardenModule(Id);
            object obj = new object();
            if (extModel != null && extModel.Id > 0)
            {
                string CreateByName = "甲鹤教育";
                if (extModel.CreateBy > 0)
                {
                    CreateByName = UserReidsCache.GetUserLoginInfo(extModel.CreateBy)?.AccountName ?? "";
                }
                obj = new
                {
                    extModel.Id,
                    extModel.Title,
                    extModel.Img,
                    extModel.Content,
                    extModel.Digest,
                    extModel.LinkUrl,
                    CreateByName,
                    CreateTime = Common.Plugin.StringHelper.DateFormatToString(extModel.CreateDate)
                };
            }
            return ApiResult.Success(data: obj);
        }

        /// <summary>
        /// 新增修改网站学习园地
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetLearningGarden()
        {
            var extModel = new RB_LearningGarden_ViewModel()
            {
                Id = base.ParmJObj.GetInt("Id"),
                Title = base.ParmJObj.GetStringValue("Title"),
                Img = base.ParmJObj.GetStringValue("Img"),
                Content = base.ParmJObj.GetStringValue("Content"),
                Digest = base.ParmJObj.GetStringValue("Digest"),
                LinkUrl = base.ParmJObj.GetStringValue("LinkUrl"),
            };
            extModel.School_Id = base.UserInfo.School_Id;
            extModel.Group_Id = base.UserInfo.Group_Id;
            extModel.CreateBy = base.UserInfo.Id;
            extModel.CreateDate = DateTime.Now;
            extModel.UpdateTime = DateTime.Now;
            extModel.Status = DateStateEnum.Normal;
            bool flag = learningGardenModule.SetLearningGardenModule(extModel);
            return flag ? ApiResult.Success(data: extModel) : ApiResult.Failed();
        }
        /// <summary>
        /// 修改网站学习园地状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult RemoveLearningGardenStatus()
        {
            var Id = base.ParmJObj.GetInt("Id", 0);
            var Status = base.ParmJObj.GetInt("Status", 0);
            var flag = learningGardenModule.RemoveLearningGardenStatusModule(Id, Status);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        #endregion


        #region 同步公众号的文章

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="cookie"></param>
        [HttpPost]
        public ApiResult GetGoodsData()
        {
            int pageIndex = 1;
            int pageSize = 20;
            int pageCount = 0;
            //获取token
            string tokenKey = Cache.CacheKey.DATA_WeChatAccountToken + Common.Config.WeChatAccountAppId;
            string token = Cache.WeChat.WeChatReidsCache2.GetToken(tokenKey);
            if (Common.Config.IsLocal == 1)
            {
                token = "53_OVLlSPNJ0hmSrsEUfnJ6kTxFRGxfkcuJJjpBjsDuaSGmtYu95vZNNyh-wIXbFSZ9DtxzFJ1eN0At2QmJ_aWLPFjz4yrz2VrWvmR3KrEQKqfwvxesG82V2WpAgDnxW_tvvWYXRRRX1oguxCtHXSShADAKFF";
            }
            if (string.IsNullOrEmpty(token))
            {
                token = Common.Plugin.WeChatHelper.GetAccessToken(Common.Config.WeChatAccountAppId, Common.Config.WeChatAccountAppSecret);
                Cache.WeChat.WeChatReidsCache2.Set(tokenKey, token);
            }
                                          
            var resultTotalCount = HttpHelper.HttpGet("https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=" + token);
            Common.Plugin.LogHelper.WriteInfo("GetGoodsData: " + resultTotalCount);
            JObject parm = JObject.Parse(resultTotalCount);

            List<WeChatLearningGardenItem> allList = new List<WeChatLearningGardenItem>();
            pageCount = parm.GetInt("news_count");//图文总数
            int dataCount = 1;
            while (dataCount>0)
            {
                string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                var tempImgList = GetGoodsList(pageIndex, pageSize);
                if (tempImgList != null && tempImgList.Any())
                {
                    allList.AddRange(tempImgList);
                }
                dataCount = tempImgList?.Count ?? 0;
                pageIndex++;
            }
 
            List<RB_LearningGarden_ViewModel> learningGardenList = new List<RB_LearningGarden_ViewModel>();

            //查询数据库信息
            List<RB_LearningGarden_ViewModel> oldLearningGardenList = new List<RB_LearningGarden_ViewModel>();
            oldLearningGardenList = learningGardenModule.GetLearningGardenListModule(new RB_LearningGarden_ViewModel { Group_Id = base.UserInfo.Group_Id });
            if (allList != null && allList.Any())
            {
                foreach (var item in allList)
                {
                    foreach (var itemNews in item.content.news_item)
                    {
                        RB_LearningGarden_ViewModel extModel = new RB_LearningGarden_ViewModel()
                        {
                            Id = 0,
                            WeChatAccountId = item.media_id,
                            Title = itemNews.title,
                            Img = itemNews.thumb_url,
                            Content = itemNews.content,
                            Digest = itemNews.digest,
                            LinkUrl = itemNews.url,
                            CreateDate = Convert.ToDateTime(GetTime(item.content.create_time)),
                            UpdateTime = Convert.ToDateTime(GetTime(item.content.update_time)),
                            Author = itemNews.author,
                            CreateBy = 0
                        };
                        //判断当前文章数据库离是否已存在
                        var nowLearningGardenModel = oldLearningGardenList.Where(x => x.WeChatAccountId == item.media_id).FirstOrDefault();
                        if (nowLearningGardenModel != null && nowLearningGardenModel.Id > 0)
                        {
                            extModel.Id = nowLearningGardenModel.Id;
                        }
                        extModel.School_Id = base.UserInfo.School_Id;
                        extModel.TypeId = "news";
                        extModel.Group_Id = base.UserInfo.Group_Id;
                        extModel.Status = DateStateEnum.Normal;
                        extModel.GardenType = Common.Enum.Course.LearningGardenTypeEnum.Japanese;//默认日语
                        learningGardenList.Add(extModel);
                    }
                }
            }
            learningGardenModule.SetBatchWebNewsModule(learningGardenList);
            return ApiResult.Success("");
        }


        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name="timeStamp">Unix时间戳格式</param>
        /// <returns>C#格式时间</returns>
        public static string GetTime(long timeStamp)
        {
            try
            {
                long begtime = timeStamp * 10000000;
                DateTime dt_1970 = new DateTime(1970, 1, 1, 0, 0, 0);
                long tricks_1970 = dt_1970.Ticks;//1970年1月1日刻度
                long time_tricks = tricks_1970 + begtime;//日志日期刻度
                DateTime dt = new DateTime(time_tricks);//转化为DateTime
                return dt.ToString("yyyy-MM-dd HH:mm:ss");
            }
            catch
            {
                return "";
            }
        }


        /// <summary>
        /// 获取公众号列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        static List<WeChatLearningGardenItem> GetGoodsList(int pageIndex, int pageSize)
        {
            string tokenKey = Cache.CacheKey.DATA_WeChatAccountToken + Common.Config.WeChatAccountAppId;
            string token = Cache.WeChat.WeChatReidsCache2.GetToken(tokenKey);
            if (Common.Config.IsLocal == 1)
            {
                token = "53_OVLlSPNJ0hmSrsEUfnJ6kTxFRGxfkcuJJjpBjsDuaSGmtYu95vZNNyh-wIXbFSZ9DtxzFJ1eN0At2QmJ_aWLPFjz4yrz2VrWvmR3KrEQKqfwvxesG82V2WpAgDnxW_tvvWYXRRRX1oguxCtHXSShADAKFF";
            }
            if (string.IsNullOrEmpty(token))
            {
                token = Common.Plugin.WeChatHelper.GetAccessToken(Common.Config.WeChatAccountAppId, Common.Config.WeChatAccountAppSecret);
                Cache.WeChat.WeChatReidsCache2.Set(tokenKey, token);
            }
            string newImaApi = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + token;
            List<WeChatLearningGardenItem> list = new List<WeChatLearningGardenItem>();
            var resultInfo = new
            {
                type = "news",
                offset = (pageIndex - 1) * pageSize,
                count = pageSize
            };
            string jsonData = HttpHelper.HttpPost(newImaApi, JsonHelper.Serialize(resultInfo), "");
            if (jsonData != null && !string.IsNullOrEmpty(jsonData))
            {
                JObject jObj = JObject.Parse(jsonData);
                var item = jObj.GetStringValue("item");
                if (!string.IsNullOrEmpty(item))
                {
                    JArray jArray = JArray.Parse(item);
                    if (jArray != null && jArray.Count > 0)
                    {
                        foreach (var jItem in jArray)
                        {
                            JObject sObj = JObject.Parse(jItem.ToString());
                            JObject dObj = JObject.Parse(sObj.GetStringValue("content"));
                            var newsItem = new List<WeChatLearningGardenNewsItem>();
                            JArray subArray = JArray.Parse(dObj.GetStringValue("news_item"));
                            if (subArray != null && subArray.Count > 0)
                            {
                                foreach (var sItem in subArray)
                                {
                                    var contentObj = JObject.Parse(sItem.ToString());
                                    newsItem.Add(new WeChatLearningGardenNewsItem()
                                    {
                                        title = contentObj.GetStringValue("title"),
                                        author = contentObj.GetStringValue("author"),
                                        digest = contentObj.GetStringValue("digest"),
                                        content = contentObj.GetStringValue("content"),
                                        show_cover_pic = contentObj.GetInt("show_cover_pic"),
                                        url = contentObj.GetStringValue("url"),
                                        thumb_url = contentObj.GetStringValue("thumb_url"),
                                    });
                                }
                            }
                            var content = new WeChatLearningGardenContent()
                            {
                                news_item = newsItem,
                                create_time = dObj.GetLong("create_time"),
                                update_time = dObj.GetLong("update_time"),
                            };
                            WeChatLearningGardenItem model = new WeChatLearningGardenItem()
                            {
                                media_id = sObj.GetStringValue("media_id"),
                                update_time = sObj.GetStringValue("update_time"),
                                content = content
                            };
                            list.Add(model);
                        }
                    }
                }
            }
            return list;
        }



        /// <summary>
        /// 获取成功发布列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        static List<WeChatLearningGardenItem> GetFreePublishList(int pageIndex, int pageSize)
        {
            string tokenKey = Cache.CacheKey.DATA_WeChatAccountToken + Common.Config.WeChatAccountAppId;
            string token = Cache.WeChat.WeChatReidsCache2.GetToken(tokenKey);
            if (Common.Config.IsLocal == 1)
            {
                token = "53_yZLlrwCr1CVh5TjyS1FkarF5M15NfYEmMFvtJKVA0C_R5tzOE20CZlFvWOWQRoezFQDweQPwkcenlISyEXoFkOpljNvyt-0_uXvtqQW41T7HfJnFGUWBGNIDkUQuFkKQWTpdXvdZhbWWeE_kMTTcAEAPWW";
            }
            if (string.IsNullOrEmpty(token))
            {
                token = Common.Plugin.WeChatHelper.GetAccessToken(Common.Config.WeChatAccountAppId, Common.Config.WeChatAccountAppSecret);
                Cache.WeChat.WeChatReidsCache2.Set(tokenKey, token);
            }
            string newImaApi = "https://api.weixin.qq.com/cgi-bin/freepublish/batchget?access_token=" + token;
            List<WeChatLearningGardenItem> list = new List<WeChatLearningGardenItem>();
            var resultInfo = new
            {
                count = pageSize,
                offset = (pageIndex - 1) * pageSize,
                no_content = pageSize
            };
            string jsonData = HttpHelper.HttpPost(newImaApi, JsonHelper.Serialize(resultInfo), "");
            if (jsonData != null && !string.IsNullOrEmpty(jsonData))
            {
                Common.Plugin.LogHelper.WriteInfo("GetVoiceData: " + jsonData);
                JObject jObj = JObject.Parse(jsonData);
                var item = jObj.GetStringValue("item");
                if (!string.IsNullOrEmpty(item))
                {
                    JArray jArray = JArray.Parse(item);
                    if (jArray != null && jArray.Count > 0)
                    {
                        foreach (var jItem in jArray)
                        {
                            JObject sObj = JObject.Parse(jItem.ToString());
                            JObject dObj = JObject.Parse(sObj.GetStringValue("content"));
                            var newsItem = new List<WeChatLearningGardenNewsItem>();
                            JArray subArray = JArray.Parse(dObj.GetStringValue("news_item"));
                            if (subArray != null && subArray.Count > 0)
                            {
                                foreach (var sItem in subArray)
                                {
                                    var contentObj = JObject.Parse(sItem.ToString());
                                    newsItem.Add(new WeChatLearningGardenNewsItem()
                                    {
                                        title = contentObj.GetStringValue("title"),
                                        author = contentObj.GetStringValue("author"),
                                        digest = contentObj.GetStringValue("digest"),
                                        content = contentObj.GetStringValue("content"),
                                        show_cover_pic = contentObj.GetInt("show_cover_pic"),
                                        url = contentObj.GetStringValue("url"),
                                        thumb_url = contentObj.GetStringValue("thumb_url"),
                                    });
                                }
                            }
                            var content = new WeChatLearningGardenContent()
                            {
                                news_item = newsItem,
                                create_time = dObj.GetLong("create_time"),
                                update_time = dObj.GetLong("update_time"),
                            };
                            WeChatLearningGardenItem model = new WeChatLearningGardenItem()

                            {
                                media_id = sObj.GetStringValue("article_id"),
                                update_time = sObj.GetStringValue("update_time"),
                                content = content
                            };
                            list.Add(model);
                        }
                    }
                }
            }
            return list;
        }
        #endregion
    }
}
