using Senparc.Weixin;
using Senparc.Weixin.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace YBDevice.NApi
{
    /// <summary>
    /// 全局微信事件有关的处理程序
    /// </summary>
    public class EventService
    {
        /// <summary>
        /// 异常消息处理
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        public void ConfigOnWeixinExceptionFunc(WeixinException ex)
        {
            Senparc.Weixin.WeixinTrace.SendCustomLog("进入 ConfigOnWeixinExceptionFunc() 方法", ex.Message);
            try
            {
                var appId = Config.SenparcWeixinSetting.WeixinAppId;

                string openId = "oyXoU0r5wvkdVk0O82XdpzJ1lZcU";//收到通知的管理员OpenId
                var host = "A1 / AccessTokenOrAppId：" + (ex.AccessTokenOrAppId ?? "null");
                string service = null;
                string message = ex.Message;
                var status = ex.GetType().Name;
                //var remark = "\r\n这是一条通过OnWeixinExceptionFunc事件发送的异步模板消息";
                //string url = "https://github.com/JeffreySu/WeiXinMPSDK/blob/master/Samples/netcore3.0-mvc/Senparc.Weixin.Sample.NetCore3/Startup.cs#L410";//需要点击打开的URL

                var sendTemplateMessage = true;

                if (ex is ErrorJsonResultException)
                {
                    var jsonEx = (ErrorJsonResultException)ex;
                    service = $"{jsonEx.JsonResult?.errcode}:{jsonEx.JsonResult?.errmsg} - {jsonEx.Url?.Replace("https://api.weixin.qq.com/cgi-bin", "ApiUrl")}".Substring(0, 30);
                    message = jsonEx.Message;

                    //需要忽略的类型
                    var ignoreErrorCodes = new[]
                    {
                                ReturnCode.获取access_token时AppSecret错误或者access_token无效,
                                ReturnCode.access_token超时,
                                ReturnCode.template_id不正确,
                                ReturnCode.缺少access_token参数,
                                ReturnCode.回复时间超过限制,
                                ReturnCode.api功能未授权,
                                ReturnCode.用户未授权该api,
                                ReturnCode.参数错误invalid_parameter,
                                ReturnCode.接口调用超过限制,
                                ReturnCode.需要接收者关注,//43004
                                ReturnCode.超出响应数量限制,//43004 - out of response count limit，一般只允许连续接收20条客服消息
                                //其他更多可能的情况
                            };
                    if (ignoreErrorCodes.Contains(jsonEx.JsonResult.errcode))
                    {
                        sendTemplateMessage = false;//防止无限递归，这种请求下不发送消息
                    }

                    //TODO:防止更多的接口自身错误导致的无限递归。
                    //记录异常
                    Senparc.Weixin.WeixinTrace.SendCustomLog("发生异常", ex.Message + "\r\n" + ex.StackTrace);
                }
                else
                {
                    if (ex.Message.StartsWith("openid:"))
                    {
                        openId = ex.Message.Split(':')[1];//发送给指定OpenId
                    }
                    service = "WeixinException";
                    message = ex.Message;
                }

                if (sendTemplateMessage)    // DPBMARK MP
                {
                    //int sleepSeconds = 3;
                    //Thread.Sleep(sleepSeconds * 1000);
                    //string templateid = Configs.GetString("WXErrorTemplateId");
                    //var data = new WeixinTemplate_ExceptionAlert(string.Format("微信发生异常（延时{0}秒）", sleepSeconds), host, service, status, message, remark, templateid);

                    //修改OpenId、启用以下代码后即可收到模板消息
                    //if (!string.IsNullOrEmpty(openId))
                    //{
                    //    var result = Senparc.Weixin.MP.AdvancedAPIs.TemplateApi.SendTemplateMessageAsync(appId, openId, data.TemplateId,
                    //      url, data);
                    //    Task.WaitAll(new[] { result });
                    //    if (result.IsFaulted)
                    //    {
                    //        Senparc.Weixin.WeixinTrace.SendCustomLog("OnWeixinExceptionFunc过程模板消息发送异常", result.Exception?.Message + "\r\n" + result.Exception?.StackTrace);
                    //    }
                    //}
                }   // DPBMARK_END
            }
            catch (Exception e)
            {
                WeixinTrace.SendCustomLog("OnWeixinExceptionFunc过程错误", e.Message);
            }
        }
    }
}
