using System;
using System.Collections.Generic;
using Library;
using LitJson;
using System.Linq;
using System.Data;
using System.Threading;
using MySystem.PxcModels;
using System.Security.Cryptography;
using System.Text;

namespace MySystem
{
    public class SetDepositPostService
    {
        public readonly static SetDepositPostService Instance = new SetDepositPostService();
        private SetDepositPostService()
        { }

        public void Start()
        {
            Thread th = new Thread(dosomething);
            th.IsBackground = true;
            th.Start();
        }

        public void dosomething()
        {
            while (true)
            {
                string data = RedisDbconn.Instance.RPop<string>("SetDepositPostQueue");
                if (!string.IsNullOrEmpty(data))
                {
                    try
                    {
                        WebCMSEntities db = new WebCMSEntities();
                        JsonData jsonObj = JsonMapper.ToObject(data);
                        string PosIds = jsonObj["PosId"].ToString();
                        int Kind = int.Parse(function.CheckInt(jsonObj["Kind"].ToString()));
                        int RecordId = 0;
                        if(data.Contains("\"RecordId\""))
                        {
                            RecordId = int.Parse(function.CheckInt(jsonObj["RecordId"].ToString()));
                        }
                        string OpMan = jsonObj["OpMan"].ToString();
                        if(!string.IsNullOrEmpty(PosIds) && Kind > 0)
                        {
                            List<int> ids = new List<int>();
                            string[] PosIdList = PosIds.Split(',');
                            foreach(string sub in PosIdList)
                            {
                                ids.Add(int.Parse(sub));
                            }
                            List<KqProducts> brands = db.KqProducts.ToList();
                            List<PosMachinesTwo> poslist = db.PosMachinesTwo.Where(m => ids.Contains(m.Id)).ToList();
                            List<int> mids = poslist.Select(m => m.BindMerchantId).ToList();
                            List<PosMerchantInfo> merchantlist = db.PosMerchantInfo.Where(m => mids.Contains(m.Id)).ToList();
                            foreach(PosMachinesTwo pos in poslist)
                            {
                                PosMerchantInfo merchant = merchantlist.FirstOrDefault(m => m.Id == pos.BindMerchantId);
                                if(merchant != null)
                                {
                                    decimal Fee = 0.63M;
                                    int addRate = 0;
                                    if(pos.BrandId != 12 && pos.BrandId != 13)
                                    {
                                        if(Kind == 1) 
                                        {
                                            addRate = 3;
                                        }
                                        else
                                        {
                                            addRate = 0;
                                            if(Kind == 3)
                                            { 
                                                Fee = 0.6M;
                                            }
                                        }
                                    }
                                    if(pos.BrandId == 12 || pos.BrandId == 13)
                                    {
                                        if(Kind > 1) Fee = 0.6M;
                                    }
                                    if(pos.BrandId == 1 || pos.BrandId == 3) //金控
                                    {
                                        addRate = addRate * 100;
                                        string content = function.GetWebRequest("http://connect.kexiaoshuang.com/home/setfee?merNo=" + merchant.KqMerNo + "&sn=" + pos.PosSn + "&fee=" + Fee + "&addRate=" + addRate);
                                        if(content.Contains("|"))
                                        {
                                            content = content.Split("|")[1];
                                            JsonData obj = JsonMapper.ToObject(content);
                                            if(obj["errorCode"].ToString() == "0000")
                                            {
                                                pos.SeoDescription = "设置成功";
                                                SetRecordResult(db, RecordId, 1, "设置成功");
                                                db.SaveChanges();
                                            }
                                            else
                                            {
                                                string msg = obj["errorCodeDesc"].ToString();
                                                pos.SeoDescription = msg;
                                                SetRecordResult(db, RecordId, -1, msg);
                                                db.SaveChanges();
                                            }
                                        }
                                        else
                                        {
                                            JsonData obj = JsonMapper.ToObject(content);
                                            string msg = obj["message"].ToString();
                                            pos.SeoDescription = msg;
                                            SetRecordResult(db, RecordId, -1, msg);
                                            db.SaveChanges();
                                        }
                                    }
                                    else if(pos.BrandId == 2) //开店宝
                                    {
                                        Fee = Fee / 100;
                                        string content = ModifyFee(pos.PosSn, Fee, addRate.ToString());
                                        JsonData obj = JsonMapper.ToObject(content);
                                        if(content.Contains("orderNo"))
                                        {
                                            pos.SeoDescription = "提交成功|" + obj["orderNo"].ToString() + "|" + RecordId;
                                            // SetRecordResult(db, RecordId, 1, "设置成功");
                                            db.SaveChanges();
                                        }
                                        else
                                        {
                                            string msg = obj["msg"].ToString();
                                            pos.SeoDescription = msg;
                                            SetRecordResult(db, RecordId, -1, msg);
                                            db.SaveChanges();
                                        }
                                    }
                                    else if(pos.BrandId == 4 || pos.BrandId == 5) //乐刷
                                    {
                                        // 电签
                                        // 电签标准0.63 729702301652492288
                                        // 电签优惠0.63 729702442300088320
                                        // 电签pos不加  696339175297294336

                                        // 大POS
                                        // PY-传统POS标准0.63 554666598481842176
                                        // PY-传统POS优惠0.63 683857388021264384
                                        // 大pos不加  698228081038991360

                                        // 大POS
                                        // 大POS标准0.6：713806109336940544 
                                        // 大POS优惠0.6：713806774515802112 

                                        // 电签POS
                                        // 电签标准0.6：712391426860134400 
                                        // 电签优惠0.6：712391668250718208 
                                        // S0电签pos不加：696339175297294336
                                        string bzConfigId = "", yhConfigId = "", surfeeConfigId = "";
                                        if(pos.BrandId == 4)
                                        {
                                            if(Kind == 1)
                                            {
                                                bzConfigId = "729702301652492288";
                                                yhConfigId = "729702442300088320";
                                                surfeeConfigId = "696339175297294336";
                                            }
                                            else
                                            {
                                                bzConfigId = "712391426860134400";
                                                yhConfigId = "712391668250718208";
                                                surfeeConfigId = "696339175297294336";
                                            }
                                        }
                                        else
                                        {
                                            if(Kind == 1)
                                            {
                                                bzConfigId = "554666598481842176";
                                                yhConfigId = "683857388021264384";
                                                surfeeConfigId = "698228081038991360";
                                            }
                                            else
                                            {
                                                bzConfigId = "713806109336940544";
                                                yhConfigId = "713806774515802112";
                                                surfeeConfigId = "698228081038991360";
                                            }
                                        }
                                        string content = SetFeeForBrand(pos.PosSn, bzConfigId, yhConfigId, surfeeConfigId, pos.BrandId);
                                        JsonData obj = JsonMapper.ToObject(content);
                                        if(obj["code"].ToString() == "0")
                                        {
                                            pos.SeoDescription = "设置成功";
                                            SetRecordResult(db, RecordId, 1, "设置成功");
                                            db.SaveChanges();
                                        }
                                        else
                                        {
                                            string msg = obj["msg"].ToString();
                                            pos.SeoDescription = msg;
                                            SetRecordResult(db, RecordId, -1, msg);
                                            db.SaveChanges();
                                        }
                                    }
                                    else if(pos.BrandId == 7) //盛付通
                                    {
                                        string content = SetFeeForSft(merchant.KqMerNo, Fee.ToString("f4"), addRate.ToString());
                                        JsonData obj = JsonMapper.ToObject(content);
                                        if(obj["respCode"].ToString() == "00")
                                        {
                                            pos.SeoDescription = "设置成功";
                                            SetRecordResult(db, RecordId, 1, "设置成功");
                                            db.SaveChanges();
                                        }
                                        else
                                        {
                                            string msg = obj["errorMsg"].ToString();
                                            pos.SeoDescription = msg;
                                            SetRecordResult(db, RecordId, -1, msg);
                                            db.SaveChanges();
                                        }
                                    }
                                    // else if(pos.BrandId == 6) //立刷
                                    // {
                                    //     string content = SetLiSFee(pos.PosSn, Fee);
                                    //     JsonData obj = JsonMapper.ToObject(content);
                                    //     if (obj["ret_code"].ToString() == "00")
                                    //     { 
                                    //         if(Kind == 1)
                                    //         {
                                    //             pos.UpFeeFlag = 1;
                                    //             pos.UpFeeMan = OpMan;
                                    //             pos.UpFeeDate = DateTime.Now;
                                    //         }
                                    //         else if(Kind == 2)
                                    //         {
                                    //             pos.DownFeeFlag = 1;
                                    //             pos.DownFeeMan = OpMan;
                                    //             pos.DownFeeDate = DateTime.Now;
                                    //             SetRecordResult(db, RecordId, 1);
                                    //         }
                                    //         db.SaveChanges();
                                    //     }
                                    //     else
                                    //     {
                                    //         string msg = obj["ret_msg"].ToString();
                                    //         pos.SeoDescription = msg;
                                    //         SetRecordResult(db, RecordId, -1, msg);
                                    //         db.SaveChanges();
                                    //     }
                                    // }
                                    else if(pos.BrandId == 8 || pos.BrandId == 9) //海科
                                    {
                                        // 【融通金宝大POS】
                                        // 584068951081226240    大POS标准贷0.60|借0.50
                                        // 584070145207963648    大POS优惠贷0.60|借0.5
                                        // 574600660289888256    大POS不加

                                        // 691739824478494720    大POS标准贷0.63|借0.50
                                        // 691740128238383104    大POS优惠贷0.63|借0.50
                                        // 574600660289888256    大POS不加

                                        // 【融通金宝电签POS】
                                        // 585167132691009536    电签POS标准贷0.60|借0.50
                                        // 579355312831074304    电签POS优惠贷0.6|借0.5
                                        // 570331704834170880    电签POS不加

                                        // 684753829778436096    电签POS标准贷0.63|借0.50
                                        // 684754046342934528    电签POS优惠贷0.63|借0.5
                                        // 570331704834170880    电签POS不加
                                        string bzConfigId = "", yhConfigId = "", surfeeConfigId = "";
                                        if(pos.BrandId == 8)
                                        {
                                            if(Kind == 1)
                                            {
                                                bzConfigId = "684753829778436096";
                                                yhConfigId = "684754046342934528";
                                                surfeeConfigId = "570331704834170880";
                                            }
                                            else
                                            {
                                                bzConfigId = "585167132691009536";
                                                yhConfigId = "579355312831074304";
                                                surfeeConfigId = "570331704834170880";
                                            }
                                        }
                                        else
                                        {
                                            if(Kind == 1)
                                            {
                                                bzConfigId = "691739824478494720";
                                                yhConfigId = "691740128238383104";
                                                surfeeConfigId = "574600660289888256";
                                            }
                                            else
                                            {
                                                bzConfigId = "584068951081226240";
                                                yhConfigId = "584070145207963648";
                                                surfeeConfigId = "574600660289888256";
                                            }
                                        }
                                        string content = HKSetFeeForBrand(pos.PosSn, bzConfigId, yhConfigId, surfeeConfigId, pos.BrandId);
                                        JsonData obj = JsonMapper.ToObject(content);
                                        if(obj["code"].ToString() == "0")
                                        {
                                            pos.SeoDescription = "设置成功";
                                            SetRecordResult(db, RecordId, 1, "设置成功");
                                            db.SaveChanges();
                                        }
                                        else
                                        {
                                            string msg = obj["msg"].ToString();
                                            pos.SeoDescription = msg;
                                            SetRecordResult(db, RecordId, -1, msg);
                                            db.SaveChanges();
                                        }
                                    }
                                    else if(pos.BrandId == 10 || pos.BrandId == 11) //联动
                                    {
                                        decimal LastFee = Fee / 100;
                                        string content = LDFeeRate(merchant.KqMerNo, LastFee.ToString("f4"), pos.BrandId, addRate);
                                        JsonData obj = JsonMapper.ToObject(content);
                                        if(obj["code"].ToString() == "000000")
                                        {
                                            pos.SeoDescription = "设置成功";
                                            SetRecordResult(db, RecordId, 1, "设置成功");
                                            db.SaveChanges();
                                        }
                                        else
                                        {
                                            string msg = obj["msg"].ToString();
                                            pos.SeoDescription = msg;
                                            SetRecordResult(db, RecordId, -1, msg);
                                            db.SaveChanges();
                                        }
                                    }
                                    else if(pos.BrandId == 12 || pos.BrandId == 13) //盒易付
                                    {
                                        string content = BoxFee(merchant.KqMerNo, Fee.ToString("f2"));
                                        JsonData obj = JsonMapper.ToObject(content);
                                        if(obj["resultCode"].ToString() == "1")
                                        {
                                            pos.SeoDescription = "设置成功";
                                            SetRecordResult(db, RecordId, 1, "设置成功");
                                            db.SaveChanges();
                                        }
                                        else
                                        {
                                            string msg = obj["errorDesc"].ToString();
                                            pos.SeoDescription = msg;
                                            SetRecordResult(db, RecordId, -1, msg);
                                            db.SaveChanges();
                                        }
                                    }
                                    else if(pos.BrandId == 15 || pos.BrandId == 16) //联客宝
                                    {
                                        List<string> merno = new List<string>();
                                        merno.Add(merchant.KqMerNo);
                                        string plan_id = "";
                                        string plan_name = "";
                                        string content = PublicImportDataService.Instance.PospFee(merno, plan_id, plan_name);
                                        JsonData obj = JsonMapper.ToObject(content);
                                        if(obj["code"].ToString() == "200")
                                        {
                                            pos.SeoDescription = "设置成功";
                                            SetRecordResult(db, RecordId, 1, "设置成功");
                                            db.SaveChanges();
                                        }
                                        else
                                        {
                                            string msg = obj["msg"].ToString();
                                            pos.SeoDescription = msg;
                                            SetRecordResult(db, RecordId, -1, msg);
                                            db.SaveChanges();
                                        }
                                    }
                                }
                            }
                        }
                        db.Dispose();
                        Thread.Sleep(500);
                    }
                    catch (Exception ex)
                    {
                        function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "设置费率到支付平台异常");
                    }
                }
                else
                {
                    Thread.Sleep(500);
                }
            }
        }

        private void SetRecordResult(WebCMSEntities db, int RecordId, int Status, string Note = "")
        {
            if(RecordId > 0)
            {
                PosMachinesFeeChangeRecord record = db.PosMachinesFeeChangeRecord.FirstOrDefault(m => m.Id == RecordId);
                if(record != null)
                {
                    record.Status = Status;
                    record.SeoDescription = Note;
                }
            }
        }


        public void StartKdb()
        {
            Thread th = new Thread(StartKdbDo);
            th.IsBackground = true;
            th.Start();
        }

        private void StartKdbDo()
        {
            while (true)
            {
                try
                {
                    WebCMSEntities db = new WebCMSEntities();
                    var poslist = db.PosMachinesTwo.Select(m => new { m.Id, m.BrandId, m.SeoDescription }).Where(m => m.BrandId == 2 && m.SeoDescription.StartsWith("提交成功|")).ToList();
                    foreach (var pos in poslist)
                    {
                        string[] datalist = pos.SeoDescription.Split('|');
                        string orderNo = datalist[1];
                        int RecordId = int.Parse(datalist[2]);
                        string content = QueryFee(orderNo);
                        JsonData obj = JsonMapper.ToObject(content);
                        PosMachinesTwo edit = db.PosMachinesTwo.FirstOrDefault(m => m.Id == pos.Id);
                        if(edit != null)
                        {
                            if(obj["status"].ToString() == "HANDLE_STATUS_COMPLETE")
                            {
                                edit.SeoDescription = "设置成功";
                                SetRecordResult(db, RecordId, 1, "设置成功");
                                db.SaveChanges();
                            }
                            else if(obj["status"].ToString() == "HANDLE_STATUS_FAIL")
                            {
                                edit.SeoDescription = "设置失败";
                                SetRecordResult(db, RecordId, -1, "设置失败");
                                db.SaveChanges();
                            }
                        }
                    }
                    db.Dispose();
                }
                catch(Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "开店宝费率异步获取结果异常");
                }
                Thread.Sleep(5000);
            }
        }






        #region 金控
        // 开发环境
        // string mfe88PublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCy8cg6/tXbSj2i1tyi7VztwJw7uNmqc3bS6sVIZkDYhTmcXhpV17jq4j2zz/tURwX8b3MdK1A1HTR1XRd7hl0w2UF9iFk6UezByJ5tdNDoffMCGJtVSThq+MCV+WQI26tJ/ub6bm7GPrzTR79fntN+nTniRM4trjONN2WzEhHEcwIDAQAB";
        // string mfe88PrivateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALLxyDr+1dtKPaLW3KLtXO3AnDu42apzdtLqxUhmQNiFOZxeGlXXuOriPbPP+1RHBfxvcx0rUDUdNHVdF3uGXTDZQX2IWTpR7MHInm100Oh98wIYm1VJOGr4wJX5ZAjbq0n+5vpubsY+vNNHv1+e036dOeJEzi2uM403ZbMSEcRzAgMBAAECgYAeRbb4/AmTypB4zt6OlZdGBXKoy9HO+y+b6OmtINdRieBAKs9LvG3lFpcXp1S+YjGKDhSsV5p/EczBGhmR5R44j52886h6OoU0HskifeEJs152gMXLEFya/1QWnf1Ev+ugzuto+CxuHlGHE0T43uFkuATZp4sfXX/03um99FIKmQJBAOrYJX+VmKdNbmwNKMXkFBAw6FM4wrtr6vT3ne0pBWgbUDIH8cs83wq/SQHuvy/Cafqr8qWC9fFX2m+hllzxzA0CQQDDEIDNXdRxEmRVQ90lnn6ppnERvLhTY3RyuyOj3aqM1lxWEU2vvylimCpccTEqgY/PqMwfqChSf2v3S2CFjzJ/AkAPw2ho8vKnMDRcPlnhRpjuKUo+4812ZR0FSmWoWJuLTGIKqavaN4DFKOfOoGbm3sbcU5Ra9bpqc7ouygrcvEI1AkB8uqbBqsfW7X2+j8Bu96Picw1F3Di5CZVCb6tgcrNFjyRH3JSiVkfuRYKAzdg0Z9g/Xp33eB0gc13kKQy1GlWdAkB6Emn94YesoHda26HWbrgBy18KSfcLH57EuXquX/pOma1TXjaXw1E7kkFz1EPde9WzuSWUmGN2AdJT0ruTOb4C";
        // string clientPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCb861uuey1252WdS8KPeBB+vm5AIBEKclsfBzVLY1cZXiiEbInCmsqT6fSO+A6wjWyJixGCzZICmUxhdBzuo3Du2YTbuo+fRlV6DW1mbguBV8/l2+LJvht0jl87J8N4skFUzvAeYKpWDX6dC6cLzjm5nyI1OrCQq0lsWPEMDCNAwIDAQAB";
        // string clientPrivateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJvzrW657LXbnZZ1Lwo94EH6+bkAgEQpyWx8HNUtjVxleKIRsicKaypPp9I74DrCNbImLEYLNkgKZTGF0HO6jcO7ZhNu6j59GVXoNbWZuC4FXz+Xb4sm+G3SOXzsnw3iyQVTO8B5gqlYNfp0LpwvOObmfIjU6sJCrSWxY8QwMI0DAgMBAAECgYAjE0dqo/6NWHu1H14ZG5mYvW31Ihu3OP7Im5GQkNI+ecQMD5bWGQ3JUmkYa8ce8BdLnjJO/q6SvWPNI5+ip87CYPH1SMXKUiSLzaCrw4xMySW9PSnudTzJwhrmlmyjYTAg70tHf2YQC4YkNvtkR+PJ2yf6JEKGFVgP5p2KyeKXgQJBANjGryxyu95QC3jIaggcYmGD36sVO/ns8Uyu8PkAHYOscuXRcV0L8LghIzPolcehj9bTbDLjiuNgeuyjNs2YBvMCQQC4K4uIXt0kVDLYzlJfhN1CsV90vQitcKdD8wTO0JRKfMCQ6UDSumU7lq+z4TxTlRYxmZjpgIqH+N0WohmEiwWxAkBEfuMzBD3gjSJS0+DNF0ruzSCLinYdDoVgWZbC1wp8ZK0ZeQh9AhzZ0X6yFDffkGlG1B9IJSXpmr68rwXOCM+JAkBkrKEUxc6bGk/FRluvDWEqIO2uUdtZfBhjQ4ggSdKWOUXGsUsXJn9KKKAZc4lXo0rDiFQXaIXRuE+bHLdYReqxAkAj0Kol0LkJgdl2PoBAeyQHTpt9nxaeNX56W7CN/srBA1O2wr+aoQiJaKsu9I0EeW3zaMJlLi3VyjU4wnF+yAsB";
        // string reqUrl = "https://test-push.mfe88.com/push-service/api/MODIFYPERPOSFEE";

        // 生产环境
        string merchantNo = "4487378308096";
        string clientId = "1243966544896";
        string mfe88PublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC2HxPVZ5ZIxIWfr24qB45PAz9WfjN9CiF1x9Lz3P/tVvIXFdBaUw+9zxCAPRDGQxJId7anjEjCOuAIKpFOiTPhVqHTHd3075FFsW5fL7lFCOFJELTj+mVamAIbKalAuRzIX0m0VQUXd+madB+yRQSBjkOIboAMYQ9amf99SqI9KwIDAQAB";
        string clientPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrSrNKkBt/X8Fkd7viGpTMk+GdJgE+SvoA4PSjccpZoLWnwxXsC8K/7pfm9uGxPjte9e4RznXE5nuhSrcfls4lDWhTrGd/lj3Id8OCM+yEG+xilJs1lvXJjHDhL6/wa+TE5NSzWoKgXnyeHF3TSHMbUefLLtoKqL3j4h4lPqrjiQIDAQAB";
        string clientPrivateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKtKs0qQG39fwWR3u+IalMyT4Z0mAT5K+gDg9KNxylmgtafDFewLwr/ul+b24bE+O1717hHOdcTme6FKtx+WziUNaFOsZ3+WPch3w4Iz7IQb7GKUmzWW9cmMcOEvr/Br5MTk1LNagqBefJ4cXdNIcxtR58su2gqovePiHiU+quOJAgMBAAECgYBQIIyIR6slRWTRG5V/KlIK9O5oNbwFKMuUF6c4weUXUi9Hv+GEXugGIpVaTIi9AdCCFmb8W2kJ54tTowDQvRnGxVpr7repYwJv2jHh5ug3oreBghfbfbaOaRMXisp2x1CLi+8Q5BNjpe9KdurRtg7jt8bqgWels5aV2PbjPHHwBQJBANjqYXbapz6xUPdI0kyEQhdxHt7jOmysTY3vT+/UcgU2sf37hWh8JlTtVlFZns3JBocc9rMtBEAh0Cy5faMQXKMCQQDKJ9eYWQvb1GyB5IdDlkOuByyuwFfosZ0Qp+QNtnz1VAHHgQRM7RGNv3nYDJNEJ+qIhIzZppG5yDbAN7PYyTXjAkEAq8a4VkIDbZ9HyfxOJbAbEqtPUhzJ+KNea0cXm4o2nTBaNhLH7B1c0aZ908BQBRDr7XWfW/cLRapBTBm8h7R+VwJBAJAKrZMPN+TuSlaPaFYfNqBE2nC1+q2CCQE6L8QZmJYRwqbN5iuN7CkNGxt3cmNo8bNOhzH6fvFamLCDwDEixbMCQEgaxfAxpJdMoR6LrklSkigHiKfA6SaRWxxShFtBfjk5XcakmLkU/U5lgD/Blu7h4x6bRf4VPTYWdbxtiOK11rY=";
        string reqUrl = "https://push.mfe88.com/push-service/api/MODIFYPERPOSFEE";




        public string SetFee(string merNo, string sn, decimal addRate, int fee)
        {
            // 2021092711IpAreT 降费特惠…刷卡交易手续费
            // 2020032508Nu0QCG 刷卡交易手续费
            // 2020032508Nx8oyW 借记卡封顶手续费
            // 2020032508O4EWB6 刷卡结算手续费
            List<SetDepositList> rateDOs = new List<SetDepositList>();
            rateDOs.Add(new SetDepositList()
            {
                productSubType = "2020032508Nu0QCG",
                updateValue = addRate,
                updateType = 0
            });
            // rateDOs.Add(new SetDepositList()
            // {
            //     productSubType = "2020032508Nx8oyW",
            //     updateValue = fee,
            //     updateType = 0
            // });
            rateDOs.Add(new SetDepositList()
            {
                productSubType = "2020032508O4EWB6",
                updateValue = fee,
                updateType = 0
            });
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("X-Client-ID", "4487378308096");
            headers.Add("X-Security", "RSA");
            function.WriteLog(DateTime.Now.ToString(), "设置金控机具费率");
            Dictionary<string, object> obj = new Dictionary<string, object>();
            obj.Add("merNo", merNo);
            obj.Add("sn", sn);
            obj.Add("batchUpdateType", 2);
            obj.Add("rateDOs", rateDOs);
            string content = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
            function.WriteLog(DateTime.Now.ToString(), "设置金控机具费率");
            function.WriteLog(content, "设置金控机具费率");
            content = Encrypt(content);
            string signstr = Sign(content);
            headers.Add("X-Sign", signstr);
            string headerString = Newtonsoft.Json.JsonConvert.SerializeObject(headers);
            function.WriteLog(headerString, "设置金控机具费率");
            string req = "{\"param\":\"" + content + "\"}";
            function.WriteLog(req, "设置金控机具费率");
            string result = function.PostWebRequest(reqUrl, req, headers, "application/json");
            function.WriteLog(result, "设置金控机具费率");
            return result;
        }

        public string SetJkFee(string merNo, string sn, decimal fee = 0.6M)
        {
            List<SetDepositList> rateDOs = new List<SetDepositList>();
            rateDOs.Add(new SetDepositList()
            {
                productSubType = "2020032007vz7Ux6",
                updateValue = fee,
                updateType = 0
            });
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("X-Client-ID", clientId);
            headers.Add("X-Security", "RSA");
            Dictionary<string, object> obj = new Dictionary<string, object>();
            obj.Add("merNo", merNo);
            obj.Add("sn", sn);
            obj.Add("batchUpdateType", 2);
            obj.Add("rateDOs", rateDOs);
            string content = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
            function.WriteLog(DateTime.Now.ToString(), "设置金控机具费率");
            function.WriteLog(content, "设置金控机具费率");
            content = Encrypt(content);
            string signstr = Sign(content);
            headers.Add("X-Sign", signstr);
            string req = "{\"param\":\"" + content + "\"}";
            string result = function.PostWebRequest(reqUrl, req, headers, "application/json");
            function.WriteLog(result, "设置金控机具费率");
            return result;
        }

        public string Decrypt(string data)
        {
            var toDecryptArray = Convert.FromBase64String(data);
            var rsa = RSA.Create();
            rsa.ImportPkcs8PrivateKey(Convert.FromBase64String(clientPrivateKey), out _);
            string result = "";
            List<byte> cache = new List<byte>();
            for (int i = 0; i < toDecryptArray.Length; i++)
            {
                cache.Add(toDecryptArray[i]);
                if ((i + 1) % 128 == 0 || i + 1 == toDecryptArray.Length)
                {
                    var ContentArray = rsa.Decrypt(cache.ToArray(), RSAEncryptionPadding.Pkcs1);
                    result += System.Text.Encoding.UTF8.GetString(ContentArray);
                    cache.Clear();
                }
            }
            return result;
        }
        public string Encrypt(string data)
        {
            return new RSAHelper(RSAType.RSA, System.Text.Encoding.UTF8, "", mfe88PublicKey).Encrypt(data);
        }
        public string Sign(string data)
        {
            var toEncryptArray = System.Text.Encoding.UTF8.GetBytes(data);
            var rsa = RSA.Create();
            rsa.ImportPkcs8PrivateKey(Convert.FromBase64String(clientPrivateKey), out _);
            string result = "";
            var buffer = rsa.SignData(toEncryptArray, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
            result = Convert.ToBase64String(buffer);
            return result;
        }
        #endregion

        #region 开店宝

        //生产环境
        string KdbApiUrl = "https://kzy.kdb-tj.com:5055/api";
        string KDBAESKEY = "F@xh#sga41c08@pe";
        string Kdb_Rsa_PrivateKey = "MIIBUwIBADANBgkqhkiG9w0BAQEFAASCAT0wggE5AgEAAkEAl2x9dSSCfNDik6VM2dn/SK1ONSbb7AKyXM1gHw8PMbzWN1pK7YGaPqHlIRbAeFeIvLKVeMxrji+63W6LpB0yDQIDAQABAkAfpHUnCIUYDhJ65f0EPTDCgCyqoL8uN3YMPIKMmvoC22/i7AC6zf/bWk4JdratN+gvvnjGgHQff6HH5dOQ6sbFAiEAxPYSLADzIv374J8O+LluXIcgI5zXm4r4dMtKbCmmWSsCIQDE0BRKsBcBZ9NvJ9Km+m/d1hN9v5hFT842zrkUFJmVpwIgBdYc17z3d3P7QL613NzxzkAazbNaGDvX/O4BOI9LZJ0CICrZElHgXGHV9NYyWU45H7mwLbYmzEPqx/5uqySQB4/pAiBgKYv3RGnsZ8Zm1EKAJjUX7ehdteBgPSA/UgIDZQ4oyw==";
        string AgencyId = "3013890129";

        //开发环境
        // string KdbApiUrl = "https://kzy-test.kdb-tj.com:5056/api";
        // string KDBAESKEY = "Ebn4N28MvEXEvPTA";
        // string Kdb_Rsa_PrivateKey = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAsPyH5Y5NySHHKWIgPwxbZFkd33vzuWKv+Kdpug5/qYAnpTShDSMXQ2Ib7gc+B/yvj4uZ/k1A/xHpzHTPl6MzQQIDAQABAkA2sGHhyj45B2n+XKbwNIZNFMiJVUjzoQ4VPM4Lww0pt781GeqBCGgEIgTjmmg/FTGjgwTb7ta1A5G9Qn2nPG0RAiEA4x7W6XKdSL/FyVdlt4jijNQNZfLEqEPy1NnchRWUf40CIQDHfb49KP3pW4ZDX3xS42fYd9p7AGZ+qpVBnJfGGyFrhQIhALk3HCHyowuBwMUKLdw3mDEqeOarzO4/w1cLd8dcKua9AiEAtdPAj9JLDGWljMb9dDddsYockzwcL5ufizwFgkW8QlkCIADYU4+fFKqySLGX3MmEIJ/mU632PRtJAh4LSL8/Ij1H";
        // string AgencyId = "3013890202";

        // 修改费率接口
        public string ModifyFee(string PosSn, decimal Rate, string Fee = "0")
        {
            string url = KdbApiUrl + "/pos/rate/modify/single/remote";
            string content = "{\"posSn\":\"" + PosSn + "\",\"type\":\"贷记卡刷卡\",\"rate\":\"" + Rate + "\",\"d0Fee\":\"0\"}";
            return PostKDB(url, content);
        }

        // 查询费率接口
        public string QueryFee(string orderNo)
        {
            string url = KdbApiUrl + "/pos/rate/change/query/orderno";
            string content = "{\"orderNo\":\"" + orderNo + "\"}";
            return PostKDB(url, content);
        }

        public string KDBDecrypt(string data)
        {
            string result = AesDecrypt(data, KDBAESKEY);
            return result;
        }

        public string AesDecrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) return null;
            byte[] toEncryptArray = Convert.FromBase64String(str);

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7,
            };

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Encoding.UTF8.GetString(resultArray);
        }

        public string AesEncrypt(string str)
        {
            // if (string.IsNullOrEmpty(str)) return null;
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(KDBAESKEY),
                Mode = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };
            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray);
        }

        public string PostKDB(string url, string content)
        {
            content = AesEncrypt(content);
            string timestamp = function.GetCurTimestamp().ToString();
            string sign = KDBSign(content + timestamp);
            string req = "{\"agencyId\":\"" + AgencyId + "\",\"content\":\"" + content + "\",\"timestamp\":\"" + timestamp + "\",\"sign\":\"" + sign + "\"}";
            string result = PostWebRequestKdb(url, req, new Dictionary<string, string>());
            return result;
        }

        private string PostWebRequestKdb(string postUrl, string paramData, Dictionary<string, string> headers)
        {
            string ret = string.Empty;
            try
            {
                function.WriteLog(DateTime.Now.ToString(), "请求开店宝API日志");
                function.WriteLog(postUrl, "请求开店宝API日志");
                function.WriteLog(paramData, "请求开店宝API日志");
                byte[] postData = System.Text.Encoding.UTF8.GetBytes(paramData);
                // 设置提交的相关参数 
                System.Net.HttpWebRequest request = System.Net.WebRequest.Create(postUrl) as System.Net.HttpWebRequest;
                System.Text.Encoding myEncoding = System.Text.Encoding.UTF8;
                request.Method = "POST";
                request.KeepAlive = false;
                request.AllowAutoRedirect = true;
                request.ContentType = "application/json";
                foreach (string key in headers.Keys)
                {
                    request.Headers.Add(key, headers[key]);
                }
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR  3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";

                request.ContentLength = postData.Length;

                // 提交请求数据 
                System.IO.Stream outputStream = request.GetRequestStream();
                outputStream.Write(postData, 0, postData.Length);
                outputStream.Close();
                System.Net.HttpWebResponse response;
                System.IO.Stream responseStream;
                System.IO.StreamReader reader;
                string srcString;
                response = request.GetResponse() as System.Net.HttpWebResponse;
                responseStream = response.GetResponseStream();
                reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);
                srcString = reader.ReadToEnd();
                ret = srcString;   //返回值赋值
                reader.Close();
                function.WriteLog(srcString, "请求开店宝API日志");
            }
            catch (System.Net.WebException ex)
            {
                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)ex.Response;
                if(response != null)
                {
                    System.IO.Stream myResponseStream = response.GetResponseStream();
                    //获取响应内容
                    System.IO.StreamReader myStreamReader = new System.IO.StreamReader(myResponseStream);
                    ret = myStreamReader.ReadToEnd();
                    myResponseStream.Close();
                }
            }
            catch (Exception ex)
            {
                ret = "fail";
                function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "请求开店宝API异常");
            }
            return ret;
        }

        public string KDBSign(string data)
        {
            var rsa = RSA.Create();
            var key = Convert.FromBase64String(Kdb_Rsa_PrivateKey);
            var content = Encoding.UTF8.GetBytes(data);
            rsa.ImportPkcs8PrivateKey(key, out _);
            var result = rsa.SignData(content, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
            return Convert.ToBase64String(result);
        }

        #endregion
        
        #region 乐刷

        string LSPrivateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMjld3flY+R+9WTR2MvcR9qWISdmpayL3GNGg9gvzwkXkhDI/E7rX6ndLvVuaBbLWXB+UOh+8Pfw3Gvfv3D2GHZCTzPHOKrs2tyzqC8EmMUDQaoVOI2BY4vtB7IjNe9FlLGZx62JEJrMkHKnOSQxsi+flCoexKc2t1q7kQsO2F+3AgMBAAECgYBmQ7EB/mpQOXSPYucaN0L4eW3dEbqKUBPbEV0yInwgo7f+BWGyhsyGuooZ857W46Leyd5Dy8K8ZAbAfwCD7zJZsSzWsuvWQE991f+n0V7AAnKc3h4OsHa4oITUNo2nD3PvOpWfQx8vSuQuSFQgx0ExdnywS3So16mG2X6J2k87wQJBAPTfV10MNpA1e5oRdX4D4lQ2tVyg5GW72NMhUGWct/FvgcEW3V7xZ0z/gSLfFcGI8c4LGYWRVPIsBnWFx0LSZ6ECQQDSBoqXuF/LobfFFT3D47ixL8d+qDbOJ+ro3p4+iCkdxxJ/ncaqouxsr3fBbkSWh4t+UkbbihO/isPdBwLPZihXAkAc2jwHAKtlLogTzT7UzExcs92GvoZq3klcBy7b6i1aS1M0lycaSsNrNSfYHgUIOsSTDIfDTy59ImbYbhzeaMBBAkEAyfz6i4IJt3jXmZadKWk4NkhiT6CN3OUtGjsH69Hd4UKUuuFNsMwyHzD+NqzLEA5aDOoqNXftGDjnuAnHHRn9zwJAHqPHR5ZOKDN/ujeAIUTwmFFJh8vx6ujv7UTesBbtTsFYW6bZln+X6aS2G3Kdvz3e2cxQyH8ncc0yIh64a1fqyg==";
        string LSPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI5Xd35WPkfvVk0djL3EfaliEnZqWsi9xjRoPYL88JF5IQyPxO61+p3S71bmgWy1lwflDofvD38Nxr379w9hh2Qk8zxziq7Nrcs6gvBJjFA0GqFTiNgWOL7QeyIzXvRZSxmcetiRCazJBypzkkMbIvn5QqHsSnNrdau5ELDthftwIDAQAB";
        string OrgNo1 = "704067708098457600"; //快联盟电签pos
        string OrgNo2 = "704058964878831616"; //快联盟大pos
        string LSReqUrl = "https://lfs-org-push.ileshua.com"; //请求url

        public string LSDecrypt(string data, string sign)
        {
            var toDecryptArray = Convert.FromBase64String(sign);
            var rsa2 = RSA.Create();
            rsa2.ImportPkcs8PrivateKey(Convert.FromBase64String(LSPrivateKey), out _);
            var ContentArray = rsa2.Decrypt(toDecryptArray, RSAEncryptionPadding.Pkcs1);
            string aeskey = System.Text.Encoding.UTF8.GetString(ContentArray);
            return AesDecrypt(data, aeskey);
        }

        public string LSEncrypt(string sign)
        {
            return new RSAHelper(RSAType.RSA, System.Text.Encoding.UTF8, "", LSPublicKey).Encrypt(sign);
        }

        public string LSAesEncrypt(string str, string aeskey)
        {
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(aeskey),
                Mode = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };
            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray);
        }

        //设置机具押金
        public string SetDepositForLS(string snNo, string oldMarketId, string newMarketId, int BrandId)
        {
            string data = "{\"snNo\":\"" + snNo + "\",\"marketType\":\"400\",\"oldMarketId\":\"" + oldMarketId + "\",\"newMarketId\":\"" + newMarketId + "\"}";
            return LSReqFunc("/org/pos/updatePosMarket", data, BrandId);
        }
        //查询配置活动信息
        public string QueryActiveForConfig(string snNo, int BrandId)
        {
            string data = "{\"snNo\":\"" + snNo + "\"}";
            return LSReqFunc("/org/pos/getMarketConfig", data, BrandId);
        }
        //查询营销活动信息
        public string QueryActiveForBrand(int marketType, int BrandId)
        {
            string data = "{\"marketType\":\"" + marketType + "\"}";
            return LSReqFunc("/org/pos/marketList", data, BrandId);
        }
        //终端费率模板查询
        public string QueryFeeTmpForBrand(string rateType, string deviceType, int BrandId)
        {
            string data = "{\"rateType\":\"" + rateType + "\",\"deviceType\":\"" + deviceType + "\"}";
            return LSReqFunc("/org/pos/rateConfigList", data, BrandId);
        }
        //终端费率查询
        public string QueryFeeForBrand(string snNo, int BrandId)
        {
            string data = "{\"snNo\":\"" + snNo + "\"}";
            return LSReqFunc("/org/pos/getRateConfig", data, BrandId);
        }
        //终端费率模板修改
        public string SetFeeForBrand(string snNo, string bzConfigId, string yhConfigId, string surfeeConfigId, int BrandId)
        {
            string data = "{\"snNo\":\"" + snNo + "\",\"bzConfigId\":\"" + bzConfigId + "\",\"yhConfigId\":\"" + yhConfigId + "\",\"surfeeConfigId\":\"" + surfeeConfigId + "\"}";
            return LSReqFunc("/org/pos/updatePosRate", data, BrandId);
        }

        public string LSReqFunc(string apiPath, string data, int BrandId)
        {
            function.WriteLog(DateTime.Now.ToString(), "设置乐刷机具费率");
            function.WriteLog(data, "设置乐刷机具费率");
            string aeskey = function.MD5_16(Guid.NewGuid().ToString());
            string req = "{";
            if (BrandId == 4)
            {
                req += "\"orgId\":\"" + OrgNo1 + "\",";
            }
            else
            {
                req += "\"orgId\":\"" + OrgNo2 + "\",";
            }
            req += "\"requestId\":\"" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8) + "\",";
            req += "\"timeStamp\":\"" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\",";
            req += "\"version\":\"1.0\",";
            req += "\"data\":\"" + LSAesEncrypt(data, aeskey) + "\",";
            req += "\"sign\":\"" + LSEncrypt(aeskey) + "\"";
            req += "}";
            function.WriteLog(req, "设置乐刷机具费率");
            string result = function.PostWebRequest(LSReqUrl + apiPath, req, "application/json");
            function.WriteLog(result + "\n\n", "设置乐刷机具费率");
            return result;
        }

        #endregion

        #region 立刷

        string LiSAgentId = "50814834";
        string LiSPrivateKey = "MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDTdeLXqQmfVJM/ATVnq+TdhgpKKPp3hXcuY2s9qrN1Uws7I7jqnq/gfoBHBWBu/PnQp/z65okBoz4PEpWzJYZDF4csgh3E45He46ialNzUlOPWv6yLzgQPHuneq2pXOb7dbN4kZx+g3nEbBjH+/P9xp+lU3HCwjNxIFSr3EyBAQf2HgvNqh70u9T13fGVx3Jtd2xbIKYhvGNPH9ZCGiZNiCy+m+F+TKywgKK/xify1KQgR6otVUOVIGYvPYlXAgLJM2/V54166KX1UUFMsKRj4Kt2j4GqoHzDfRk9ibYJ/8iSDGX4+WH5+8mq/raqA77VcAD+bMrt3Bm59XmaWtjZwDY1zh5sP5jEaxu4lde2xZD80kQ6p1ZydpqnjmWm6NKXSz8j85gRkTQqNALKNANnJb6f1Yy30WirnrhMkqU2dqBzzXxtk3k/2zv9BENjYs1igrRYpwX3QRx87aTOrIk/PO6cxMaWl249LPigah0OqVyIg5yOvtnUCdU12OqaVELIw5GnZ7rTRn3tAsJ+u1om+3XktbN3GUEpw5RWAT3UAsAU7Vxt9xPCss+JXF+ogXYgo9QpEjanXOfLo5KPv2CkBuzy87d85OId71gXpYcbp0zbKz5eXKZanVP9pwn43jqiPkqtam8N1TLCCmZ4t2cd+gpW2CX/+W7bmc25HJtRPuwIDAQABAoICAE7B9GfwTGYsYN8xewuOySH8n255jrffXMFJRBLmtgo3kNJI/sFbsxPA6dQJ253a2MxvFNj57gNPInkIqfrcOgJZC/52w9GmFJlY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NYmcuuXkyWM83s11YSC9ZgeilbJuvdajePHrtIAxy8cny+yTBcbnJnWw1yHtzWCA5FAw5OWSaeotbWaFEAHaOW1VG9e1I54pgmVTc5n+WixsgH1fpiz04ojlWRWRyP7hqS+GbAyGgg00KyErRrPcwc=";

        string LiSReqUrl = "https://openapi.jlpay.com/access/charge/"; //请求url

        public string LiSSign(string data)
        {
            var rsa = RSA.Create();
            var key = Convert.FromBase64String(LiSPrivateKey);
            var content = Encoding.UTF8.GetBytes(data);
            rsa.ImportPkcs8PrivateKey(key, out _);
            var result = rsa.SignData(content, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
            return Convert.ToBase64String(result);
        }

        // 设置费率
        public string SetLiSFee(string sn, decimal serviceFee = 0.6M)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("agentId", LiSAgentId);
            dic.Add("deviceSn", sn);
            List<Dictionary<string, object>> feeList = new List<Dictionary<string, object>>();
            Dictionary<string, object> item = new Dictionary<string, object>();
            item.Add("feeCalcType", "M5");
            item.Add("fixed", "0");
            item.Add("rate", serviceFee);
            feeList.Add(item);
            dic.Add("feeList", feeList);
            dic.Add("signMethod", "02");
            string content = LiSAgentId + sn + "M50" + serviceFee + "02";
            string signstr = LiSSign(content);
            dic.Add("signData", signstr);
            string req = Newtonsoft.Json.JsonConvert.SerializeObject(dic);
            function.WriteLog(DateTime.Now.ToString(), "设置立刷费率");
            function.WriteLog(req, "设置立刷费率");
            string result = PostWebRequest(LiSReqUrl + "FEE003", req, new Dictionary<string, string>());
            function.WriteLog(result, "设置立刷费率");
            function.WriteLog("\n\n", "设置立刷费率");
            return result;
        }

        public string QueryLiSDeposit(string merchNo, string sn)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("agentId", LiSAgentId);
            dic.Add("deviceSn", sn);
            dic.Add("merchNo", merchNo);
            dic.Add("signMethod", "02");
            string content = LiSAgentId + sn + merchNo + "02";
            string signstr = LiSSign(content);
            dic.Add("signData", signstr);
            string req = Newtonsoft.Json.JsonConvert.SerializeObject(dic);
            string result = PostWebRequest(LiSReqUrl + "FEE001", req, new Dictionary<string, string>());
            return result;
        }

        private string PostWebRequest(string postUrl, string paramData, Dictionary<string, string> headers)
        {
            string ret = string.Empty;
            try
            {
                function.WriteLog(DateTime.Now.ToString(), "请求立刷API日志");
                function.WriteLog(postUrl, "请求立刷API日志");
                function.WriteLog(paramData, "请求立刷API日志");
                byte[] postData = System.Text.Encoding.UTF8.GetBytes(paramData);
                // 设置提交的相关参数 
                System.Net.HttpWebRequest request = System.Net.WebRequest.Create(postUrl) as System.Net.HttpWebRequest;
                System.Text.Encoding myEncoding = System.Text.Encoding.UTF8;
                request.Method = "POST";
                request.KeepAlive = false;
                request.AllowAutoRedirect = true;
                request.ContentType = "application/json";
                foreach (string key in headers.Keys)
                {
                    request.Headers.Add(key, headers[key]);
                }
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR  3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";

                request.ContentLength = postData.Length;

                // 提交请求数据 
                System.IO.Stream outputStream = request.GetRequestStream();
                outputStream.Write(postData, 0, postData.Length);
                outputStream.Close();
                System.Net.HttpWebResponse response;
                System.IO.Stream responseStream;
                System.IO.StreamReader reader;
                string srcString;
                response = request.GetResponse() as System.Net.HttpWebResponse;
                responseStream = response.GetResponseStream();
                reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);
                srcString = reader.ReadToEnd();
                ret = srcString;   //返回值赋值
                reader.Close();
                function.WriteLog(srcString, "请求立刷API日志");
            }
            catch (Exception ex)
            {
                ret = "fail";
                function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "请求立刷API异常");
            }
            return ret;
        }

        #endregion

        #region 盛付通
        string OrgId = "38844193";
        // 生产环境
        string SftPrivateKey = "MIIJQwIBADANBgkqhkiG9w0BAQEF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Z5hDc1p2oO7l1/DaAXEkwbm7eSaTB9FrZOf4mbAlj9chFzBA1ZnEkOdTIXzLaYZvDWF/Y30CkQhsn79srEcjeDtxRNF+JVaRzI3kuRdF1hDeB84CVIXUG5hxupEa9E0eQawLvT9PSqjiJLrIRhY72bpzBpLX61my9NuzOc4cMQLsxOjDTGpRuqJ+jlZvTbXNceLVNcIgW9OlxVlnU778IKCnp7khqatdkA4JmqF8gla86BNwRdxJoH/juFGtp6GJA6jsR0+0EjGA4I1AoIBAGl2ITNeGX2dXgvmPEcH8/CARFWMCozpjuWwm1acu1baQFRvoaSZmEXzF5SnySMIvf0sFBE0GgbqbnK/ePNE6/7XvSuMAR2Qi3CJhTe0jzrxd8tS9QBB12hlLmM6TlM08Z0mI7jSMcz/KJ/gJD9QG7enS6T+J0GhcT8NUaDDxhYcujram384CdToVXq9vd4n7L7PpaIvG0XY8ZsXiAqduzssZrZnmMuLtM+DQf+US8e3ymWTgveZJxA52GhFYy5RkWdMy28fUheb467GE3g3NgTHqwFAFXd/ENmgiKk1rxW7HVfGepLMczjy8ZvBbzDyGTjBEMyGc8DXmTauUfPUJX0CggEBAKEWyNHhEBcEfW6ppPYsaKTlIquA2Chr15KsZcSFOMIcsF/6D7TDZg2NPDYFmlALF/cdqDjRIAP/v5IMRiu3UtHyfDbRyEHx0prvucFMY0HyX9VOJnticwTb39awHi/uFJLs7txERw89eJFcLaxRRRRSpPq3PCalGFpC2i8HXsPnv3gyt+bfE92h6E2YTyP41NYmcuuXkyWM83s11YSC9ZgeilbJuvdajePHrtIAxy8cny+yTBcbnJnWw1yHtzWCA5FAw5OWSaeotbWaFEAHaOW1VG9e1I54pgmVTc5n+WixsgH1fpiz04ojlWRWRyP7hqS+GbAyGgg00KyErRrPcwc=";
        string SftReqUrl = "https://zqb.shengpay.com/cp-bff-thirdparty/v1/thirdparter/pos/"; //请求url
        string SftPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCEtC73mdnEQ5b0G93Dseg457m6Rc8lVU9K31SEc0YyK4anN3fgGDOl2CuQT2JIaxwwqCAHoUQp7jLUirc7XUQlh+y0WnYgPre6jmfI9upuJwTD7TmUr+Mqtg2RZTYX1r81OtRL/ELQW/lm4kBcuXeCWVlwhMyAQiJdb9+plkYXIwIDAQAB";
        // 测试环境
        // string SftPrivateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAILFLdmFwfNHCGk3vpwj/FR9XpE9jjVreLlOaIEkSAOWOfzxCF7pMeSy0UDroRLgfLD4nQbUcK5AT7gg8PEM6H99SEHcpBkTKhfK1iI5iU9sN/WGL2Ft5T/uwo+KD7X3CsqMD0HsMQtv/YHJeAz/SPf5zyD5KttwohXXzO8a3P1pAgMBAAECgYAchxl2f6iNAu0Bzyhk9bDBWcw8kRop6zUd7836hkizh51E4ew6kFLTGnNt3zl3XcO187aF2+htCxiZCY6md3NstJod1zshoXf2slxxPWRUK92sS0XzlVT6ahVTdq2tAS3hOY3ldtnfOXMmMQPNn9OqlALQGOH/hJatBV6ZQxpp0QJBAMGKsxJkg3M6sZEO4zUgWgnGN+uS6nwAWpCfBY7eDvYSN78BxGGLgn+t40c0R8M/n85IM8OUmfHxTGWN3hYyGuUCQQCs+Kg1ypul9XLTWrVApyvZxY4ZxjAWG4yW4xqbUtHWUkGyle7Dy8xiYezl0kWN81lJNTz3qrJ4ZvM825+7tPw1AkBDPNxZV3ITZiCqNHHa0xJ0sthajv/HdJgCBjz4FU09T7buNL705HLByLdc1VzZCBGMqKjTGZ0h4KKZ5V9ydpXBAkABpZx0Zql0uxGM0aBILU9Nk4P22tw6WajNBvyJ3hABamcVvDe5xYb8qNIInifrYhXHjKo38XghjVljivPKZb7BAkAt4pCUYLI7LzLeSh/lnVxA7jOaRI3UsngCXn9VA4f+dkNcKAftRQqe7ytudqG07GKoInnDiyjrYe4kTLym8zoc";
        // string OrgId = "88031499";
        // string SftReqUrl = "https://zqbtest.shengpay.com/cp-bff-thirdparty/v1/thirdparter/pos/"; //请求url

        public string SftEncrypt(string data)
        {
            var rsa = RSA.Create();
            var key = Convert.FromBase64String(SftPrivateKey);
            var content = Encoding.UTF8.GetBytes(data);
            rsa.ImportPkcs8PrivateKey(key, out _);
            var result = rsa.SignData(content, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
            return Convert.ToBase64String(result);
            // return new RSAHelper(RSAType.RSA, System.Text.Encoding.UTF8, SftPrivateKey).Encrypt(data);
        }

        //设置机具押金
        public string SetFeeForSft(string merchantId, string Rate, string fee = "0")
        {
            Dictionary<string, object> req = new Dictionary<string, object>();
            req.Add("orgPromoterId", OrgId);
            req.Add("promoterId", OrgId);
            List<Dictionary<string, object>> merchantFeeList = new List<Dictionary<string, object>>();
            Dictionary<string, object> item = new Dictionary<string, object>();
            item.Add("merchantId", merchantId);
            List<Dictionary<string, object>> feeList = new List<Dictionary<string, object>>();
            Dictionary<string, object> feeItem = new Dictionary<string, object>();
            feeItem.Add("feeType", "CC");
            feeItem.Add("feeRate", Rate);
            feeItem.Add("feeDisRate", Rate);
            feeList.Add(feeItem);
            
            feeItem = new Dictionary<string, object>();
            feeItem.Add("feeType", "T0_CC");
            feeItem.Add("feeRate", fee);
            feeItem.Add("feeDisRate", fee);
            feeList.Add(feeItem);
                
            item.Add("feeList", feeList);
            merchantFeeList.Add(item);
            req.Add("merchantFeeList", merchantFeeList);
            req.Add("signType", "RSA");
            req.Add("charType", "UTF-8");
            req.Add("requestId", DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8));
            req.Add("requestTime", function.GetCurTimestamp());
            req = req.OrderBy(m => m.Key).ToDictionary(m => m.Key, m => m.Value);
            string signString = "";
            foreach (string key in req.Keys)
            {
                if (key == "merchantFeeList")
                {
                    signString += key + "=" + Newtonsoft.Json.JsonConvert.SerializeObject(req[key]) + "&";
                }
                else
                {
                    signString += key + "=" + req[key].ToString() + "&";
                }
            }
            signString = signString.TrimEnd('&');
            req.Add("mac", SftEncrypt(signString));
            function.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(req), "设置盛付通机具费率");
            string result = function.PostWebRequest(SftReqUrl + "batchChangeMerchantFee", Newtonsoft.Json.JsonConvert.SerializeObject(req), "application/json");
            function.WriteLog(result + "\n\n", "设置盛付通机具费率");
            return result;
        }

        #endregion
        
        #region 海科

        string HKPrivateKey1 = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAK5iJ2q2nF+9jEnof9VYhMdbAgI0ZS4cYmgWTMW2JR61lJhR0GH+A/m6mjN9FsTS6Bq03u/+e6BKdE6VqMGk0q7asi2VZIgD59zj4HubS8EFrcb5ZprwmGLnG71cBga7V5EWnHxSB9BlbFt6rGeQiit8NSbv62NxGh1U+rAVE/a3AgMBAAECgYEApQGxpJNowls8bQ74LytUcMMX0ng7qXcoUq+PM6IX28gb9EmuMZtHrb05fjEGI3YiNGsjbNpTpqftCBMrHRjWVRgb0PDf/zD9YYrxmcP9DWKQjG5f1ygYtQBlnOPEX963Y2SXrsTKr4+szTpI8r6YqFfVbbooKVMesCBtshgg16kCQQDYHGDuCuOzULP84QvGi8z+wHNv0arFpYYxvwitntD7K3iolAh8gTDWeaC03MHruGM43ybCUi9EHhCrcVKjgpK1AkEAzpIUajdmAAwtwGg4G0v7tP/ulmpGhnALVN84gSMAc5f8D6aCnoUyle+GylwRBw9WblHBLxsOtARQIvvdphDrOwJBAIFvXc60zvQTHfoTf84G5VyfP4R1e2atYNZiqHv0Zw5IVxgAsaSAbBPI/SvWHH9mDGd/n+M6/fw6VZmZYfl0txECQQCQB3yifpPpDpTL5h7QsY8EKbqyN9GKpQ7Rk35zU/NZpawDQYcrfhXCQytJZx4cPQ53hxtae9QpoiQ58EEgLAXHAkABzJ/QDS1QfYrkP9t9X+Pny2iEuWGeIHyfsfSKQKr5pv16k1WqiIvlFRyDPl+aw5IOedkYb0vSkcU1KzjMW+Ra";
        string HKPublicKey1 = "MIGfMA0GCSqGSIb3DQEBAQU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BAQUAA4GNADCBiQKBgQCMgEb8k2LxpXnb/uBNw/BcbEtO6Zs2WCZCHVsaL/8QKQejG9gVT+gZIbEcqMklmxMomJWacdQN2+w+MnO7w91nwdItHBj8DHST/7xrs1nxdpi2NL+Jia8XV7hnlqX1p5eAz9GkEuqpFJXoun9L1ku+sHaR7ylBm9ezc/3/Xs6+bQIDAQAB";
        string HKOrgNo1 = "747187394495131648"; //电签pos
        string HKOrgNo2 = "747189644974104576"; //大pos
        string HKReqUrl = "https://org-push.juheposp.com"; //请求url

        public string HKDecrypt(string data, string sign, int Kind)
        {
            string HKPrivateKey = Kind == 8 ? HKPrivateKey1 : HKPrivateKey2; 
            var toDecryptArray = Convert.FromBase64String(sign);
            var rsa2 = RSA.Create();
            rsa2.ImportPkcs8PrivateKey(Convert.FromBase64String(HKPrivateKey), out _);
            var ContentArray = rsa2.Decrypt(toDecryptArray, RSAEncryptionPadding.Pkcs1);
            string aeskey = System.Text.Encoding.UTF8.GetString(ContentArray);
            return AesDecrypt(data, aeskey);
        }

        public string HKEncrypt(string sign, int Kind)
        {
            string HKPrivateKey = Kind == 8 ? HKPrivateKey1 : HKPrivateKey2;
            string HKPublicKey = Kind == 8 ? HKPublicKey1 : HKPublicKey2;
            return new RSAHelper(RSAType.RSA, System.Text.Encoding.UTF8, "", HKPublicKey).Encrypt(sign);
        }

        public string HKAesEncrypt(string str, string aeskey)
        {
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(aeskey),
                Mode = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };
            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray);
        }

        //设置机具押金
        public string SetDepositForHK(string snNo, string oldMarketId, string newMarketId, int BrandId)
        {
            string data = "{\"snNo\":\"" + snNo + "\",\"marketType\":\"400\",\"oldMarketId\":\"" + oldMarketId + "\",\"newMarketId\":\"" + newMarketId + "\"}";
            return HKReqFunc("/org/pos/updatePosMarket", data, BrandId);
        }
        //查询配置活动信息
        public string HKQueryActiveForConfig(string snNo, int BrandId)
        {
            string data = "{\"snNo\":\"" + snNo + "\"}";
            return HKReqFunc("/org/pos/getMarketConfig", data, BrandId);
        }
        //查询营销活动信息
        public string HKQueryActiveForBrand(int marketType, int BrandId)
        {
            string data = "{\"marketType\":\"" + marketType + "\"}";
            return HKReqFunc("/org/pos/marketList", data, BrandId);
        }
        //终端费率模板查询
        public string HKQueryFeeTmpForBrand(string rateType, string deviceType, int BrandId)
        {
            string data = "{\"rateType\":\"" + rateType + "\",\"deviceType\":\"" + deviceType + "\"}";
            return HKReqFunc("/org/pos/rateConfigList", data, BrandId);
        }
        //终端费率查询
        public string HKQueryFeeForBrand(string snNo, int BrandId)
        {
            string data = "{\"snNo\":\"" + snNo + "\"}";
            return HKReqFunc("/org/pos/getRateConfig", data, BrandId);
        }
        //终端费率模板修改
        public string HKSetFeeForBrand(string snNo, string bzConfigId, string yhConfigId, string surfeeConfigId, int BrandId)
        {
            string data = "{\"snNo\":\"" + snNo + "\",\"bzConfigId\":\"" + bzConfigId + "\",\"yhConfigId\":\"" + yhConfigId + "\",\"surfeeConfigId\":\"" + surfeeConfigId + "\"}";
            return HKReqFunc("/org/pos/updatePosRate", data, BrandId);
        }

        public string HKReqFunc(string apiPath, string data, int BrandId)
        {
            function.WriteLog(DateTime.Now.ToString(), "设置海科机具费率");
            function.WriteLog(data, "设置海科机具费率");
            string aeskey = function.MD5_16(Guid.NewGuid().ToString());
            string req = "{";
            if (BrandId == 8)
            {
                req += "\"orgId\":\"" + HKOrgNo1 + "\",";
            }
            else
            {
                req += "\"orgId\":\"" + HKOrgNo2 + "\",";
            }
            req += "\"requestId\":\"" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8) + "\",";
            req += "\"timeStamp\":\"" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\",";
            req += "\"version\":\"1.0\",";
            req += "\"data\":\"" + HKAesEncrypt(data, aeskey) + "\",";
            req += "\"sign\":\"" + HKEncrypt(aeskey, BrandId) + "\"";
            req += "}";
            function.WriteLog(req, "设置海科机具费率");
            string result = function.PostWebRequest(HKReqUrl + apiPath, req, "application/json");
            function.WriteLog(result + "\n\n", "设置海科机具费率");
            return result;
        }

        #endregion

        #region 联动

        //测试环境
        // string LDRequestUrl = "http://111.14.221.188:18066/CloudTerminalServiceAction/";
        // string AgentNo = "LD110014";
        // string LDPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3WG04QXTzWBg2rj4BbSmnXVTqQiCk2lZ7yi2vur2LxsSc+KN0o1W9y2AkCHcFIAk2aAfMEMQYTO3HQ+F/Vcb27BNBSjnaOLfGv0PXNHKyVzC4EQLe4M5Pqd1wMl6NaZK+HnyrPBTnfsGeywhGJc1Ke96ANrydhk7UbwezydC7nQIDAQAB";
        // string LDPrivateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJwUiLkXb6zTpvNmB+zTZtuJi97/XCdGBWgiMn/2ayVEtRuarPOvMUQo0aX4Pb/JrfdFyQccXiXFGtmh/m5Mhfuj03t0pOTC4bniQAy2veytDhnRImL1xY9YjSMX+YRXI44VRcNUSefyNmBjL7V1HgbJOfnq/PmVkcBClTf1gtefAgMBAAECgYBRbYkS/34crWNJUq7JyFS+LllRounh9270r/qmtdmaXOkbmKuoinrqc11E+GjGuSJQghDp68vWaqmiZxhFVRkEqPzaesYyMJr73GB/efXhIRWWGCqQvARs3QgOFmCL2YsC/Vq7niI72mmNLC9jOUFN30vCnJH7xI2PljfQKBLwkQJBAN1/JRJmt+2ms/eeGsI/tgClciCAfHzTtAhPHRs7XL98mzk8IDGFjysKsiSacAym5e0xV1uB6ijsuAm61go4b8cCQQC0ZLVyKdUPadhzXSjyOqtk4HVzorHW6OkDCnMazL0CYLxdJOQzrpicPhww0TB397rqLC+FuGEOEcjrDnYyGQlpAkEAq4OU9VbM/h2kJg4rslcbXAzA/yH/Q7m7IuQAKeIhw7V9jShd1XsSjcXOhEGCmolyaeVXO+ixpdcH+6DNtURWaQJACh5L/ydRiBfLyEzFazDXREVC0UWi7AcMats/MZWiVGvQpPjYw/1bGghx1FsneNMwbMolsD5zUzK0LlsVTiIRYQJAZT0p0Mg3kqSaYO2JlC6fTkI9aHMJ50iDr8qLJ2JnrNFylDxxoHwKfA7GxA2KGotguGTKhw7xCp+IyrXtXiuNrQ==";

        //生产环境
        string LDRequestUrl = "http://ldys.umpay.com/service_exter/CloudTerminalServiceAction/";
        string AgentNo = "LD112692";
        string LDPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCGtWShTeFEgSSFx3PJXcjCOmS+OgtcUvPOHhpALY3Orm6t7rl1E0n3j7XlM049YwwtGRJI4OWhgrtR4/AnOMBXdyMBoKxF23uay1WQiNekzfUrTwil7/CRrQ+VlGgPe6dr3WQT2/HLbzMnJHeoIZ4KSIj/7pgAwTF4ciL1UC3awwIDAQAB";
        string LDPrivateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJwUiLkXb6zTpvNmB+zTZtuJi97/XCdGBWgiMn/2ayVEtRuarPOvMUQo0aX4Pb/JrfdFyQccXiXFGtmh/m5Mhfuj03t0pOTC4bniQAy2veytDhnRImL1xY9YjSMX+YRXI44VRcNUSefyNmBjL7V1HgbJOfnq/PmVkcBClTf1gtefAgMBAAECgYBRbYkS/34crWNJUq7JyFS+LllRounh9270r/qmtdmaXOkbmKuoinrqc11E+GjGuSJQghDp68vWaqmiZxhFVRkEqPzaesYyMJr73GB/efXhIRWWGCqQvARs3QgOFmCL2YsC/Vq7niI72mmNLC9jOUFN30vCnJH7xI2PljfQKBLwkQJBAN1/JRJmt+2ms/eeGsI/tgClciCAfHzTtAhPHRs7XL98mzk8IDGFjysKsiSacAym5e0xV1uB6ijsuAm61go4b8cCQQC0ZLVyKdUPadhzXSjyOqtk4HVzorHW6OkDCnMazL0CYLxdJOQzrpicPhww0TB397rqLC+FuGEOEcjrDnYyGQlpAkEAq4OU9VbM/h2kJg4rslcbXAzA/yH/Q7m7IuQAKeIhw7V9jShd1XsSjcXOhEGCmolyaeVXO+ixpdcH+6DNtURWaQJACh5L/ydRiBfLyEzFazDXREVC0UWi7AcMats/MZWiVGvQpPjYw/1bGghx1FsneNMwbMolsD5zUzK0LlsVTiIRYQJAZT0p0Mg3kqSaYO2JlC6fTkI9aHMJ50iDr8qLJ2JnrNFylDxxoHwKfA7GxA2KGotguGTKhw7xCp+IyrXtXiuNrQ==";

        public string LDEncrypt(string data)
        {
            return new RSAHelper(RSAType.RSA, System.Text.Encoding.UTF8, "", LDPublicKey).Encrypt(data);
        }

        public string LDDecrypt(string data)
        {
            var toDecryptArray = Convert.FromBase64String(data);
            var toKey = Convert.FromBase64String(LDPrivateKey);
            var rsa = RSA.Create();
            rsa.ImportPkcs8PrivateKey(toKey, out _);
            string result = "";
            List<byte> cache = new List<byte>();
            for (int i = 0; i < toDecryptArray.Length; i++)
            {
                cache.Add(toDecryptArray[i]);
                if ((i + 1) % 128 == 0 || i + 1 == toDecryptArray.Length)
                {
                    var ContentArray = rsa.Decrypt(cache.ToArray(), RSAEncryptionPadding.Pkcs1);
                    result += System.Text.Encoding.UTF8.GetString(ContentArray);
                    cache.Clear();
                }
            }
            return result;
        }

        public string LDServiceFee(string SnList, int ServiceFee, int BrandId)
        {
            function.WriteLog(DateTime.Now.ToString(), "设置联动机具服务费");
            function.WriteLog(SnList, "设置联动机具服务费");
            Dictionary<string, object> reqdic = new Dictionary<string, object>();
            string RequestId = DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
            string TerminalModeName = BrandId == 10 ? "DZA" : "DZDA";
            int PosType = BrandId == 10 ? 2 : 3;
            reqdic.Add("rpid", RequestId); //请求流水
            reqdic.Add("agentNumber", AgentNo); //代理商编号
            reqdic.Add("snList", SnList.Split(',').ToList()); //SN号
            reqdic.Add("posType", PosType); //2：电签 3 大pos
            reqdic.Add("terminalModeName", TerminalModeName); //终端模式名
            reqdic.Add("fwfRate", ServiceFee); //服务费
            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            function.WriteLog(req, "设置联动机具服务费");
            req = LDEncrypt(req);
            function.WriteLog(req, "设置联动机具服务费");
            Dictionary<string, object> datadic = new Dictionary<string, object>();
            datadic.Add("encryptedData", req);
            string data = Newtonsoft.Json.JsonConvert.SerializeObject(datadic);
            function.WriteLog("请求地址：" + LDRequestUrl + "terminalSelfDistribute", "设置联动机具服务费");
            string result = function.PostWebRequest(LDRequestUrl + "terminalSelfDistribute", data, "application/json");
            function.WriteLog(result + "\n\n", "设置联动机具服务费");
            return result;
        }

        public string LDFeeRate(string MerNo, string Fee, int BrandId, int addRate = 0)
        {
            function.WriteLog(DateTime.Now.ToString(), "设置联动机具费率");
            function.WriteLog(MerNo, "设置联动机具费率");
            Dictionary<string, object> reqdic = new Dictionary<string, object>();
            string RequestId = DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
            string MercModel = BrandId == 10 ? "DZA" : "DZDA";
            int PosType = BrandId == 10 ? 2 : 3;
            reqdic.Add("rpid", RequestId); // 请求流水(2字母开头+13位数字)
            reqdic.Add("agentNumber", AgentNo); // 代理编号
            reqdic.Add("mercModel", MercModel); // 商户模式
            reqdic.Add("rate", Fee); // 费率 如 0.0053
            reqdic.Add("addRate", addRate); // 附加费 如0
            reqdic.Add("rateType", "M015"); // 秒刷 M015 扫码 S010 特惠 T015
            reqdic.Add("mercId", MerNo); // 商户编号
            reqdic.Add("cardType", "01"); // 01 贷记卡 02 扫码
            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            function.WriteLog(req, "设置联动机具费率");
            req = LDEncrypt(req);
            function.WriteLog(req, "设置联动机具费率");
            Dictionary<string, object> datadic = new Dictionary<string, object>();
            datadic.Add("encryptedData", req);
            string data = Newtonsoft.Json.JsonConvert.SerializeObject(datadic);
            function.WriteLog("请求地址：" + LDRequestUrl + "updateMercRate", "设置联动机具费率");
            string result = function.PostWebRequest(LDRequestUrl + "updateMercRate", data, "application/json");
            function.WriteLog(result + "\n\n", "设置联动机具费率");
            return result;
        }

        #endregion
        
        #region 盒易付

        //测试环境
        // string BoxRequestUrl = "https://openapi-test.iboxpay.com/api";
        // string BoxAppId = "8840021411446784";
        // string BoxAppSecret = "xgwGnmYGjVy0GOWOWkQtRk8Hk8ur5tCV";
        // string BoxPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjMQxp24mjxDTr13uPW0y+tiO1yXFGw7P/pPQ0oZKK7F6KstEaus7pLEywBZ5XRXE5jgkhR2TS7Ne7djJfbpn5yFc6pPlz3ZsOfBVeB88NEwhx6xzCGX2eqSSkO33n8w2G0xc2ss5HpYBarT00NBZWhrwOXpdRPYLOYHKVU3Rl+FA9xDw/wYfoWvrr+JSfHRGn/ENMmQFEdckAbPauKaQMrZD2kz+PRrhq56eWnCuVQPcaz/jroVT8qQEgkg2IsNy+DwfLOIqm8IySEpxnQ5wN/KvsQJc2wXDQNf9F5kvWwjoqSSP0qJS+oPRXET+zJb+WTk2y5M6AYoC9NodwsC4NwIDAQAB";
        // string BrhCode = "039001";

        //生产环境
        string BoxRequestUrl = "https://openapi.iboxpay.com/api";
        string BoxAppId = "AP5879017839106039808";
        string BoxAppSecret = "DGtftIyl6R3nzwPr5YuV5fnmkfwufXRj";
        string BoxPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjmjoQirIYZBD9Qon2HkF4j/NAINXtJ7Lzq/WXxTF7t7mg7LNARt0+ZZaeWx8caq2fv5zdsGyyoInL23cBtDI5KmFfK69iA0ygQMK0WbiKqsUB1OpPbT3+9zLuadIJAznjA223lY6CIjTpdLZhaRjImNVqc60bdkx6YsQcA+xW+3r1JH4PPHb7yBEbkKIX8OhyX7U4p0TkbDkAobbjHr5YB9gmYLoSFJMOPfTtSExkv7/Y7IVR9poZAHcr3teFoAiXW3RzxelRtnXxIkl/6AUOKoL5fhr/UTUN+Q18uzNljYWr6SwnTI3EmtzgykaewWtZvV85Xdhe/BjiQ5Xor7YbwIDAQAB";
        string BrhCode = "039004";

        public string BoxFee(string MerNo, string Fee)
        {
            function.WriteLog(DateTime.Now.ToString(), "设置盒易付机具费率");
            function.WriteLog(MerNo, "设置盒易付机具费率");
            Dictionary<string, object> reqdic = new Dictionary<string, object>();
            Dictionary<string, string> headdic = new Dictionary<string, string>();
            string batchNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);

            string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            headdic.Add("appid", BoxAppId);//开发者id
            headdic.Add("appsecret", BoxAppSecret);//开发者密码
            headdic.Add("X-Up-AppId", BoxAppId);
            headdic.Add("X-Timestamp", timestamp);
            headdic.Add("X-Sign-Type", "SHA-256");

            reqdic.Add("mchtNo", MerNo);//终端列表
            reqdic.Add("brhCode", BrhCode);//机构号
            //MHN10917（贷记0.63%，借记卡0.63%/25） MHN10916(贷记0.60%，借记卡0.60%/25)
            reqdic.Add("tNDiscId", Fee == "0.60" ? "MHN10916" : "MHN10917");//费率模型
            reqdic.Add("effectiveFlag", "1");//立即生效
            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);

            headdic.Add("X-Sign", BoxSHA256Sign(timestamp + BoxAppSecret + req));
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            function.WriteLog("请求头\n" + head, "设置盒易付机具费率");
            function.WriteLog("请求参数\n" + req, "设置盒易付机具费率");
            function.WriteLog("请求地址：" + BoxRequestUrl + "/inst/mcht/update_disc", "设置盒易付机具费率");
            string result = PostWebRequest(BoxRequestUrl + "/inst/mcht/update_disc", req, headdic);
            function.WriteLog("返回\n" + result + "\n\n", "设置盒易付机具费率");
            return result;
        }

        public string BoxSHA256Sign(string toSignStr)
        {
            byte[] toSignByte = Encoding.UTF8.GetBytes(toSignStr);
            SHA256 sha256 = SHA256.Create();
            byte[] signByte = sha256.ComputeHash(toSignByte);
            string sign = Convert.ToBase64String(signByte);
            return sign;
        }

        public bool BoxVerifySign(string toSignStr, string signStr)
        {
            byte[] toSignByte = Encoding.Default.GetBytes(toSignStr);
            byte[] signByte = Convert.FromBase64String(signStr);
            var toKey = Convert.FromBase64String(BoxPublicKey);
            var rsaroot = RSA.Create();
            rsaroot.ImportSubjectPublicKeyInfo(toKey, out _);
            var publicKeyParameters = rsaroot.ExportParameters(false);
            using (var rsa = RSA.Create())
            {
                rsa.ImportParameters(publicKeyParameters);
                var sha256 = SHA256.Create();
                var hash = sha256.ComputeHash(toSignByte);
                return rsa.VerifyHash(hash, signByte, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
            }
        }

        public string BoxSignData(string toSignStr)
        {
            byte[] toSignByte = Encoding.UTF8.GetBytes(toSignStr);
            var toKey = Convert.FromBase64String(BoxPublicKey);
            var rsaroot = RSA.Create();
            rsaroot.ImportSubjectPublicKeyInfo(toKey, out _);
            var publicKeyParameters = rsaroot.ExportParameters(false);
            using (var rsa = RSA.Create())
            {
                rsa.ImportParameters(publicKeyParameters);
                var sha256 = SHA256.Create();
                var hash = sha256.ComputeHash(toSignByte);
                byte[] endByte = rsa.SignData(toSignByte, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
                return Convert.ToBase64String(endByte);
            }
        }

        #endregion



    }
}