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

namespace Hncore.Pass.PaymentCenter.WeiFuTong.ClientExtension
{
    public static class SwipeCard
    {
        /// <summary>
        /// 刷卡支付下单
        /// </summary>
        /// <param name="weiFuTongClient"></param>
        /// <param name="request"></param>
        /// <returns>need_query为Y时需要轮询查询支付状态，不为Y则支付成功</returns>
        public static async Task<SwipeCardCreateOrderResponse> SwipeCardCreateOrderAsync(
            this WeiFuTongClient weiFuTongClient
            , SwipeCardCreateOrderRequest 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);

            LogHelper.Trace("威富通-刷卡支付下单", log.ToString());

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new HttpException(response.StatusCode) {Content = resText};
            }

            Util.CheckSignFromXml(resText, request.MchInfo);

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

            if (res.HasError() && res.NeedQuery != "Y" && res.NeedQuery != "")
            {
                res.HandleError();
            }

            return res;
        }
    }
}