using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Api.SignToken;
using MadRunFabric.Common;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using NLog;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.Containers;
using Senparc.Weixin.MP.Entities.Request;
using Senparc.Weixin.MP.Helpers;
using Senparc.Weixin.MP.MvcExtension;
using WechatApi.MessageHandlers;


namespace WechatApi.Controllers
{
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/Home/[action]")]
    public class HomeController : BaseController
    {
        private readonly string Token;
        private readonly string AppId;
        private readonly string AppSecret;
        private readonly string EncodingAESKey;
        static Logger Logger = LogManager.GetCurrentClassLogger();
        private readonly ISignTokenService _signTokenService;
        private IHostingEnvironment _host;
        private IConfiguration _configuration;
        public HomeController(IConfiguration configuration, ISignTokenService signTokenService, IHostingEnvironment host)
        {
            Token = configuration["WechatStatic:Token"];
            AppId = configuration["WechatStatic:AppId"];
            AppSecret = configuration["WechatStatic:AppSecret"];
            EncodingAESKey = configuration["WechatStatic:EncodingAESKey"];
            _configuration = configuration;
            _signTokenService = signTokenService;
            _host = host;
        }

        /// <summary>
        /// 微信开发验证
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="echostr"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Verify(string signature, string timestamp, string nonce, string echostr)
        {
            if (CheckSignature.Check(signature, timestamp, nonce, Token))
            {
                return Content(echostr, "application/x-www-form-urlencoded", Encoding.UTF8); //返回随机字符串则表示验证通过
            }
            return Content($"failed:{signature},{CheckSignature.GetSignature(timestamp, nonce, Token) }。如果您在浏览器中看到这条信息，表明此Url可以填入微信后台。");
        }

        /// <summary>
        /// 用户发送消息后，微信平台自动Post一个请求到这里，并等待响应XML。
        /// </summary>
        [HttpPost]
        [Produces("text/xml")]
        public IActionResult Verify(PostModel postModel)
        {
            if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))
            {
                return new WeixinResult("参数错误");
            }
            postModel.Token = Token;
            postModel.EncodingAESKey = EncodingAESKey;
            postModel.AppId = AppId;

            string body = new StreamReader(Request.Body).ReadToEnd();
            byte[] requestData = Encoding.UTF8.GetBytes(body);
            Stream inputStream = new MemoryStream(requestData);


            CustomMessageHandler messageHandler = new CustomMessageHandler(inputStream, postModel, _configuration, _signTokenService);//接收消息
            messageHandler.Execute();//执行微信处理过程

            return new FixWeixinBugWeixinResult(messageHandler);//返回结果、、
            //最终返回结果是：【xml文档转为xml字符串并且去掉“换行”、“空格”后的字符串】
            //return new WeixinResult(messageHandler.FinalResponseDocument.ToString().Replace("\r\n", "").Replace(" ", ""));
        }

        /// <summary>
        /// 供前端调用JSSDK，获取基本验证信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetInfo(string fromUrl = "")
        {
            var timestamp = JSSDKHelper.GetTimestamp(); //获取随机码
            var nonce = JSSDKHelper.GetNoncestr();
            var ticket = await JsApiTicketContainer.GetJsApiTicketAsync(AppId);
            var signature = JSSDKHelper.GetSignature(ticket.ToString(), nonce, timestamp, fromUrl);
            return Success("", new
            {
                appid = AppId,
                timestamp,
                nonce,
                signature,
                ticket,
                fromUrl
            });
        }
    }
}
