using Mall.Common.API;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Mall.WebApi.Controllers.Adapay
{

    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class MessageController : ControllerBase
    {
        public string token = "jjswviitto";
        public string aes = "leHp9tJo9shWv63PFebqWT3UR6o5OKMD9YKFrDd2yxT";
        public string appId = "wx5349e63aea0c8529";

        /// <summary>
        /// 接口认证
        /// </summary>
        /// <param name="echostr"></param>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <returns></returns>
        [HttpGet]
        public string CheckSignature(string echostr, string signature, string timestamp, string nonce)
        {
            Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(token, aes, appId);
            string sVerifyMsgSig = signature;
            string sVerifyTimeStamp = timestamp;
            string sVerifyNonce = nonce;
            string sVerifyEchoStr = echostr;
           
            string sEchoStr = "";
            int ret = wxcpt.VerifySignature(token, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, sVerifyMsgSig);
            if (ret != 0)
            {
                Common.Plugin.LogHelper.Write("验证Url失败：" + ret);
            }

            return sEchoStr;
        }

        /// <summary>
        /// 接收客服消息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<HttpResponseMessage> wx()
        {
             
            //var content = await Request.Content.ReadAsStringAsync();
 
            HttpResponseMessage responseMessage = new HttpResponseMessage();
            return responseMessage;
        }
        /// <summary>
        /// 验证微信签名
        /// </summary>
        private bool CheckSignatureModule(string token, string signature, string timestamp, string nonce)
        {
            string[] ArrTmp = { token, timestamp, nonce };
            Array.Sort(ArrTmp);
            string tmpStr = string.Join("", ArrTmp);
            var data = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(tmpStr));
            Common.Plugin.LogHelper.Write("data:" + data);
            var sb = new StringBuilder();
            foreach (var t in data)
            {
                sb.Append(t.ToString("X2"));
            }
            tmpStr = sb.ToString();
            tmpStr = tmpStr.ToLower();

            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


    }
}
