using Microsoft.Extensions.DependencyInjection;
using Senparc.NeuChar.App.AppStore;
using Senparc.NeuChar.Entities;
using Senparc.NeuChar.Helpers;
using Senparc.Weixin;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.Entities.Request;
using Senparc.Weixin.MP.MessageHandlers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using YBDevice.Core;
using YBDevice.WXApplication.DeviceInfo;

namespace YBDevice.WX.MessageHandlers.CustomMessageHandler
{
    /// <summary>
    /// 自定义MessageHandler,把MessageHandler作为基类，重写对应请求的处理方法
    /// </summary>
    public partial class CustomMessageHandler : MessageHandler<CustomMessageContext>
    {
        private string appId =Senparc.Weixin.Config.SenparcWeixinSetting.WeixinAppId;
        /// <summary>
        /// 为中间件提供生成当前类的委托
        /// </summary>
        public static Func<Stream, PostModel, int, IServiceProvider,CustomMessageHandler> GenerateMessageHandler = (stream, postModel, maxRecordCount, serviceProvider)
                        => new CustomMessageHandler(stream, postModel, maxRecordCount, false /* 是否只允许处理加密消息，以提高安全性 */,
                            serviceProvider:serviceProvider
                            );

        public CustomMessageHandler(Stream inputStream, PostModel postModel, int maxRecordCount = 0, bool onlyAllowEncryptMessage = false, IServiceProvider serviceProvider = null)
    : base(inputStream, postModel, maxRecordCount, onlyAllowEncryptMessage, serviceProvider: serviceProvider)
        {
            //这里设置仅用于测试，实际开发可以在外部更全局的地方设置，
            //比如MessageHandler<MessageContext>.GlobalGlobalMessageContext.ExpireMinutes = 3。
            GlobalMessageContext.ExpireMinutes = 3;

            OnlyAllowEncryptMessage = true;//是否只允许接收加密消息，默认为 false

            if (!string.IsNullOrEmpty(postModel.AppId))
            {
                appId = postModel.AppId;//通过第三方开放平台发送过来的请求
            }

            //在指定条件下，不使用消息去重
            base.OmitRepeatedMessageFunc = requestMessage =>
            {
                var textRequestMessage = requestMessage as RequestMessageText;
                if (textRequestMessage != null && textRequestMessage.Content == "容错")
                {
                    return false;
                }
                return true;
            };
        }
        /// <summary>
        /// 处理文字请求
        /// </summary>
        /// <param name="requestMessage">请求消息</param>
        /// <returns></returns>
        public override async Task<IResponseMessageBase> OnTextRequestAsync(RequestMessageText requestMessage)
        {
            if(requestMessage.Content.Length == 4)
            {
                var deviceService = base.ServiceProvider.GetService<IDeviceService>();
                var returndata =await deviceService.HandlerTextAsync(requestMessage.ToUserName, requestMessage.FromUserName, requestMessage.Content);
                if (!string.IsNullOrEmpty(returndata.wxfansid))
                {
                    List<Article> arts = new List<Article>();
                    //固定贴纸
                    if(returndata.type == 2)
                    {
                        Guid rid = Guid.Parse(returndata.resultid);
                        arts = deviceService.GetStickyWXMessageNews(RequestMessage.ToUserName, requestMessage.FromUserName, returndata.wxfansid, 4, rid);
                    }
                    else
                    {
                        arts = deviceService.GetWXMessageNews(RequestMessage.ToUserName, requestMessage.FromUserName, returndata.wxfansid, 4, returndata.resultid);
                    }
                    var requestMessagenews = base.CreateResponseMessage<ResponseMessageNews>();
                    requestMessagenews.Articles.AddRange(arts);
                    return requestMessagenews;
                }
            }
            if (requestMessage.Content == "内部测试api")
            {
                var responseMessage = CreateResponseMessage<ResponseMessageText>();
                responseMessage.Content = requestMessage.Content;
                return await Task.FromResult(responseMessage);
            }
            return await base.OnTextRequestAsync(requestMessage);
        }

        /// <summary>
        /// 默认消息处理
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage)
        {

            return new SuccessResponseMessage();
        }
        /// <summary>
        /// 未知消息处理
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override async Task<IResponseMessageBase> OnUnknownTypeRequestAsync(RequestMessageUnknownType requestMessage)
        {
            /*
             * 此方法用于应急处理SDK没有提供的消息类型，
             * 原始XML可以通过requestMessage.RequestDocument（或this.RequestDocument）获取到。
             * 如果不重写此方法，遇到未知的请求类型将会抛出异常（v14.8.3 之前的版本就是这么做的）
             */
            var loggerService = base.ServiceProvider.GetService <ILoggerService>();
            return await Task.Factory.StartNew<IResponseMessageBase>(() =>
            {
                var msgType = MsgTypeHelper.GetRequestMsgTypeString(requestMessage.RequestDocument);
                var responseMessage = this.CreateResponseMessage<ResponseMessageText>();
                responseMessage.Content = "未知消息类型：" + msgType;
                loggerService.AddLogger($"未知请求消息类型:{requestMessage.RequestDocument.ToString()}",3);
                return responseMessage;
            });
        }
    }
}
