using Hncore.Infrastructure.Common;
using Hncore.Infrastructure.Extension;
using Hncore.Pass.BaseInfo.Service;
using Hncore.Pass.Sells.Service;
using Hncore.Wx.Open;
using Home.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Senparc.NeuChar.App.Entities;
using Senparc.Weixin.MP;
using System;
using System.Threading.Tasks;

namespace Home.Controllers
{
    [AllowAnonymous]
    [Controller]
    [Route("[Controller]/[Action]")]
    public class WeiXinController : Controller
    {
        WxAppUserService m_WxAppUserService;
        CouponService m_CouponService;
        IConfiguration m_Configuration;
        public WeiXinController(IConfiguration _Configuration
            , WxAppUserService _WxAppUserService
            , CouponService _CouponService)
        {
            m_WxAppUserService = _WxAppUserService;
            m_CouponService = _CouponService;
            m_Configuration = _Configuration;
        }

        [HttpGet]
        [ActionName("Index")]
        public ActionResult Get(string signature, string timestamp, string nonce, string echostr)
        {
            if (CheckSignature.Check(signature, timestamp, nonce, "hualian"))
            {
                return Content(echostr); //返回随机字符串则表示验证通过
            }
            else
            {
                return Content("failed");
            }
        }

        /// <summary>
        /// 最简化的处理流程（不加密）
        /// </summary>
        [HttpPost]
        [ActionName("Index")]
        public ActionResult Post(PostModel postModel)
        {
            if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, "hualian"))
            {
                return Content("参数错误！");
            }

            postModel.Token ="hualian";
            postModel.EncodingAESKey = m_Configuration["WxApps:EncodingAESKey"];//根据自己后台的设置保持一致
            postModel.AppId = m_Configuration["WxApps:AppID"];//根据自己后台的设置保持一致



            var messageHandler = new MyMessageHandler(Request.Body, m_WxAppUserService,m_CouponService);

            messageHandler.Execute();//执行微信处理过程

            return Content(messageHandler.ResponseDocument.ToString());//v0.7-
            //return new WeixinResult(messageHandler);//v0.8+
           // return new FixWeixinBugWeixinResult(messageHandler);//v0.8+
        }

        /// <summary>
        /// 微信后台推送过来的用户与公众号交互的信息 消息和事件
        /// </summary>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="encrypt_type"></param>
        /// <param name="msg_signature"></param>
        /// <returns></returns>
        [HttpPost("{appid}"), AllowAnonymous]
        public async Task<string> msg_notice(string appid, string timestamp, string nonce, string encrypt_type, string msg_signature)
        {
            LogHelper.Debug("公众号交互消息", $"appid={appid}，{timestamp},{nonce},{encrypt_type},{msg_signature}");
            var msg = await this.Request.Body.ReadAsStringAsync();
            LogHelper.Debug("公众号交互消息-加密", msg);
            var token = m_Configuration["WxOpen:Token"];
            var decyptKey = m_Configuration["WxOpen:DecyptKey"];
            var appID = m_Configuration["WxOpen:AppID"];
            string decMsg = "";
            var wxcpt = new WxOpenCrypt(token, decyptKey, appID);
            var ret = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, msg, ref decMsg);
            if (ret != 0)
            {
                LogHelper.Error("开放平台推送的消息-解密失败", ret);
                return "faild";
            }

            var flag = false;
            try
            {
                var requestMessage = MessageFactory.GetRequestEntity(decMsg);
                if (requestMessage != null)
                {                   
                    requestMessage.AppId = appid;
                    flag = await requestMessage.Handler();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Fatal("微信开放平台的消息-解析失败", ex.Message);
                LogHelper.Error("开放平台推送的消息-解密的消息", decMsg);
                flag = false;
            }
            return flag ? "success" : "faild";
        }
    }
}
