using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using Hncore.Infrastructure.Extension;

namespace Hncore.Pass.PaymentCenter.WeiFuTong.Refund
{
    /// <summary>
    /// 威富通退款查询响应
    /// </summary>
    [XmlRoot("xml", Namespace = "")]
    public class WeiFuTongRefundQueryResponse : WeiFuTongResponseBase
    {
        /// <summary>
        /// 平台交易号
        /// </summary>
        [XmlElement("transaction_id")]
        public string TransactionId { get; set; }

        /// <summary>
        /// 商户系统内部的订单号
        /// </summary>
        [XmlElement("out_trade_no")]
        public string OutTradeNo { get; set; }

        /// <summary>
        /// 退款记录数
        /// </summary>
        [XmlElement("refund_count")]
        public int RefundCount { get; set; }

        /// <summary>
        /// 多笔退款详情
        /// </summary>
        public List<RefundQueryItem> RefundQueryItems { get; set; } = new List<RefundQueryItem>();

        public WeiFuTongRefundQueryResponse ParseItemsFromXml(string xmlText)
        {
            if (RefundCount <= 0)
            {
                return this;
            }

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.XmlResolver = null;
            xmlDoc.LoadXml(xmlText);
            XmlNode root = xmlDoc.SelectSingleNode("xml");

            for (int i = 0; i < RefundCount; i++)
            {
                RefundQueryItems.Add(new RefundQueryItem()
                {
                    OutRefundNo = root.SelectSingleNode("out_refund_no_" + i).InnerText,
                    RefundId = root.SelectSingleNode("refund_id_" + i).InnerText,
                    RefundChannel = root.SelectSingleNode("refund_channel_" + i).InnerText,
                    RefundFee = root.SelectSingleNode("refund_fee_" + i).InnerText.ToInt(),
                    RefundTime = root.SelectSingleNode("refund_time_" + i).InnerText,
                    RefundStatus = root.SelectSingleNode("refund_status_" + i).InnerText
                });
            }

            return this;
        }

        /// <summary>
        /// 是否是退款成功
        /// </summary>
        /// <returns></returns>
        public bool IsRefundSuccess()
        {
            return !HasError()
                   && RefundQueryItems.Any()
                   && RefundQueryItems.First().RefundStatus == "SUCCESS";
        }

        /// <summary>
        /// 是否是退款失败
        /// </summary>
        /// <returns></returns>
        public bool IsRefundFail()
        {
            return !HasError()
                   && RefundQueryItems.Any()
                   && RefundQueryItems.First().RefundStatus == "FAIL";
        }

        /// <summary>
        /// 是否是已撤销
        /// </summary>
        /// <returns></returns>
        public bool IsCancel()
        {
            return RefundCount == 0
                   && ErrCode == "REFUND_FAIL"
                   && ErrMsg.Contains("已撤销");
        }

        /// <summary>
        /// 退款不存在
        /// </summary>
        /// <returns></returns>
        public bool IsNotExists()
        {
            return HasError() &&
                   (
                       ErrCode.ToLower().Contains("refund not exists")
                       || ErrCode.ToLower().Contains("order not exists")
                       || ErrMsg.Contains("退款不存在")
                       || ErrMsg.Contains("订单不存在")
                   );
        }


        public DateTime GetRefundSuccessTime()
        {
            DateTime.TryParseExact(RefundQueryItems.First().RefundTime, "yyyyMMddHHmmss", null, DateTimeStyles.None,
                out var paySuccessTime);

            return paySuccessTime;
        }
    }

    public class RefundQueryItem
    {
        /// <summary>
        /// 商户退款单号
        /// </summary>
        [XmlElement("out_refund_no")]
        public string OutRefundNo { get; set; }

        /// <summary>
        /// 平台退款单号
        /// </summary>
        [XmlElement("refund_id")]
        public string RefundId { get; set; }

        /// <summary>
        /// 退款渠道 ORIGINAL—原路退款，默认
        /// </summary>
        [XmlElement("refund_channel")]
        public string RefundChannel { get; set; }

        /// <summary>
        /// 退款总金额,单位为分,可以做部分退款
        /// </summary>
        [XmlElement("refund_fee")]
        public int RefundFee { get; set; }

        /// <summary>
        /// 退款时间 yyyyMMddHHmmss
        /// </summary>
        [XmlElement("refund_time")]
        public string RefundTime { get; set; }

        /// <summary>
        /// SUCCESS—退款成功
        /// FAIL—退款失败
        /// PROCESSING—退款处理中
        /// NOTSURE—未确定， 需要商户原退款单号重新发起
        /// CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者平台转账的方式进行退款。
        /// </summary>
        [XmlElement("refund_status")]
        public string RefundStatus { get; set; }
    }
}