using Fuel.Payment.Core.Models;
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 System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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
            };
        }
        public override async Task<GenericProcessResponse> Initialize(ElectronicOrderModel order)
        {
            string config = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<AliPayConfig xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n  <alipay_public_key>alipay_rsa_public_key_dev.pem</alipay_public_key>\r\n  <merchant_private_key>rsa_private_key_dev.pem</merchant_private_key>\r\n  <merchant_public_key>rsa_public_key_dev.pem</merchant_public_key>\r\n  <appId>2021003112655779</appId>\r\n  <serverUrl>https://openapi.alipay.com/gateway.do</serverUrl>\r\n  <mapiUrl>https://mapi.alipay.com/gateway.do</mapiUrl>\r\n  <pid>2088222976038113</pid>\r\n  <charset>utf-8</charset>\r\n  <sign_type>RSA2</sign_type>\r\n  <version>1.0</version>\r\n</AliPayConfig>";
            return new GenericProcessResponse() {
                electronicOrderModel = order
            };
        }
        public override async Task<GenericProcessResponse> Process(ElectronicOrderModel order)
        {
            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}");
                    }
                }
            }
            return new GenericProcessResponse()
            {
                AllInPayResponse = response
            };
        }

        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);
        }
    }

}
