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

namespace Hncore.Pass.PaymentCenter.WeiFuTong.ClientExtension
{
    public static class RefundExt
    {
        /// <summary>
        /// 退款请求
        /// </summary>
        /// <param name="weiFuTongClient"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        public static async Task<WeiFuTongRefundResponse> RefundAsync(this WeiFuTongClient weiFuTongClient,
            WeiFuTongRefundRequest 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());

            Util.CheckSignFromXml(resText, request.MchInfo);

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

            res.HandleError();

            return res;
        }

        /// <summary>
        /// 退款查询
        /// </summary>
        /// <param name="weiFuTongClient"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        public static async Task<WeiFuTongRefundQueryResponse> QueryRefundAsync(this WeiFuTongClient weiFuTongClient,
            WeiFuTongRefundQueryRequest 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());

            Util.CheckSignFromXml(resText, request.MchInfo);

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

            if (!(res.IsCancel() || res.IsNotExists()) && res.HasError())
            {
                res.HandleError();
            }

            return res;
        }
    }
}