using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using AdapayCore;
using Mall.Common.Plugin;
using Mall.Module.User;
using Mall.Repository.Education;
using Mall.ThirdCore.Adapay.Model;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Mall.WebApi.Controllers.Adapay
{

    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class AdapayCallBackController : ControllerBase
    {

        private readonly UserCommonModule userCommonModule = new UserCommonModule();        

        #region 汇付天下接收事件

        /// <summary>
        /// 汇付天下支付回调
        /// </summary>
        [HttpPost]
        public string AdapayCallBackEvent()
        {
            LogHelper.WriteInfo("汇付天下 支付回调进来了");
            #region Post请求的密文数据
            Request.EnableBuffering();
            string responseData = "";
            using (var reader = new StreamReader(Request.Body, encoding: System.Text.Encoding.UTF8))
            {
                var body = reader.ReadToEndAsync();
                responseData = body.Result;
                Request.Body.Position = 0;
            }
            #endregion

            LogHelper.WriteInfo("回调参数：" + responseData);
            #region 解码参数
            try
            {
                responseData = System.Web.HttpUtility.UrlDecode(responseData);
                List<string> rlist = responseData.Split('&').ToList();
                Dictionary<string, string> expendDict = new Dictionary<string, string>();
                foreach (var item in rlist)
                {
                    string[] values = item.Split('=');
                    expendDict.Add(values[0], values[1]);
                }
                //验签请参data
                expendDict.TryGetValue("data", out string data);
                //验签请参sign
                expendDict.TryGetValue("sign", out string sign);
                //事件类型
                expendDict.TryGetValue("type", out string type);
                //验签
                bool checkSign = NetUtils.verfySign(sign, data);
                if (checkSign)
                {
                    //验签成功逻辑
                    LogHelper.WriteInfo("成功返回数据data:" + data);
                    //退款返回
                    //data = '{"object":"refund","status":"succeeded","prod_mode":"true","id":"0021120220718133304980394978062292664320","refund_order_no":"R202207181658151172712","payment_id":"002112022071419472310393622712813637632","payment_order_no":"202207141657828044797","refund_amt":"0.01","fee_amt":"0.00","channel_no":"2022071821R5j30g","created_time":"1658122384000","succeed_time":"1658122386000","app_id":"app_c474eae3-28a4-487b-9d07-c92c228c9a0b"}';
                    AdaPayResultModel payMdoel = JsonHelper.DeserializeObject<AdaPayResultModel>(data);
                    switch (type)
                    {
                        case "payment.succeeded"://支付成功

                            //异步操作订单实收  新增财务单据
                            System.Threading.Tasks.Task.Run(() => userCommonModule.InsertAdapayOrderTrade(payMdoel));

                            break;
                        case "payment.failed"://支付失败

                            LogHelper.WriteInfo("订单支付失败：" + data);
                            break;
                        case "refund.succeeded"://退款成功

                            break;
                        case "refund.failed"://退款失败

                            break;
                        case "fastpay.succeeded":// 快捷支付确认成功

                            break;
                        case "fastpay.failed":// 快捷支付确认失败

                            break;
                    }
                }
                else
                {
                    //验签失败逻辑
                    LogHelper.WriteInfo("签名效验失败");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "AdapayCallBackEvent");
            }
            #endregion

            return "";
        }

        #endregion
    }
}