using GxPress.Common.WechatPay;
using GxPress.Repository.Interface.Order;
using GxPress.Service.Interface.Order;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Threading.Tasks;

namespace GxPress.Api.WebControllers
{
    [Route("api/web/wxpay")]
    [ApiController]
    [Authorize]
    public class WxpayController : Controller
    {
        private IHttpContextAccessor _contextAccessor;
        private HttpContext _context { get { return _contextAccessor.HttpContext; } }

        private readonly IOrderRepository orderRepository;
        private IOrderService orderService;
        public WxpayController(IHttpContextAccessor contextAccessor, IOrderService orderService, IOrderRepository orderRepository)
        {
            _contextAccessor = contextAccessor;
            this.orderService = orderService;
            this.orderRepository = orderRepository;
        }
        [HttpGet()]
        [AllowAnonymous]
        public string GetNativePayUrl()
        {
            var nativePay = new NativePay();
            return nativePay.GetPayUrl("637263608658642540", "汪峰讲故事", "637263608658642540_7_2", 1);
        }
        /// <summary>
        /// 回调地址
        /// </summary>
        [HttpPost("notify")]
        [AllowAnonymous]
        public async Task<string> Callback()
        {
            var contentType = Request.ContentType;
            var notifyData = await GetNotifyData();
            //检查支付结果中transaction_id是否存在
            if (!notifyData.IsSet("transaction_id"))
            {
                //若transaction_id不存在,则立即返回结果给微信支付后台
                var res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "支付结果中微信订单号不存在");
                return (res.ToXml());
            }
            string transaction_id = notifyData.GetValue("transaction_id").ToString();
            //查询订单,判断订单真实性
            if (!Common.WechatPay.WxPayApi.QueryOrder(transaction_id))
            {
                //若订单查询失败,则立即返回结果给微信支付后台
                var res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "订单查询失败");
                return (res.ToXml());
            }
            //查询订单成功
            else
            {
                var res = new WxPayData();
                //创建订单
                if (await orderService.InsertWxOrderAsync(notifyData))
                {
                    res.SetValue("return_code", "SUCCESS");
                    res.SetValue("return_msg", "OK");
                    return (res.ToXml());
                }
            }
            notifyData = new WxPayData();
            notifyData.SetValue("return_code", "FAIL");
            notifyData.SetValue("return_msg", "支付结果中微信订单号不存在");
            return (notifyData.ToXml());
        }
        /// <summary>
        /// 退款
        /// </summary>
        /// <param name="orderNumber"></param>
        /// <returns></returns>
        [HttpGet("{orderNumber}")]
        [AllowAnonymous]
        public async Task<string> Refund(string orderNumber)
        {
            var order = await orderRepository.GetOrderAsync(orderNumber);
            var nativePay = new NativePay();
            var price = Convert.ToInt32((order.Price) * 100).ToString();
            return nativePay.Refund(order.TransactionId, order.OutTradeNo, price, price);
        }
        private async Task<WxPayData> GetNotifyData()
        {
            var body = string.Empty;
            //接收从微信后台POST过来的数据
            using (var reader = new StreamReader(Request.Body))
            {
                body = await reader.ReadToEndAsync();
            }
            //转换数据格式并验证签名
            WxPayData data = new WxPayData();
            if (string.IsNullOrEmpty(body))
            {
                data.SetValue("return_code", "FAIL");
                return data;
            }
            try
            {
                data.FromXml(body);
            }
            catch (WxPayException ex)
            {
                //若签名错误,则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);
                // Log.Error(this.GetType().ToString(), "Sign check error : " + res.ToXml());
                // page.Response.Write(res.ToXml());
                // page.Response.End();
            }
            // Log.Info(this.GetType().ToString(), "Check sign success");
            return data;
        }
    }
}