using Mall.CacheManager.AppletWeChat;
using Mall.CacheManager.User;
using Mall.Common.API;
using Mall.Common.Plugin;
using Mall.Module.User;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
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";

        private readonly MiniProgramModule miniProgramModule = new MiniProgramModule();

        /// <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)
        {
            string[] ArrTmp = { token, timestamp, nonce };
            Array.Sort(ArrTmp);
            string tmpStr = string.Join("", ArrTmp);
            SHA1 sha;
            string hash = "";
            try
            {
                sha = new SHA1CryptoServiceProvider();
                byte[] dataToHash = Encoding.UTF8.GetBytes(tmpStr);
                byte[] dataHashed = sha.ComputeHash(dataToHash);
                hash = BitConverter.ToString(dataHashed).Replace("-", "");
                hash = hash.ToLower();
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "CheckSignature");
            }
            if (hash == signature)
            {
                return echostr;
            }
            return "";
        }


        /// <summary>
        /// 接口认证
        /// </summary>
        /// <param name="echostr"></param>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <returns></returns>
        [HttpPost]
        public string CheckSignature(string signature, string timestamp, string nonce)
        {
            string responseData = "";
            try
            {
                #region Post请求的密文数据
                Request.EnableBuffering();
                using (var reader = new StreamReader(Request.Body, encoding: System.Text.Encoding.UTF8))
                {
                    var body = reader.ReadToEndAsync();
                    responseData = body.Result;
                    Request.Body.Position = 0;
                }
                #endregion
                if (!string.IsNullOrEmpty(responseData))
                {
                    JObject jobj = JObject.Parse(responseData);
                    string openId = jobj.GetStringValue("FromUserName");
                    string MsgType = jobj.GetStringValue("MsgType");
                    string Content = jobj.GetStringValue("Content");
                    Common.Plugin.LogHelper.Write($"请求参数:: openId:{openId} MsgType:{MsgType} Content:{Content}" );
                    if (MsgType == "text" && !string.IsNullOrEmpty(openId) && !string.IsNullOrEmpty(Content) && Content.Contains("支付"))
                    {
                        Task.Run(() =>
                        {
                            Common.Plugin.LogHelper.WriteInfo($"消息_推送客服消息:{openId}");
                            string payInfoKey = CacheManager.DataStatistic.DataConstant.DATA_AliPay_Order + openId;
                            Common.Plugin.LogHelper.WriteInfo($"消息_推送客服消息：获取缓存");
                            var zfbPayList = UserReidsCache.GetOrderPay(payInfoKey);
                            if (zfbPayList != null && zfbPayList.Count > 0)
                            {
                                Common.Plugin.LogHelper.WriteInfo($"消息_推送客服缓存:{JsonHelper.Serialize(zfbPayList)}");
                                List<string> pushUrlList = new List<string>();
                                foreach (var item in zfbPayList)
                                {
                                    if (!pushUrlList.Contains(item.PayInfo))
                                    {
                                        pushUrlList.Add(item.PayInfo);
                                    }
                                }
                                Common.Plugin.LogHelper.WriteInfo($"消息_删除缓存");
                                //删除缓存
                                UserReidsCache.DeleteMiniAppUsetOpenId(payInfoKey);
                                SendMessage(openId, pushUrlList);
                                Common.Plugin.LogHelper.WriteInfo($"消息_推送客服消息:{openId} ，地址:{JsonHelper.Serialize(pushUrlList)}");
                            }
          
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "CheckSignature::请求参数异常");
            }
            return "";
        }

        /// <summary>
        /// 发送客服消息
        /// </summary>
        /// <param name="toUser">接收人URL</param>
        /// <param name="targerList">支付订单列表</param>
        private void SendMessage(string toUser, List<string> targerList)
        {
            int MallBaseId = 17;
            // toUser = "oyiQo5Dgzt7X3WZudvx3LaZmf2h0";
            // targerList.Add("https://qr.alipay.com/bax00835y0gx4mzmeycd0020");
            List<string> pushList = new List<string>();
            foreach (var item in targerList)
            {
                string tempItem = item;
                tempItem = System.Web.HttpUtility.UrlEncode(item);
                string postUrl = string.Format("http://jj.kookaku.com/pages/pay/transition?aliuri={0}", tempItem);
                pushList.Add(postUrl);
            }
            var miniProgram = miniProgramModule.GetMiniProgramModule(new Model.Extend.User.RB_MiniProgram_Extend() { MallBaseId = MallBaseId });
            string token = WeiXinReidsCache.Get(miniProgram.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, miniProgram.MiniAppId, miniProgram.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(miniProgram.MiniAppId, token));
            }
            Common.Plugin.LogHelper.WriteInfo($"SendMessage:{token}");
            bool flag = Common.Plugin.WeChatMessageHelper.SendCustomerMessage(token, toUser, pushList, out string message);
        }
    }
}
