using System.Net.Mime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Library;
using System.Net;
using System.IO;
using Aop.Api.Util;
using LitJson;

namespace MySystem
{
    /// <summary>
    /// 好哒相关接口
    /// </summary>
    public class HaoDaHelper
    {
        public readonly static HaoDaHelper Instance = new HaoDaHelper();
        private HaoDaHelper()
        {
        }

        #region 盒易付

        //测试环境
        // string BoxRequestUrl = "https://openapi-test.iboxpay.com";
        // string BoxAppId = "AT7317781468267548672";
        // string BoxAppSecret = "OfWuHQdhQfnE8NaF4xdtgk4B9CYqnbri";
        // string BoxPublicKey = "";
        // string BrhCode = "001040";

        //生产环境
        // string BoxRequestUrl = "https://openapi.iboxpay.com";
        // string BoxAppId = "AP7175619323825451008";
        // string BoxAppSecret = "hUfR53gdjyfiZTBR5bILanMqRD1dXD7y";
        // string BoxPublicKey = "";
        // public static string BrhCode = "030145";

        // string BoxRequestUrl = "https://openapi.iboxpay.com";
        // string BoxAppId = "AP8322645764893728768";
        // string BoxAppSecret = "je1TElprp3jzWETsG3FcWqtmpreEHqZS";
        // string BoxPublicKey = "";
        // public static string BrhCode = "";


        /// <summary>
        /// 新创建商户
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public string AddNewMerchant(AddNewMerchant request, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1)
            {
                BoxRequestUrl = HaodaParam.BoxRequestUrl;
                string oprInvitedCode = "";
                if (BrandId == 1)
                {
                    if(string.IsNullOrEmpty(RedisDbconn.Instance.Get<string>("AgentInvitedCode:" + AgentTag)))
                    {
                        oprInvitedCode = RedisDbconn.Instance.Get<string>("AgentInvitedCode:1");
                    }
                    else
                    {
                        oprInvitedCode = RedisDbconn.Instance.Get<string>("AgentInvitedCode:" + AgentTag);
                    }
                }
                request.oprInvitedCode = oprInvitedCode;
            }

            // request.brh = BrhCode;
            string logString = "";
            logString += "\n" + DateTime.Now.ToString();

            string req = Newtonsoft.Json.JsonConvert.SerializeObject(request);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/inst/mcht/new_create_mcht";
            string result = PostWebRequest(BoxRequestUrl + "/api/inst/mcht/new_create_mcht", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒新创建商户", true);

            return result;
        }

        /// <summary>
        /// 查询商户审核状态
        /// </summary>
        /// <param name="instId">机构编号</param>
        /// <param name="mchtNo">收款商户号</param>
        /// <returns></returns>
        public string QueryMerchantStatus(string instId, string mchtNo, int BrandId = 0, string AgentTag = "1")
        {
            if(string.IsNullOrEmpty(mchtNo))
            {
                return "{}";
            }
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            
            string logString = "";
            logString += "\n" + DateTime.Now.ToString();
            Dictionary<string, object> reqdic = new Dictionary<string, object>();
            reqdic.Add("instId", instId);
            reqdic.Add("mchtNo", mchtNo);

            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/inst/mcht/query_mcht_audit";
            string result = PostWebRequest(BoxRequestUrl + "/api/inst/mcht/query_mcht_audit", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            
            LogHelper.Instance.WriteLog(logString, "好哒查询商户审核状态", true);

            return result;
        }

        /// <summary>
        /// 查询实名认证状态
        /// </summary>
        /// <param name="mchtNo">慧掌柜商户号</param>
        /// <param name="storeNo">慧掌柜门店号</param>
        /// <returns></returns>
        public string QueryAuthStatus(string mchtNo, string storeNo, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();
            Dictionary<string, object> reqdic = new Dictionary<string, object>();
            reqdic.Add("mchtNo", mchtNo); // 慧掌柜商户号
            reqdic.Add("storeNo", storeNo); // 慧掌柜门店号
            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/hzg/v2/wechat/queryVerifiedResult.json";
            string result = PostWebRequest(BoxRequestUrl + "/api/hzg/v2/wechat/queryVerifiedResult.json", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            
            LogHelper.Instance.WriteLog(logString, "好哒查询实名认证状态", true);

            return result;
        }

        /// <summary>
        /// 查询实名认证二维码
        /// </summary>
        /// <param name="mchtNo">慧掌柜商户号</param>
        /// <param name="storeNo">慧掌柜门店号</param>
        /// <returns></returns>
        public string QueryAuthQRcode(string mchtNo, string storeNo, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();
            Dictionary<string, object> reqdic = new Dictionary<string, object>();
            reqdic.Add("mchtNo", mchtNo); // 慧掌柜商户号
            reqdic.Add("storeNo", storeNo); // 慧掌柜门店号
            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/hzg/v2/wechat/queryVerifiedQrcode.json";
            string result = PostWebRequest(BoxRequestUrl + "/api/hzg/v2/wechat/queryVerifiedQrcode.json", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒查询实名认证二维码", true);

            return result;
        }

        /// <summary>
        /// 微信公众号和小程序支付接口
        /// </summary>
        /// <param name="mchtNo">盒子的商户编号</param>
        /// <param name="storeNo">盒子的门店编码</param>
        /// <param name="outOrderNo">商户订单号</param>
        /// <param name="transAmount">交易金额，单位：分</param>
        /// <param name="callbackUrl">交易完成之后，商户接收交易结果通知的地址</param>
        /// <param name="subOpenId">用户子标识</param>
        /// <param name="confirmCode">支付确认码</param>
        /// <param name="subAppId">公众号或者小程序appId</param>
        /// <param name="subAppIdType">对应的类型，默认为公众号， SUBSCRIPTION: 公众号 MINI_PROGRAM: 小程序</param>
        /// <param name="ledgerModel">分账类型:1不分账 2分账,注意只有开通了分账才能传这个字段</param>
        /// <returns></returns>
        public string WeChatPay(string mchtNo, string storeNo, string outOrderNo, string transAmount, string callbackUrl, string subOpenId, string confirmCode, string subAppId, string subAppIdType, string ledgerModel, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();
            Dictionary<string, object> reqdic = new Dictionary<string, object>();
            reqdic.Add("mchtNo", mchtNo); //盒子的商户编号
            reqdic.Add("storeNo", storeNo); //盒子的门店编码	
            reqdic.Add("outOrderNo", outOrderNo); //商户订单号
            reqdic.Add("transAmount", transAmount); //交易金额，单位：分
            reqdic.Add("callbackUrl", callbackUrl); //交易完成之后，商户接收交易结果通知的地址	
            reqdic.Add("subOpenId", subOpenId); //用户子标识
            reqdic.Add("confirmCode", confirmCode); //支付确认码，由4位纯数字组成，每次请求时随机生成	
            reqdic.Add("subAppId", subAppId); //公众号或者小程序appId	
            reqdic.Add("subAppIdType", subAppIdType); //subAppId 对应的类型，默认为公众号， SUBSCRIPTION: 公众号 MINI_PROGRAM: 小程序
            reqdic.Add("ledgerModel", ledgerModel); //分账类型:1不分账 2分账,注意只有开通了分账才能传这个字段

            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/hzg/v2/unitedtrade/wechat_js_pay";
            string result = PostWebRequest(BoxRequestUrl + "/api/hzg/v2/unitedtrade/wechat_js_pay", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒微信公众号和小程序支付", true);

            return result;
        }

        /// <summary>
        /// 支付宝服务窗支付接口
        /// </summary>
        /// <param name="mchtNo">盒子的商户编号</param>
        /// <param name="storeNo">盒子的门店编码</param>
        /// <param name="outOrderNo">商户订单号</param>
        /// <param name="transAmount">交易金额，单位：分</param>
        /// <param name="callbackUrl">交易完成之后，商户接收交易结果通知的地址</param>
        /// <param name="subOpenId">支付宝用户标识</param>
        /// <param name="confirmCode">支付确认码，由4位纯数字组成，每次请求时随机生成</param>
        /// <returns></returns>
        public string Alipay(string mchtNo, string storeNo, string outOrderNo, string transAmount, string callbackUrl, string subOpenId, string confirmCode, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();
            Dictionary<string, object> reqdic = new Dictionary<string, object>();
            reqdic.Add("mchtNo", mchtNo); //盒子的商户编号
            reqdic.Add("storeNo", storeNo); //盒子的门店编码	
            reqdic.Add("outOrderNo", outOrderNo); //商户订单号
            reqdic.Add("transAmount", transAmount); //交易金额，单位：分	
            reqdic.Add("callbackUrl", callbackUrl); //交易完成之后，商户接收交易结果通知的地址
            reqdic.Add("subOpenId", subOpenId); //支付宝用户标识	
            reqdic.Add("confirmCode", confirmCode); //支付确认码，由4位纯数字组成，每次请求时随机生成

            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/hzg/v2/unitedtrade/wechat_js_pay";
            string result = PostWebRequest(BoxRequestUrl + "/api/hzg/v2/unitedtrade/wechat_js_pay", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒新创建商户", true);

            return result;
        }

        /// <summary>
        /// 聚合支付退款接口
        /// </summary>
        /// <param name="mchtNo">盒子的商户编号</param>
        /// <param name="storeNo">盒子的门店编号</param>
        /// <param name="outRefundNo">商户退款订单号</param>
        /// <param name="outOrderNo">商户支付订单号</param>
        /// <param name="refundAmount">退款金额，单位：分</param>
        /// <returns></returns>
        public string AggregatedPayRefund(string mchtNo, string storeNo, string outRefundNo, string outOrderNo, string refundAmount, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();
            Dictionary<string, object> reqdic = new Dictionary<string, object>();

            reqdic.Add("mchtNo", mchtNo); // 盒子的商户编号	
            reqdic.Add("storeNo", storeNo); // 盒子的门店编号	
            reqdic.Add("outRefundNo", outRefundNo); //32 商户退款订单号	
            reqdic.Add("outOrderNo", outOrderNo); // 商户支付订单号	
            reqdic.Add("refundAmount", refundAmount); //10 退款金额，单位：分
            reqdic.Add("refundReason", "门店消费补贴"); //退款原因        

            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/hzg/v2/unitedtrade/refund";
            string result = PostWebRequest(BoxRequestUrl + "/api/hzg/v2/unitedtrade/refund", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒聚合支付退款", true);

            return result;
        }

        /// <summary>
        /// 开通分账功能
        /// </summary>
        /// <param name="mchtNo">慧掌柜商户号(进件接口返回的outMchtNo字段)</param>
        /// <param name="storeNo">慧掌柜门店号</param>
        /// <returns></returns>
        public string OpenDivideAccounts(string mchtNo, string storeNo, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();
            Dictionary<string, object> reqdic = new Dictionary<string, object>();

            reqdic.Add("mchtNo", mchtNo); // 慧掌柜商户号	
            reqdic.Add("storeNo", storeNo); // 慧掌柜门店号	

            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/v3/hzg/part/mcht/reg";
            string result = PostWebRequest(BoxRequestUrl + "/api/v3/hzg/part/mcht/reg", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒开通分账", true);

            return result;
        }

        /// <summary>
        /// 分账接收方签约
        /// </summary>
        /// <param name="acctNo">账户号</param>
        /// <param name="mchtNo">慧掌柜商户号</param>
        /// <param name="storeNo">慧掌柜门店号</param>
        /// <returns></returns>
        public string DivideAccountsSign(string acctNo, string mchtNo, string storeNo, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();
            Dictionary<string, object> reqdic = new Dictionary<string, object>();
            reqdic.Add("acctNo", acctNo); // 账户号	
            reqdic.Add("mchtNo", mchtNo); // 慧掌柜商户号
            reqdic.Add("storeNo", storeNo); // 慧掌柜门店号
            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/v3/hzg/part/acct/bind_mcht";
            string result = PostWebRequest(BoxRequestUrl + "/api/v3/hzg/part/acct/bind_mcht", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒分账接收方签约", true);

            return result;
        }

        /// <summary>
        /// 添加分账接收方账户
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public string AddOpenDivideAccounts(AddOpenDivideAccounts request, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();

            string req = Newtonsoft.Json.JsonConvert.SerializeObject(request);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/v3/hzg/part/acct/register";
            string result = PostWebRequest(BoxRequestUrl + "/api/v3/hzg/part/acct/register", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒添加分账接收方账户", true);

            return result;
        }

        /// <summary>
        /// 分账交易详情查询
        /// </summary>
        /// <param name="mchtNo">慧掌柜商户号</param>
        /// <param name="orderNo">交易订单号	</param>
        /// <returns></returns>
        public string QueryOrderDivideAccounts(string mchtNo, string orderNo, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();
            Dictionary<string, object> reqdic = new Dictionary<string, object>();
            reqdic.Add("mchtNo", mchtNo); // 慧掌柜商户号
            reqdic.Add("orderNo", orderNo); // 交易订单号	
            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/v3/hzg/part/acct/bind_mcht";
            string result = PostWebRequest(BoxRequestUrl + "/api/v3/hzg/part/acct/bind_mcht", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒分账交易详情查询", true);

            return result;
        }

        /// <summary>
        /// 分账交易详情查询
        /// </summary>
        /// <param name="mchtNo">慧掌柜商户号</param>
        /// <param name="orderNo">交易订单号	</param>
        /// <returns></returns>
        public string QueryOrderDivideDetail(string mchtNo, string orderNo, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();
            Dictionary<string, object> reqdic = new Dictionary<string, object>();
            reqdic.Add("mchtNo", mchtNo); // 慧掌柜商户号
            reqdic.Add("orderNo", orderNo); // 交易订单号	
            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/v3/hzg/part/trade/clear/get";
            string result = PostWebRequest(BoxRequestUrl + "/api/v3/hzg/part/trade/clear/get", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒分账交易详情查询", true);

            return result;
        }

        /// <summary>
        /// 订单分账申请
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// 
        public string OrderDivideAccounts(OrderDivideAccounts request, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();

            string req = Newtonsoft.Json.JsonConvert.SerializeObject(request);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/v3/hzg/part/order/apply";
            string result = PostWebRequest(BoxRequestUrl + "/api/v3/hzg/part/order/apply", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒订单分账申请", true);

            return result;
        }

        /// <summary>
        /// 订单分账结果查询
        /// </summary>
        /// <param name="applyNo">分账批次号</param>
        /// <param name="mchtNo">慧掌柜商户号</param>
        /// <returns></returns>
        public string OrderDivideAccountsQuery(string applyNo, string mchtNo, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();
            Dictionary<string, object> reqdic = new Dictionary<string, object>();
            reqdic.Add("applyNo", applyNo); // 账户号	
            reqdic.Add("mchtNo", mchtNo); // 慧掌柜商户号
            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/v3/hzg/part/apply/query";
            string result = PostWebRequest(BoxRequestUrl + "/api/v3/hzg/part/apply/query", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒订单分账结果查询", true);

            return result;
        }

        /// <summary>
        /// 商户修改银行卡
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public string ChangeMerchantCard(ChangeMerchantCard request, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();

            string req = Newtonsoft.Json.JsonConvert.SerializeObject(request);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/inst/mcht/update_acct";
            string result = PostWebRequest(BoxRequestUrl + "/api/inst/mcht/update_acct", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒商户修改银行卡", true);

            return result;
        }

        /// <summary>
        /// 查询修改银行卡任务审核状态
        /// </summary>
        /// <param name="mchtNo">收款商户号</param>
        /// <param name="taskId">任务id</param>
        /// <returns></returns>
        public string QueryChangeCardStatus(string mchtNo, string taskId, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();
            Dictionary<string, object> reqdic = new Dictionary<string, object>();
            reqdic.Add("mchtNo", mchtNo);
            reqdic.Add("taskId", taskId);

            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/inst/mcht/query_acct_task";
            string result = PostWebRequest(BoxRequestUrl + "/api/inst/mcht/query_acct_task", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒查询修改银行卡任务审核状态", true);

            return result;
        }


        /// <summary>
        /// 绑定微信appid接口
        /// </summary>
        /// <param name="mchtNo">盒子的商户编号</param>
        /// <param name="storeNo">盒子的门店编号</param>
        /// <param name="subAppId">公众号appid或者小程序appid</param>
        /// <returns></returns>
        public string BindWeChatAppId(string mchtNo, string storeNo, string subAppId, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();
            Dictionary<string, object> reqdic = new Dictionary<string, object>();

            reqdic.Add("mchtNo", mchtNo); // 盒子商户号	
            reqdic.Add("storeNo", storeNo); // 盒子门店号	
            reqdic.Add("subAppId", subAppId); // 公众号appid或者小程序appid	

            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/hzg/v2/wechat/add_sub_config";
            string result = PostWebRequest(BoxRequestUrl + "/api/hzg/v2/wechat/add_sub_config", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            
            LogHelper.Instance.WriteLog(logString, "好哒绑定微信appid接口", true);

            return result;
        }

        /// <summary>
        /// 到账记录查询
        /// </summary>
        /// <param name="mchtNo">商户号</param>
        /// <param name="startTime">查询开始时间（yyyy-MM-dd）</param>
        /// <param name="endTime">查询结束时间（yyyy-MM-dd），最大查询时间区间31天</param>
        /// <param name="tradeMchtNo">收单商户号（15位）</param>
        /// <param name="cardNo">结算卡号</param>
        /// <param name="settleStatus">出款状态（0：入账成功、1：入账失败、2：结算超时、3：入账受理成功、4：已提交结算请求）</param>
        /// <param name="page">当前页数，默认1</param>
        /// <param name="rows">每页大小，默认10，最大500</param>
        /// <returns></returns>
        public string QueryAccountList(string mchtNo, string startTime, string endTime, string tradeMchtNo, string cardNo, string settleStatus, string page = "1", string rows = "10", int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();
            Dictionary<string, object> reqdic = new Dictionary<string, object>();

            reqdic.Add("mchtNo", mchtNo); // 盒子商户号	
            reqdic.Add("startTime", startTime); // 查询开始时间（yyyy-MM-dd）	
            reqdic.Add("endTime", endTime); // 查询结束时间（yyyy-MM-dd），最大查询时间区间31天	
            reqdic.Add("tradeMchtNo", tradeMchtNo); // 收单商户号（15位）	
            reqdic.Add("cardNo", cardNo); // 结算卡号	
            reqdic.Add("settleStatus", settleStatus); // 出款状态（0：入账成功、1：入账失败、2：结算超时、3：入账受理成功、4：已提交结算请求）	
            reqdic.Add("page", page); // 当前页数，默认1	
            reqdic.Add("rows", rows); // 每页大小，默认10，最大500	

            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/v3/hzg/accb/to_account/query";
            string result = PostWebRequest(BoxRequestUrl + "/api/v3/hzg/accb/to_account/query", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒到账记录查询", true);

            return result;
        }

        /// <summary>
        /// 到账记录详情
        /// </summary>
        /// <param name="mchtNo">商户号</param>
        /// <param name="id"></param>
        /// <returns></returns>
        public string QueryAccountDetail(string mchtNo, string id, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();
            Dictionary<string, object> reqdic = new Dictionary<string, object>();

            reqdic.Add("mchtNo", mchtNo); // 商户号	
            reqdic.Add("id", id); // id	

            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/v3/hzg/accb/to_account/get";
            string result = PostWebRequest(BoxRequestUrl + "/api/v3/hzg/accb/to_account/get", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒到账记录详情", true);

            return result;
        }

        /// <summary>
        /// 聚合支付查询接口
        /// </summary>
        /// <param name="mchtNo">商户号</param>
        /// <param name="outOrderNo">商户订单号</param>
        /// <returns></returns>
        public string QueryTradeDetail(string mchtNo, string outOrderNo, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();
            Dictionary<string, object> reqdic = new Dictionary<string, object>();

            reqdic.Add("mchtNo", mchtNo); // 商户号	
            reqdic.Add("outOrderNo", outOrderNo); // 商户订单号

            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/hzg/v2/unitedtrade/query_status";
            string result = PostWebRequest(BoxRequestUrl + "/api/hzg/v2/unitedtrade/query_status", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒聚合支付查询", true);

            return result;
        }

        /// <summary>
        /// 聚合支付退款查询接口
        /// </summary>
        /// <param name="mchtNo">商户号</param>
        /// <param name="storeNo">门店编号</param>
        /// <param name="outRefundNo">退款订单号</param>
        /// <returns></returns>
        public string QueryRefundDetail(string mchtNo, string storeNo, string outRefundNo, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();
            Dictionary<string, object> reqdic = new Dictionary<string, object>();

            reqdic.Add("mchtNo", mchtNo); // 商户号	
            reqdic.Add("storeNo", storeNo); // 商户订单号
            reqdic.Add("outRefundNo", outRefundNo);

            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/hzg/v2/unitedtrade/refund_query";
            string result = PostWebRequest(BoxRequestUrl + "/api/hzg/v2/unitedtrade/refund_query", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒退款查询", true);

            return result;
        }

        /// <summary>
        /// 修改商户费率
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public string SetFee(string mchtNo, string feeRate, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();
            
            Dictionary<string, object> request = new Dictionary<string, object>();

            request.Add("mchtNo", mchtNo); // 商户号
            request.Add("alipayRate", feeRate);
            request.Add("wechatPayRate", feeRate);
            request.Add("unionPayRate", feeRate);

            string req = Newtonsoft.Json.JsonConvert.SerializeObject(request);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/inst/mcht/update_disc";
            string result = PostWebRequest(BoxRequestUrl + "/api/inst/mcht/update_disc", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒商户修改费率", true);

            return result;
        }

        public Dictionary<string, string> GetHeader(string req, int BrandId = 0, string Agent = "1")
        {
            var BoxAppId = HaodaUnionParam.BoxAppId;
            var BoxAppSecret = HaodaUnionParam.BoxAppSecret;
            if (BrandId == 1)
            {
                if(string.IsNullOrEmpty(RedisDbconn.Instance.Get<string>("AgentAppId:" + Agent)))
                {
                    BoxAppId = RedisDbconn.Instance.Get<string>("AgentAppId:1");
                    BoxAppSecret = RedisDbconn.Instance.Get<string>("AgentAppSecret:1");
                }
                else
                {
                    BoxAppId = RedisDbconn.Instance.Get<string>("AgentAppId:" + Agent);
                    BoxAppSecret = RedisDbconn.Instance.Get<string>("AgentAppSecret:" + Agent);
                }
            }

            Dictionary<string, string> headdic = new Dictionary<string, string>();
            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");
            headdic.Add("X-Sign", SHA256Sign(timestamp + BoxAppSecret + req));
            return headdic;
        }

        public string SHA256Sign(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 VerifySign(string toSignStr, string signStr, int BrandId = 0, string AgentTag = "1")
        {
            var BoxPublicKey = HaodaUnionParam.BoxPublicKey;
            if (BrandId == 1) BoxPublicKey = HaodaParam.BoxPublicKey;

            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 SignData(string toSignStr, int BrandId = 0, string AgentTag = "1")
        {
            var BoxPublicKey = HaodaUnionParam.BoxPublicKey;
            if (BrandId == 1) BoxPublicKey = HaodaParam.BoxPublicKey;

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

        private string PostWebRequest(string postUrl, string paramData, Dictionary<string, string> headers)
        {
            string ret = string.Empty;
            try
            {
                string logString = "";
                logString += "\n" + DateTime.Now.ToString();
                logString += "\n" + postUrl;
                logString += "\n" + paramData;
                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();
                logString += "\n" + srcString;
                
                LogHelper.Instance.WriteLog(logString, "请求好哒API日志", true);
            }
            catch (System.Net.WebException ex)
            {
                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)ex.Response;
                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";
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "请求好哒API异常", true);
            }
            return ret;
        }

        /// <summary>
        /// 获取文件令牌接口
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="action">操作类型 0 上传图片</param>
        /// <returns></returns>
        public string GetToken(string fileName, string action, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            string logString = "";
            logString += "\n" + DateTime.Now.ToString();
            Dictionary<string, object> reqdic = new Dictionary<string, object>();

            reqdic.Add("fileName", fileName); // 文件名	
            reqdic.Add("action", action); // 操作类型 0 上传图片

            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
            logString += "\n" + req;
            Dictionary<string, string> headdic = GetHeader(req, BrandId, AgentTag);
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            logString += "\n" + "请求头\n" + head;
            logString += "\n" + "请求参数\n" + req;
            logString += "\n" + "请求地址：" + BoxRequestUrl + "/api/auth/v1/get_file_token";
            string result = PostWebRequest(BoxRequestUrl + "/api/auth/v1/get_file_token", req, headdic);
            logString += "\n" + "返回\n" + result + "\n\n";
            LogHelper.Instance.WriteLog(logString, "好哒获取文件令牌接口", true);

            return result;
        }

        /// <summary>
        /// 执行带文件上传的HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="textParams">请求文本参数</param>
        /// <param name="fileParams">请求文件参数</param>
        /// <param name="charset">编码字符集</param>
        /// <returns>HTTP响应</returns>
        public string DoPost(string url, string token, IDictionary<string, string> textParams, IDictionary<string, FileItem> fileParams, string charset = "utf-8")
        {
            // 如果没有文件参数，则走普通POST请求
            if (fileParams == null || fileParams.Count == 0)
            {
                return "";
            }

            string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线

            HttpWebRequest req = GetWebRequest(url, "POST");
            req.Headers.Add("X-File-Token", token);
            req.ContentType = "multipart/form-data;charset=" + charset + ";boundary=" + boundary;

            Stream reqStream = req.GetRequestStream();
            byte[] itemBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "\r\n");
            byte[] endBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "--\r\n");

            // 组装文本请求参数
            string textTemplate = "Content-Disposition:form-data;name=\"{0}\"\r\nContent-Type:text/plain\r\n\r\n{1}";
            IEnumerator<KeyValuePair<string, string>> textEnum = textParams.GetEnumerator();
            while (textEnum.MoveNext())
            {
                string textEntry = string.Format(textTemplate, textEnum.Current.Key, textEnum.Current.Value);
                byte[] itemBytes = Encoding.GetEncoding(charset).GetBytes(textEntry);
                reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                reqStream.Write(itemBytes, 0, itemBytes.Length);
            }

            // 组装文件请求参数
            string fileTemplate = "Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n";
            IEnumerator<KeyValuePair<string, FileItem>> fileEnum = fileParams.GetEnumerator();
            while (fileEnum.MoveNext())
            {
                string key = fileEnum.Current.Key;
                FileItem fileItem = fileEnum.Current.Value;
                string fileEntry = string.Format(fileTemplate, key, fileItem.GetFileName(), fileItem.GetMimeType());
                byte[] itemBytes = Encoding.GetEncoding(charset).GetBytes(fileEntry);
                reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                reqStream.Write(itemBytes, 0, itemBytes.Length);

                byte[] fileBytes = fileItem.GetContent();
                reqStream.Write(fileBytes, 0, fileBytes.Length);
            }

            reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            reqStream.Close();

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            return GetResponseAsString(rsp, encoding);
        }

        public HttpWebRequest GetWebRequest(string url, string method)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.ServicePoint.Expect100Continue = false;
            req.Method = method;
            req.KeepAlive = true;
            req.Timeout = 100000;
            return req;
        }

        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        public string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            StringBuilder result = new StringBuilder();
            Stream stream = null;
            StreamReader reader = null;

            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);

                // 按字符读取并写入字符串缓冲
                int ch = -1;
                while ((ch = reader.Read()) > -1)
                {
                    // 过滤结束符
                    char c = (char)ch;
                    if (c != '\0')
                    {
                        result.Append(c);
                    }
                }
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }

            return result.ToString();
        }


        /// <summary>
        /// 获取好哒开放平台文件名
        /// </summary>
        /// <param name="token">上传图片凭证token</param>
        /// <param name="value">图片路径</param>
        /// <returns></returns>
        public string ReturnFileName(string token, string value, int BrandId = 0, string AgentTag = "1")
        {
            var BoxRequestUrl = HaodaUnionParam.BoxRequestUrl;
            if (BrandId == 1) BoxRequestUrl = HaodaParam.BoxRequestUrl;

            Dictionary<string, string> file = new Dictionary<string, string>();
            file.Add("fileName", value.Substring(value.LastIndexOf("/")).Trim('/'));
            if (string.IsNullOrEmpty(value.Split(',')[0]))
            {
                return "";
            }
            FileItem item = PublicFunction.GetNetFileItem(AppConfig.Base.OssHost + value.Split(',')[0]);
            // FileItem item = new FileItem(function.getPath(value.Split(',')[0]));
            Dictionary<string, FileItem> files = new Dictionary<string, FileItem>();
            files.Add("file", item);
            var upLoadInfo = JsonMapper.ToObject(HaoDaHelper.Instance.DoPost(BoxRequestUrl + "/api/file/v1/upload_file", token, file, files, "utf-8"));
            if (upLoadInfo["code"].ToString() == "1")
            {
                return upLoadInfo["data"]["fileName"].ToString();
            }
            else
            {
                return "false";
            }
        }

        #endregion

    }
}