using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Senparc.Weixin.MP;
using Microsoft.Extensions.Configuration;
using Senparc.Weixin.MP.MvcExtension;
using Senparc.Weixin.MP.Entities.Request;
using ServiceWechat.Api.MessageHandlers.CustomMessageHandler;
using ServiceWechat.Api.Controllers.Base;

namespace ServiceWechat.Api.Controllers.WechatApis
{
    [Route("wechatapi/Home/[action]")]
    public class HomeController : BaseController
    {
        private readonly string Token;
        private readonly string AppId;
        private readonly string EncodingAESKey;
        public HomeController(IConfiguration configuration)
        {
            Token = configuration["WechatStatic:Token"];
            AppId = configuration["WechatStatic:AppId"];
            EncodingAESKey = configuration["WechatStatic:EncodingAESKey"];
        }

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

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

            postModel.Token = Token;//根据自己后台的设置保持一致
            postModel.EncodingAESKey = EncodingAESKey;//根据自己后台的设置保持一致
            postModel.AppId = AppId;//根据自己后台的设置保持一致

            //自定义MessageHandler，对微信请求的详细判断操作都在这里面。
            var messageHandler = new CustomMessageHandler(Request.Body, postModel);//接收消息
            messageHandler.Execute();//执行微信处理过程
            return new WeixinResult(messageHandler);//返回结果
        }

    }
}
