using Fuel.Payment.Core;
using Fuel.Payment.Core.Enum;
using Fuel.Payment.Core.Models;
using Fuel.Payment.Core.Models.AllInPay;
using Fuel.Payment.Service;
using Fuel.Payment.Service.AllInPayProcessor.AllInPay.Models;
using Fuel.Payment.Service.AllInPayProcessor.AllInPay.Util;
using Fuel.Payment.Service.Factory;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1.X509;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WayneCloud.Models;
using ElectronicOrderModel = Fuel.Payment.Core.Models.ElectronicOrderModel;
using ElectronicOrderProcessResultModel = Fuel.Payment.Core.Models.ElectronicOrderProcessResultModel;
using TradeStatus = Fuel.Payment.Core.Models.TradeStatus;

namespace Fuel.Payment.Service.AllInPayProcessor.AllInPay
{

    public class AllInPayProcessor : AsyncPaymentProcessor
    {
        private readonly NLog.Logger _logger = NLog.LogManager.GetLogger("Main");
        public override async Task<GenericProcessResponse> Cancel(ElectronicOrderModel order)
        {
            //var response = DoCancel(order);
            //LogResponse(response);
            return new GenericProcessResponse()
            {
                AllInPayResponse = null
            };
        }
        /// <summary>
        /// 支付结果处理
        /// </summary>
        /// <param name="processResponse"></param>
        /// <param name="eOrder"></param>
        /// <returns></returns>
        protected override async Task<ElectronicOrderModel> PaymentResult(GenericProcessResponse processResponse, ElectronicOrderModel eOrder)
        {
            var returnCode = ReturnCode.PAY_ERROR;
            var response = processResponse.AllInPayResponse;
            if (response != null && eOrder.TradeStatus == TradeStatus.SUCCESS)
            {
                returnCode = ReturnCode.OK;
            }
            else
            {
                returnCode = ReturnCode.PAY_ERROR;

                if (!eOrder.IsRefund)
                {
                    //cancelOrder = true;

                }
            }
            List<ElectronicOrderProcessResultModel> electronicOrderProcessResultModels = new List<ElectronicOrderProcessResultModel>();
            electronicOrderProcessResultModels.Add(new ElectronicOrderProcessResultModel()
            {
                BillNumber = eOrder.BillNumber,
                ResultCode = ((int)returnCode).ToString(CultureInfo.InvariantCulture),
                ResultMessage = returnCode.ToString(),
                ErrorDetail = response != null && response.ContainsKey("retmsg") ? response["retmsg"] : "",
                RawResult = response != null && response.ContainsKey("errmsg") ? response["errmsg"] : ""
            });
            eOrder.ProcessResults = electronicOrderProcessResultModels;
            return eOrder;
        }
        /// <summary>
        /// 初始化参数
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        protected override async Task<GenericProcessResponse> Initialize(ElectronicOrderModel order)
        {
            string config = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<TongLianPayConfig xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n  <appId>00261178</appId>\r\n  <subAppId>wx32dbc8c959199561</subAppId>\r\n  <cusId>660332055410P91</cusId>\r\n  <appKey>qwe1234567</appKey>\r\n  <apiVersion>11</apiVersion>\r\n  <apiUrl>https://vsp.allinpay.com/apiweb/unitorder</apiUrl>\r\n  <notifyUrl></notifyUrl>\r\n  <queryInterval>3</queryInterval>\r\n  <queryTimeout>90</queryTimeout>\r\n</TongLianPayConfig>";
            TongLianPayConfig aliPayConfig = TongLianPayConfig.DeserializeFromXmlString(config);
            order.Config = aliPayConfig;
            return new GenericProcessResponse() {
                electronicOrderModel = order
            };
        }
        public override async Task<GenericProcessResponse> Process(ElectronicOrderModel order)
        {
            order.Config= Initialize(order).Result?.electronicOrderModel?.Config;
            order.TradeStatus = TradeStatus.PAYERROR;
            var response = new Dictionary<string, string>();
            try
            {
                if (order.Optional.ContainsKey("preCreatedBillNumber"))
                {
                    var config = (TongLianPayConfig)order.Config;
                    response = await QueryTrxResult(order, config.queryInterval, config.queryTimeout);
                }
                else
                {
                    response = await QrPay(order);
                    if (IsSuccessful(response))
                    {
                        order.TradeStatus = TradeStatus.SUCCESS;
                    }

                    if (response != null && response.ContainsKey("trxstatus") && response["trxstatus"] == "2000")
                    {
                        // 当结果码为“2000”时，商户系统可设置间隔时间(建议10秒)重新查询支付结果，直到支付成功或超时(建议40秒)
                        var config = (TongLianPayConfig)order.Config;
                        response = await QueryTrxResult(order, config.queryInterval, config.queryTimeout);
                        if (IsSuccessful(response))
                        {
                            order.TradeStatus = TradeStatus.SUCCESS;
                        }
                    }
                }

                LogResponse(response);
            }
            catch (Exception ex)
            {
                _logger.Error($"Request AllInPay exceptioned: {ex.ToString()}, try query trx result no matter what");
                if (!order.Optional.ContainsKey("preCreatedBillNumber"))
                {
                    try
                    {
                        var config = (TongLianPayConfig)order.Config;
                        response = await QueryTrxResult(order, config.queryInterval, config.queryTimeout);
                        if (IsSuccessful(response))
                        {
                            order.TradeStatus = TradeStatus.SUCCESS;
                        }
                    }
                    catch (Exception e)
                    {
                        _logger.Error($"Request AllInPay Query exceptioned: {e}");
                    }
                }
            }
            var Generic = new GenericProcessResponse()
            {
                AllInPayResponse = response
            };
            var ProcessResults = await PaymentResult(Generic, order);
            Generic.ProcessResults = ProcessResults.ProcessResults;
            return Generic;
        }

        private async Task<Dictionary<string, string>> QueryTrxResult(ElectronicOrderModel order, int interval = 3, int dueTime = 60)
        {
            _logger.Info($"AllInPay QueryTrxResult started, query interval = {interval}, dueTime = {dueTime}");
            var reponse = new GenericProcessResponse()
            {
                AllInPayResponse = new Dictionary<string, string>()
            };
            var cts = new CancellationTokenSource();
            try
            {
                await Task.WhenAny(PeriodicTask.Run(Query, QuitQuerying, order, reponse, cts, TimeSpan.FromSeconds(interval)),
                    Task.Delay(TimeSpan.FromSeconds(dueTime)));
                cts.Cancel();
            }
            catch (Exception ex)
            {
                _logger.Error($"QueryTrxResult exceptioned, msg {ex}");
            }

            return reponse.AllInPayResponse;
        }

        public override async Task<GenericProcessResponse> UnifiedOrder(ElectronicOrderModel order)
        {
            order.TradeStatus = TradeStatus.PAYERROR;
            var response = new Dictionary<string, string>();
            try
            {
                response = await PlaceUnifiedOrder(order);

                if (IsSuccessful(response))
                {
                    order.TradeStatus = TradeStatus.SUCCESS;
                }

                //if (IsQueryResponse(response) && !string.IsNullOrEmpty(response.payInfo))
                //{
                //    order.TradeStatus = TradeStatus.SUCCESS;
                //}
                if (response.ContainsKey("payinfo"))
                {
                    order.TradeStatus = TradeStatus.SUCCESS;
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"Request AllInPayV2 exceptioned: {ex.ToString()}");
            }
            return new GenericProcessResponse()
            {
                AllInPayResponse = response
            };
        }

        public async Task<Dictionary<string, string>> PlaceUnifiedOrder(ElectronicOrderModel order)
        {
            var config = (TongLianPayConfig)order.Config;
            var paramDic = BuildBasicParam(config);
            paramDic.Add("trxamt", Convert.ToInt32(order.NetAmount * 100).ToString());
            paramDic.Add("reqsn", order.BillNumber);
            paramDic.Add("body", order.Title);
            paramDic.Add("sub_appid", config.subAppId);
            paramDic.Add("paytype", "W06");
            paramDic.Add("remark", "");
            paramDic.Add("acct", order.Optional["mobilePayId"] as string);
            paramDic.Add("authcode", order.AuthCode);
            paramDic.Add("notify_url", config.notifyUrl);
            paramDic.Add("limit_pay", "");
            paramDic.Add("idno", "");
            paramDic.Add("truename", "");
            paramDic.Add("asinfo", "");
            paramDic.Add("validtime", "1");
            paramDic.Add("sign", AppUtil.signParam(paramDic, config.appKey));
            return await DoRequest(paramDic, "/pay", config);
        }

        private bool IsQueryResponse(TongLianResponseV2 response)
        {
            return response.bizCode == "2000" || response.payStatus == "2000";
        }

        public override async Task<GenericProcessResponse> Query(ElectronicOrderModel order)
        {
            order.TradeStatus = TradeStatus.PAYERROR;
            var response = await DoQuery(order);
            if (IsSuccessful(response))
            {
                order.TradeStatus = TradeStatus.SUCCESS;
            }

            LogResponse(response);
            return new GenericProcessResponse()
            {
                AllInPayResponse = response
            };
        }

        public async Task<GenericProcessResponse> Query(ElectronicOrderModel order, GenericProcessResponse reponse, CancellationTokenSource cts)
        {
            var response = await Query(order);
            if (IsSuccessful(reponse.AllInPayResponse))
            {
                cts.Cancel();
            }
            return response;
        }

        public override async Task<GenericProcessResponse> Return(ElectronicOrderModel order)
        {
            order.TradeStatus = TradeStatus.PAYERROR;
            var response = await DoCancel(order);
            if (IsSuccessful(response))
            {
                order.TradeStatus = TradeStatus.SUCCESS;
            }

            if (response != null && response.ContainsKey("trxstatus") && response["trxstatus"] == "2000")
            {
                //当结果码为“2000”时，商户系统可设置间隔时间(建议10秒)重新查询支付结果，直到支付成功或超时(建议40秒)
                var config = (TongLianPayConfig)order.Config;
                response = await QueryTrxResult(order, config.queryInterval, config.queryTimeout);
                if (IsSuccessful(response))
                {
                    order.TradeStatus = TradeStatus.SUCCESS;
                }
            }
            LogResponse(response);
            return new GenericProcessResponse()
            {
                AllInPayResponse = response
            };
        }

        public async Task<Dictionary<string, string>> Pay(ElectronicOrderModel order)
        {
            var config = (TongLianPayConfig)order.Config;
            var paramDic = BuildBasicParam(config);
            paramDic.Add("trxamt", Convert.ToInt32(order.NetAmount * 100).ToString());
            paramDic.Add("reqsn", order.BillNumber);
            paramDic.Add("paytype", "W01");
            paramDic.Add("body", order.Title);
            paramDic.Add("remark", "");
            paramDic.Add("acct", "");
            paramDic.Add("authcode", order.AuthCode);
            paramDic.Add("notify_url", config.notifyUrl);
            paramDic.Add("limit_pay", "");
            paramDic.Add("idno", "");
            paramDic.Add("truename", "");
            paramDic.Add("asinfo", "");
            paramDic.Add("sign", AppUtil.signParam(paramDic, config.appKey));
            return await DoRequest(paramDic, "/pay", config);
        }

        public async Task<Dictionary<string, string>> QrPay(ElectronicOrderModel order)
        {
            var config = (TongLianPayConfig)order.Config;
            var paramDic = BuildBasicParam(config);
            paramDic.Add("trxamt", Convert.ToInt32(order.NetAmount * 100).ToString());
            paramDic.Add("reqsn", order.BillNumber);
            paramDic.Add("body", order.Title);
            paramDic.Add("remark", "");
            paramDic.Add("acct", "");
            paramDic.Add("authcode", order.AuthCode);
            paramDic.Add("notify_url", config.notifyUrl);
            paramDic.Add("limit_pay", "");
            paramDic.Add("idno", "");
            paramDic.Add("truename", "");
            paramDic.Add("asinfo", "");
            paramDic.Add("sign", AppUtil.signParam(paramDic, config.appKey));
            return await DoRequest(paramDic, "/scanqrpay", config);
        }

        public async Task<Dictionary<string, string>> DoCancel(ElectronicOrderModel order)
        {
            var config = (TongLianPayConfig)order.Config;
            var paramDic = BuildBasicParam(config);
            paramDic.Add("trxamt", Convert.ToInt32(order.NetAmount * 100).ToString());
            paramDic.Add("reqsn", DateTime.Now.ToFileTime().ToString());
            paramDic.Add("oldtrxid", "");
            paramDic.Add("oldreqsn", order.BillNumber);
            paramDic.Add("sign", AppUtil.signParam(paramDic, config.appKey));
            return await DoRequest(paramDic, "/cancel", config);
        }

        public async Task<Dictionary<string, string>> Refund(ElectronicOrderModel order)
        {
            var config = (TongLianPayConfig)order.Config;
            var paramDic = BuildBasicParam(config);
            paramDic.Add("trxamt", Convert.ToInt32(order.NetAmount * 100).ToString());
            paramDic.Add("reqsn", DateTime.Now.ToFileTime().ToString());
            paramDic.Add("oldtrxid", "");
            paramDic.Add("oldreqsn", order.BillNumber);
            paramDic.Add("sign", AppUtil.signParam(paramDic, config.appKey));
            return await DoRequest(paramDic, "/refund", config);
        }

        public async Task<Dictionary<string, string>> DoQuery(ElectronicOrderModel order)
        {
            //String reqsn, String trxid
            var config = (TongLianPayConfig)order.Config;
            var paramDic = BuildBasicParam(config);
            paramDic.Add("reqsn", order.BillNumber);
            paramDic.Add("trxid", "");
            paramDic.Add("sign", AppUtil.signParam(paramDic, config.appKey));
            return await DoRequest(paramDic, "/query", config);
        }

        private Dictionary<string, string> BuildBasicParam(TongLianPayConfig config)
        {
            var paramDic = new Dictionary<string, string>();
            paramDic.Add("cusid", config.cusId);
            paramDic.Add("appid", config.appId);
            paramDic.Add("version", config.apiVersion);
            paramDic.Add("randomstr", DateTime.Now.ToFileTime().ToString());
            return paramDic;

        }

        private async Task<Dictionary<string, string>> DoRequest(Dictionary<string, string> param, string url, TongLianPayConfig config)
        {
            var rsp = await HttpUtil.CreatePostHttpResponseAsync(config.apiUrl + url, param, Encoding.UTF8);
            _logger.Info($"AllInPay recieved raw response: {rsp}");
            var rspDic = (Dictionary<string, string>)JsonConvert.DeserializeObject(rsp, typeof(Dictionary<string, string>));
            if ("SUCCESS".Equals(rspDic["retcode"]))//验签
            {
                var signRsp = rspDic["sign"];
                rspDic.Remove("sign");
                var sign = AppUtil.signParam(rspDic, config.appKey);
                if (signRsp.Equals(sign))
                {
                    return rspDic;
                }
                else
                    throw new Exception("验签失败");

            }
            else
            {
                throw new Exception(rspDic["retmsg"]);
            }
        }

        private void LogResponse(Dictionary<string, string> rspDic)
        {
            var rsp = "请求返回数据:\n";
            if (rspDic != null)
            {
                foreach (var item in rspDic)
                {
                    rsp += item.Key + "-----" + item.Value + ";\n";
                }
            }
            _logger.Info($"AllInPay recieved response: {rsp}");
        }

        private bool IsSuccessful(Dictionary<string, string> response)
        {
            if (response != null && response.Count > 0)
            {
                if (response.ContainsKey("retcode") &&
                    response["retcode"] == "SUCCESS")
                {
                    if (response.ContainsKey("trxstatus") &&
                    response["trxstatus"] == "0000")
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private bool PayFailed(Dictionary<string, string> response)
        {
            if (response != null && response.Count > 0)
            {
                if (response.ContainsKey("retcode") &&
                    response["retcode"] == "SUCCESS")
                {
                    if (response.ContainsKey("trxstatus") &&
                    response["trxstatus"] == "3045")
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private bool QuitQuerying(Dictionary<string, string> response)
        {
            return IsSuccessful(response) || PayFailed(response);
        }

        public override Task<GenericProcessResponse> Query(ElectronicOrderModel order, int count, int interval)
        {
            throw new NotImplementedException();
        }
    }
}
public class PeriodicTask
{
    public static async Task Run(Func<ElectronicOrderModel, GenericProcessResponse, CancellationTokenSource, Task<GenericProcessResponse>> process,
        Func<Dictionary<string, string>, bool> predicate, ElectronicOrderModel order,
        GenericProcessResponse response, CancellationTokenSource cts, TimeSpan period)
    {
        while (!cts.Token.IsCancellationRequested)
        {
            if (!cts.Token.IsCancellationRequested)
            {
                response = await process(order, response, cts);
                if (response != null && predicate(response.AllInPayResponse))
                    return;
            }
            await Task.Delay(period, cts.Token);
        }
    }

}
