using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Google.Protobuf.WellKnownTypes;
using Mall.Common.API;
using Mall.Common.Pay.WeChatPat;
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;

namespace Mall.WebApi.Controllers.AppletWeChat
{

    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class WeChatNotifyController : Controller
    {
        private static object _lock = new object();

        UserCommonModule userCommonModule = new UserCommonModule();


        private IHttpContextAccessor _accessor;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="accessor"></param>
        public WeChatNotifyController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }
        /// <summary>
        /// 订单支付回调
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public string Notify()
        {
            var req = new RequestHandler();
            App_Code.PayUtil PayUtil = new App_Code.PayUtil();
            var result = PayUtil.Notify(_accessor);
            if (result.IsSuccess)
            {
                var dic = ((Dictionary<string, string>)result.Data);
                //开始回写订单状态
                lock (_lock)
                {
                    string sOrderNo = dic["sOrderNo"];//订单号 时间挫+OrderId
                    int OrderId = Convert.ToInt32(sOrderNo[17..]);

                    decimal dPaid = Convert.ToDecimal(dic["dPrice"]) / 100;
                    string sPayerOpenID = dic["sPayerOpenID"];
                    int UserId = Convert.ToInt32(dic["bIsRecharge"]);
                    string TransactionId = dic["sTradeNo"];
                    string PayType = dic["OrderPayType"];
                    DateTime PayDate = DateTime.ParseExact(dic["PayDate"], "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);//转换时间// Convert.ToDateTime(dic["PayDate"]);

                    #region 新增订单支付信息

                    userCommonModule.InsertOrderPayInfo(UserId, OrderId, sOrderNo, TransactionId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, PayType, dPaid, PayDate, 0);
                   

                    #endregion
                }
                //告诉微信我们已经处理成功，不需要再调用我们的接口了
                req.SetParameter("return_code", "SUCCESS");
                req.SetParameter("return_msg", "OK");
                var reqXml = req.ParseXml();
                return reqXml;
                //  return ApiResult.Success("", reqXml);
            }
            else
            {
                req.SetParameter("return_code", "FAIL");
                req.SetParameter("return_msg", "订单失败");
                var reqXmlFAIL = req.ParseXml();
                LogHelper.Write(null, "Notify返回信息：" + reqXmlFAIL);
                return reqXmlFAIL;
                // return ApiResult.Failed("", reqXmlFAIL);
            }
        }
    }
}