using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Hncore.Infrastructure.Common;
using Hncore.Infrastructure.Serializer;
using Hncore.Pass.PaymentCenter.WeiFuTong.WechatJsPay;

namespace Hncore.Pass.PaymentCenter.WeiFuTong.ClientExtension
{
    public static class WechatJsPay
    {
        /// <summary>
        /// 微信小程序或公众号支付
        /// </summary>
        /// <param name="weiFuTongClient"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        public static async Task<WechatJsPayCreateOrderResponse> WechatJsPayCreateOrderAsync(
            this WeiFuTongClient weiFuTongClient
            , WechatJsPayCreateOrderRequest request)
        {
            StringBuilder log = new StringBuilder();

            var body = request.ToXml();

            log.Append("请求：\r\n" + body);

            var response = await weiFuTongClient.CreateHttpClient()
                .PostAsync(request.PaymentChannel.GetUrl(), new StringContent(body));

            var resText = await response.Content.ReadAsStringAsync();

            log.Append("\r\n响应：" + resText);

            string appEnv = "";

            if (request.IsMinipg == "1")
            {
                appEnv = "小程序";
            }
            else
            {
                appEnv = "公众号";
            }

            LogHelper.Trace($"威富通-微信{appEnv}支付下单", log.ToString());

            Util.CheckSignFromXml(resText, request.MchInfo);

            var res = XML.XmlDeserialize<WechatJsPayCreateOrderResponse>(resText);

            res.HandleError();

            return res;
        }
    }
}