using Microsoft.AspNetCore.Http;
using CrazyStudio.Core.Pay.TenPay.Lib;
using System;
using System.Threading.Tasks;

namespace CrazyStudio.Core.Pay.TenPay.Business
{
    /// <summary>
    /// 支付结果通知回调处理类
    /// 负责接收微信支付后台发送的支付结果并对订单有效性进行验证，将验证结果反馈给微信支付后台
    /// </summary>
    public class ResultNotify : Notify
    {
        public delegate Task<WxPayData> OrderProcessDelegate(string outTradeNo, string transaction_id, string orderAttach, ResultNotify notify);
        public OrderProcessDelegate OrderProcess = null;
        public ResultNotify(HttpContext context, OrderProcessDelegate orderProcess) : base(context)
        {
            OrderProcess = orderProcess;
        }

        public static DateTime GetNewBuyCardStartTime(string memo)
        {
            DateTime startTime = DateTime.Now;
            if (!string.IsNullOrEmpty(memo))
            {
                string[] parms = memo.Split('_');
                if (parms.Length > 1)
                {
                    string startDateStr = parms[1];
                    if (!string.IsNullOrEmpty(startDateStr))
                    {
                        startTime = DateTime.Parse(startDateStr);
                    }
                }
            }
            return startTime;
        }

        public override async Task<WxPayData?> ProcessNotify()
        {
            WxPayData notifyData = null;
            try
            {
                notifyData = await GetNotifyData();
            }
            catch (Exception ex)
            {
                Log.Debug("ex", ex.Message + " trace:" + ex.StackTrace);
                return null;
            }

            if (notifyData == null)
            {
                return null;
            }

            //检查支付结果中transaction_id是否存在
            if (!notifyData.IsSet("transaction_id"))
            {
                //若transaction_id不存在，则立即返回结果给微信支付后台
                var res = GetPayResult(false, "支付结果中微信订单号不存在");
                return res;
            }

            string? transaction_id = notifyData.GetValue("transaction_id").ToString();
            string? out_trade_no = notifyData.GetValue("out_trade_no").ToString();
            string? attach = notifyData.GetValue("attach").ToString();

            //查询订单，判断订单真实性
            string? outTradeNo = QueryOrder(transaction_id!, out_trade_no!, out int total_fee);

            if (string.IsNullOrEmpty(outTradeNo))
            {
                var res = GetPayResult(false, "订单查询失败");
                return res;
            }
            //查询订单成功
            else
            {
                if (!outTradeNo.Equals("0"))
                {
                    if (OrderProcess != null)
                    {
                        var res = await OrderProcess.Invoke(outTradeNo, transaction_id, attach!, this);
                        return res;
                    }
                    return null;
                }
                else
                {
                    var res = GetPayResult(false, "订单查询失败，orderId为0");
                    return res;
                }
            }
        }

        public WxPayData GetPayResult(bool isSuccess, string message)
        {
            WxPayData res = new WxPayData();
            //var xml = string.Empty;
            if (isSuccess)
            {
                res.SetValue("return_code", "SUCCESS");
                res.SetValue("return_msg", message);
                //xml = res.ToXml();
                Log.Info(this.GetType().ToString(), "order query success : " + res.ToXml());
            }
            else
            {
                //若订单查询失败，则立即返回结果给微信支付后台
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", message);
            }

            return res;

            //if (!string.IsNullOrEmpty(xml))
            //{
            //    var send = Encoding.UTF8.GetBytes(xml);
            //    await context.Response.Body.WriteAsync(send, 0, send.Length);
            //    await context.Response.Body.FlushAsync();
            //}
        }

        //查询订单
        private string? QueryOrder(string transaction_id, string out_trade_no, out int total_fee)
        {
            WxPayData req = new WxPayData();
            req.SetValue("transaction_id", transaction_id);
            WxPayData res = WxPayApi.JsApiOrderQuery(req);
            //if (wxPayType == "0")
            //{
            //    res = WxPayApi.JsApiOrderQuery(req);
            //}
            //else
            //{
            //    res = WxPayApi.OrderQuery(req);
            //}


            if (res.GetValue("return_code").ToString() == "SUCCESS" && res.GetValue("result_code").ToString() == "SUCCESS")
            {
                var orderId = "0";
                orderId = res.GetValue("out_trade_no").ToString();
                total_fee = Convert.ToInt32(res.GetValue("total_fee"));     //支付价格
                Log.Debug(" cache_OrderId", orderId!);

                return orderId;
            }
            else
            {
                total_fee = -1; //表示出错。
                return null;
            }
        }
    }
}