using System;
using System.Collections.Generic;
using Aop.Api;
using Library;
using Microsoft.AspNetCore.Http;
using Aop.Api.Request;
using Aop.Api.Response;
using Aop.Api.Util;

namespace MySystem
{
    public class AlipayFunction
    {
        private string AppId = "2021003116616751";
        private string PrivateKey = "MIIEpAIBAAKCAQEA1KjMzZJIRG6QQ3+c/euVrc+8RR0xMw6A+EONSKhJq4Bg+rtxQPCfdF2bpZ4NMaSqfalSiLoxrZSYBYOZhpDP67i9LXGUoFCWdRL7ROTqJvuU6KyEeMplQ6Q3uwWbuKbh9COt0vhqn/pjlUsomTwq+DRQv10awynkZikqceXdP0EH4iGZG0hyerEP5yLHpHiggf4f7TOsovHX+fGLPmWFO1zUTHHbz7HxU4BQKn3yuje4yMhoyv5h/wZzeVwvj+Qti8Hlh351rF0f5BHwN1YMGIrWuPU5bF8OMHS/UXPxh7Bs795ZZyplYztTz26QfKfLWVVsLOng4pvgPS+OgzZydwIDAQABAoIBAEu6mMQT9Zw46zK+PP/HZxPwSBEsphqSbab7F1LqauGh4+cl3NzNU1szAnxl3jjxdK0vIO8DrzErGz/Lb16WLxS4QtXt/olgaVPjoIsWIbQkHxEEbmA9YvZFgnsdMij9dLVmBz57rCywE8pUa262GG8u4hpjY2Zggq9GtZC91J3zOeETBG828gU+FLHGcDpfz7pD1jC0noDfDRxmIImOMZvChIvvY+tm6MpySXN8lw1vxhLc0aZbKSQkuVyCyB4fIsdJJvh2dRPiY+BA0jXNK3mWwnnHzac/9JXqWFlwk6iPIIjXPUldz7Zq3EpCI+9p+UqLtIu6BAUbk1biFTt8xMECgYEA+2iIxZfdl1N1suA/aEbUdjd0kxeeOsGv7Ps0rOYn+4/q1dkUukg2V6VRy3E8BUt+9zLPTR8DmL7oBi+kDsGehjHlH7U6Pe8qKszB4ufQBDHc71yg9liqOWa4s9VoBD0VIU9CO0HtYjRor7rVuUzp+j58SLP7wIEPGEwdgjeYENECgYEA2IsYEyHiwhjy5rx7fmv3duZC5zyesIqxdAz79AuZ7gnpNEhddi5cEpcibnVmwZliCe6SoLzXZ6difEfD4VmLsYEAWqf5sqJ2PswZmHtA9F4We9WUe2zj+pFG0yCCVrcbDZXzQYaLmyuMNe/jpgyY178czohpnvQlr++bYa9DYMcCgYEAqGX6xy/UM9qpiel/T1+yTIUUxroZOI4oQvp47B82ROC/kgJYSfa4v7hys2zjoUBSiU41YRkXFac6T3p1z5SNlKGzMav4mSer/QMuE8jmowirToGjJ594Vf6iVYLqq3wmvSsT2BFu6krknGDva7FDQGW+Zgx44xcPf1zsnx6R8yECgYEAtfFA3Cp3lbBSvy4U8ScUOPHFuvbDOwB9k02pkOcCgfAP4p7+8GKJeBFGm9rG6NnQdxneV3Hz5yLL7DJ8UebkKdODEajbc41vntnsk6LT877uU0QkSwQ2FX1lLdW9zdBxyZt5VVAQEuOnHlaeRxGEhpoMQTh6zlTDKa1AN/aDvVcCgYApytvSEdTpKcQuEyPOfbQv2pXYujCacMFIRHvJW/HvX7yaZSAvSYK+lw8l53bTbJpJ3pq/1Tol6tyjY7HRsVvQ68Jn1MApARMlldn1GoAPcgDFzlJCB0JCOUAE1rBS5lA97wQ1YhI8qBRqaE7Qrtf4D5oZdEjbtq8VCeIaD9huIQ==";
        private string PublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1KjMzZJIRG6QQ3+c/euVrc+8RR0xMw6A+EONSKhJq4Bg+rtxQPCfdF2bpZ4NMaSqfalSiLoxrZSYBYOZhpDP67i9LXGUoFCWdRL7ROTqJvuU6KyEeMplQ6Q3uwWbuKbh9COt0vhqn/pjlUsomTwq+DRQv10awynkZikqceXdP0EH4iGZG0hyerEP5yLHpHiggf4f7TOsovHX+fGLPmWFO1zUTHHbz7HxU4BQKn3yuje4yMhoyv5h/wZzeVwvj+Qti8Hlh351rF0f5BHwN1YMGIrWuPU5bF8OMHS/UXPxh7Bs795ZZyplYztTz26QfKfLWVVsLOng4pvgPS+OgzZydwIDAQAB";
        private string AlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxycehrmnTl2IaIAECP+0HWc1eWGM/T6x022K7K6fdf+xoyC97TBJaG4G3Bcon4gsJX+Sad5IA9OJIQ4eN1joM35hIlwcFZ6MmCuVXx/SMAKThIjK0jsRc6aTxVQG+GVCgS7dXMKb4Sm+vK2wEM6xtDeqcfYMB0BqGZRvxbIV59a2ooPrha4FkV6nNC9DQefzC0picHXV64oYUjMM2ed4ASTQVds7HP9BZfalz//APZcWdBV08f+xv7n79Twz/gNtVAadfuTAlcjsS6aK+G/OrZtr/diuemeRPRUKlVhcr5xOQDhqBgtdIw8M9Wp6I4ULXRlthKVBWToH9j6n9vDIiwIDAQAB";
        public AlipayFunction()
        {
        }


        #region 代商家签约

        //（开启事务）接口创建应用事务，返回生成代商户操作事务编号 batch_no
        public string GetBatchNo(string AlipayAccount, string Name, string Mobile, string Email)
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayOpenAgentCreateRequest request = new AlipayOpenAgentCreateRequest();
            request.BizContent = "{" +
            "\"account\":\"" + AlipayAccount + "\"," +
            "\"contact_info\":{" +
            "\"contact_name\":\"" + Name + "\"," +
            "\"contact_mobile\":\"" + Mobile + "\"," +
            "\"contact_email\":\"" + Email + "\"" +
            "}" +
            "}";
            string result = "";
            try
            {
                AlipayOpenAgentCreateResponse response = client.Execute(request);
                result = response.Body;
                function.WriteLog(result, "开启事务");
                //{"alipay_open_agent_create_response":{"code":"10000","msg":"Success","batch_no":"2022021011321326200059849","batch_status":"init"},"sign":"su+weyK1CZEXES8mdckalg16J4BELTQeVNJSpXVYg3nh5g3E7jDh/mQctkjH8HbM0RybQSahZ2j60aUTossPMXqdq2nPRkR4c/kM34toFFNU/2p7jqo9k/MbB1JotW+qFI+C/GCX/9mZQqm2tSQdYIiZlCsEtP13ZP2EQ6momEZrApyLQYUl1H54PojJgqo6zGKDXTnXuZcpi/VPP5YoWhYMx8WPFMS6+T3zr+LNPDOI94j5vDdUHQdjFAGiQMyyhfNOBcFFi18bAfWhPqlLWwblCZamTHN/QaOHo+fkBZeo9uKqrnSHPn8XW0tDAIf1qNUfY2eBzYZUIqWKbz509A=="}
            }
            catch (Exception ex)
            {
                function.WriteLog(ex.ToString(), "接口创建应用事务异常");
                result = "";
            }
            return result;
        }
        //代签约产品通用接口，代商家发起签约产品申请
        public string CommonSign(string BatchNo, string MccCode, string BusinessLicenseNo = "", string BusinessLicensePicPath = "", string SpecialLicensePicPath = "", string ShopScenePicPath = "", string ShopSignBoardPicPath = "")
        { 
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayOpenAgentCommonSignRequest request = new AlipayOpenAgentCommonSignRequest();
            request.BatchNo = BatchNo;
            request.MccCode = MccCode; //软件系统商 D_D05_7372
            if(string.IsNullOrEmpty(SpecialLicensePicPath)) SpecialLicensePicPath = BusinessLicensePicPath;
            FileItem SpecialLicensePic = new FileItem(SpecialLicensePicPath);
            request.SpecialLicensePic = SpecialLicensePic;
            if (!string.IsNullOrEmpty(BusinessLicenseNo))
            {
                request.BusinessLicenseNo = BusinessLicenseNo;  //营业执照号码
            }
            if (!string.IsNullOrEmpty(BusinessLicensePicPath))
            {
                FileItem BusinessLicensePic = new FileItem(BusinessLicensePicPath);
                request.BusinessLicensePic = BusinessLicensePic; //营业执照图片。被代创建商户运营主体为个人账户必填，企业账户无需填写
            }
            FileItem BusinessLicenseAuthPic = new FileItem(BusinessLicensePicPath);
            request.BusinessLicenseAuthPic = BusinessLicenseAuthPic;
            request.LongTerm = true;
            request.DateLimitation = "长期";
            if (!string.IsNullOrEmpty(ShopScenePicPath))
            {
                FileItem ShopScenePic = new FileItem(ShopScenePicPath);
                request.ShopScenePic = ShopScenePic;
            }
            if (!string.IsNullOrEmpty(ShopSignBoardPicPath))
            {
                FileItem ShopSignBoardPic = new FileItem(ShopSignBoardPicPath);
                request.ShopSignBoardPic = ShopSignBoardPic;
            }
            request.ProductCode = "FACE_TO_FACE_PAYMENT"; //isv要代商户签约产品码，产品码是支付宝内部对产品的唯一标识，例如：QUICK_WAP_WAY:手机网站支付，FACE_TO_FACE_PAYMENT:当面付
            request.AppName = "客小爽";
            // FileItem AppDemo = new FileItem(BusinessLicensePicPath);
            // request.AppDemo = AppDemo;
            List<string> WebSites = new List<string>();
            WebSites.Add("http://www.kexiaoshuang.com/");
            request.WebSites = WebSites;
            request.AlipayLifeName = "客小爽";
            request.WechatOfficialAccountName = "客小爽";
            // FileItem WebSitesLoa = new FileItem(BusinessLicensePicPath);
            // request.WebSitesLoa = WebSitesLoa;
            request.WebTestAccount = "testAccount";
            request.WebTestAccountPassword = "testPassword";
            FileItem WebHomeScreenshot = new FileItem(BusinessLicensePicPath);
            request.WebHomeScreenshot = WebHomeScreenshot;
            FileItem WebItemScreenshot = new FileItem(BusinessLicensePicPath);
            request.WebItemScreenshot = WebItemScreenshot;
            FileItem WebPayScreenshot = new FileItem(BusinessLicensePicPath);
            request.WebPayScreenshot = WebPayScreenshot;
            request.WebStatus = "已上线";
            string result = "";
            try
            {
                AlipayOpenAgentCommonSignResponse response = client.Execute(request);
                result = response.Body;
                function.WriteLog(result, "代商家发起签约产品申请");
                //{"alipay_open_agent_common_sign_response":{"code":"10000","msg":"Success"},"sign":"qt0DiXFXIJ7mX+W2+IX+cyYXx8ROGe8yxesXHGNltxpEv/s/zW16xzf4HQLtUlaAiWf3DiD2QV7Hj+REyoZw9AcktDAmlobcjQ28lTYufPECZoUJHpkn9VpGB932FC0hScVwCbsxQakH84MGT4cmjr1hCuSs7+XogdhlCTIKjau1e7ZglLnt7f1NqT8JnljVhmvkkE9gJTLq5H+Zq6XbFfBVptvM9w09HdjfhrsxAXJyQ4yU6JYX2tUYsRGz8ZrveDQMvXKTN9jnwKE9hh8ik6Sq49eUqfutV9GkKqhC96+Vy3nOTOTnPoECXZkco1wP5jsqHottWVsRV+NxdylnTw=="}
            }
            catch (Exception ex)
            {
                function.WriteLog(ex.ToString(), "代签约产品通用接口异常");
                result = "";
            }
            return result;
        }
        //代商户签约，提交信息确认接口
        public string CommonSignConfirm(string BatchNo)
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayOpenAgentCommonsignConfirmRequest request= new AlipayOpenAgentCommonsignConfirmRequest();
            request.BizContent="{" +
            "\"batch_no\":\"" + BatchNo + "\"" +
            "}";
            string result = "";
            try
            {
                AlipayOpenAgentCommonsignConfirmResponse response = client.Execute(request);
                result = response.Body;
                function.WriteLog(result, "提交信息确认");
                //{"alipay_open_agent_order_query_response":{"code":"10000","msg":"Success","order_no":"20220210034000100000015895929361","product_agent_status_infos":[{"product_code":"QUICK_WAP_WAY","product_name":"手机网站支付","status":"WAIT_CONFIRM"}],"order_status":"MERCHANT_CONFIRM","confirm_url":"https:\/\/openhome.alipay.com\/isv\/settling\/confirm.htm?orderNo=20220210034000100000015895929361","merchant_pid":"2088012934025363"},"sign":"mgdhauHMV9352S3FVrQmesXvHOrk633FX/EOXRYdc2ix5phCBZJ2KZRRP9MWJ566YEtWbnQlAJzHVS9X29hjgiJWOQ/wCidql4AoSAYYeqPtxiqKAZw/QEM/du5AdbWC0xBmmkQljXF9Hx8cm+IrOyPMSJXIw4Tqpm/T96YBwhsjw4Xr5dcUcvF6HX9h/i5FSdIJODxQ26PJcqQ98GQ3Y50YhTpPQkIPDFVE2QzcL6dvuhBOpwu5KbTxvgzS8Wtm3G6nMbzJ33Cv/I2lhTCIMHz90c9bvyjJpWxPWBzywO2zzv7+EZCbDkZGkdRic9l5s6qac+ZVMHkPbveaZ2wyig=="}
            }
            catch (Exception ex)
            {
                function.WriteLog(ex.ToString(), "接口创建应用事务异常");
                result = "";
            }
            return result;
        }

        #endregion

        #region （查询申请单状态）查询签约申请的结果
        public string QuerySignStatus(string BatchNo)
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayOpenAgentOrderQueryRequest  request= new AlipayOpenAgentOrderQueryRequest() ;
            request.BizContent="{" +
            "  \"batch_no\":\"" + BatchNo + "\"" +
            "}";
            string result = "";
            try
            {
                AlipayOpenAgentOrderQueryResponse response = client.Execute(request);
                result = response.Body;
                function.WriteLog(result, "查询签约申请的结果");
            }
            catch (Exception ex)
            {
                function.WriteLog(ex.ToString(), "查询签约申请的结果异常");
                result = "";
            }
            return result;
        }

        #endregion
        
        #region 小程序支付请调用MySystemLib下的统一收单交易创建，返回交易号返给小程序请求支付my.tradePay
        public string GetToken()
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayOpenAuthTokenAppRequest request = new AlipayOpenAuthTokenAppRequest();
            request.BizContent = "{" +
            "\"grant_type\":\"authorization_code\"," +
            "\"code\":\"P16be77ee92264acc99553528b8a7103\"" +
            "  }";
            string result = "";
            try
            {
                AlipayOpenAuthTokenAppResponse response = client.Execute(request);
                result = response.Body;
                //{"alipay_open_auth_token_app_response":{"code":"10000","msg":"Success","tokens":[{"app_auth_token":"202202BBd8c1365cd09b4a27a0c0f0b7f8cabX03","app_refresh_token":"202202BB539f0f5aa99f4b509aa3628b0af25X03","auth_app_id":"2021003116654736","expires_in":31536000,"re_expires_in":32140800,"user_id":"2088141704579033"}]},"sign":"VZINXguZZFvVDyhVp/iMK5BWXYnDYLvxYEMEZTZOVUl9MUy6xQesDzpwBBUclLLU+QgrKpeekaxj9zgwRXdh7cKlVot2lkVPkGdfkqcK/B9t8kxPXa13WIszcROCqIutlcBZW9pCIUAbWRjorDvzRCc5rLNfSBAjEldZDA0rGOPeWJXM/5uLi/70oTwyO6eaEbKdRyHLjUwp0qtolhXIvyf9HL1HbZMGtyY/Hzq35BmhB/jQ4XIVdcOEpFtNoC/1S/viLOsBCD2m4aNCGUY0i24lr92dRsEinZlCxAQq+FK6ILNUnDmBUjNkPTycDrJFw+w9sEC6AcZodNB6OC8XTw=="}
            }
            catch (Exception ex)
            {
                function.WriteLog(ex.ToString(), "支付宝统一收单交易创建(获取authtoken)异常");
                result = "";
            }
            return result;
        }

        public string CreateTrade(string OrderNo, string Subject, string Amount, string BuyerId, string Notify_Url, string Token)
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
            request.SetNotifyUrl(Notify_Url);
            request.BizContent = "{" +
            "\"out_trade_no\":\"" + OrderNo + "\"," +
            "\"total_amount\":" + Amount + "," +
            "\"subject\":\"" + Subject + "\"," +
            "\"buyer_id\":\"" + BuyerId + "\"," +
            "\"timeout_express\":\"10m\"" +
            "}";
            string result = "";
            try
            {
                AlipayTradeCreateResponse response = client.Execute(request, null, Token);
                result = response.Body;
            }
            catch (Exception ex)
            {
                function.WriteLog(ex.ToString(), "支付宝统一收单交易创建异常");
                result = "";
            }
            return result;
        }

        public string QueryTrade(string OrderNo, string Token)
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            request.BizContent = "{" +
            "\"out_trade_no\":\"" + OrderNo + "\"" +
            "}";
            string result = "";
            try
            {
                AlipayTradeQueryResponse response = client.Execute(request, null, Token);
                result = response.Body;
            }
            catch (Exception ex)
            {
                function.WriteLog(ex.ToString(), "统一收单线下交易查询异常");
                result = "";
            }
            return result;
        }

        #endregion

        #region 退款

        public string Refund(string TradeNo, string Amount, string Token)
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            request.BizContent = "{" +
            "\"trade_no\":\"" + TradeNo + "\"," +
            "\"refund_amount\":" + Amount + "" +
            "}";
            string result = "";
            try
            {
                AlipayTradeRefundResponse response = client.Execute(request, null, Token);
                result = response.Body;
            }
            catch (Exception ex)
            {
                function.WriteLog(ex.ToString(), "退款异常");
                result = "";
            }
            return result;
        }

        #endregion

        #region 分账
        public string Settle(string OrderNo, string TradeNo, List<RoyaltyParameters> Parameters)
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayTradeOrderSettleRequest  request= new AlipayTradeOrderSettleRequest();
            string royalty_parameters = "";
            foreach (RoyaltyParameters Parameter in Parameters)
            {
                royalty_parameters += "    {" +
                "      \"royalty_type\":\"transfer\"," +
                "      \"trans_in_type\":\"loginName\"," +
                "      \"trans_in\":\"" + Parameter.Account + "\"," +
                "      \"amount\":" + Parameter.Amount + "," +
                "      \"trans_in_name\":\"" + Parameter.Name + "\"" +
                "    },";
            }
            request.BizContent = "{" +
            "  \"out_request_no\":\"" + OrderNo + "\"," +
            "  \"trade_no\":\"" + TradeNo + "\"," +
            "  \"royalty_parameters\":[" +
            royalty_parameters.TrimEnd(',') +
            "  ]" +
            "}";
            string result = "";
            try
            {
                AlipayTradeOrderSettleResponse response = client.Execute(request);
                result = response.Body;
            }
            catch (Exception ex)
            {
                function.WriteLog(ex.ToString(), "分账异常");
                result = "";
            }
            return result;
        }

        #endregion


    }
}
