using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using MySystem.Models.Main;
using Library;
using LitJson;
using System.Threading;
using System.Net;
using System.IO;

namespace MySystem
{
    /// <summary>
    /// 好哒测试服务
    /// </summary>
    public class TestHaoDaService
    {
        public readonly static TestHaoDaService Instance = new TestHaoDaService();
        private TestHaoDaService()
        { }

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

        public void StartListen()
        {
            // GetFTPListInfo(); // 获取好哒FTPInfo
            GetFTPDataInfo(); //获取好哒FTPDataInfo
            //开户意愿申请
            // RedisDbconn.Instance.AddList("AlipayForHaoDaQueue",824);
            // RedisDbconn.Instance.AddList("WeChatForHaoDaQueue",824);
            // AlipayAddInfo(826);//提交支付宝开户意愿申请单
            // AlipayAddInfo(828,"202309011037906510");//查询支付宝开户意愿申请状态
            // WeChatAddInfo(826);//提交微信开户意愿申请单
            // WeChatAddInfo(825,"2000002424428809");//查询微信开户意愿申请状态
            // ConfiemMer(1833);//新建商户
            // QueryMerchantStatus(1833);//新建商户查询状态
            // GetTencentAddressInfo(112); //获取商户经纬坐标
            // ChangeMerchantCard(1);//商户修改银行卡
            // QueryChangeCardStatus(1874);//商户修改银行卡状态
            // AddOpenDivideAccounts(832); //添加分账方
            // QueryAuthStatus(1845);//查询实名认证状态
            // WeChatFunctionForHD.Instance.QueryAuthMerchant("600955391");
            // AlipayFunctionForHD.Instance.AuthOrderAuthQuery("2088820718243322");
            // StartProfitShareListen();
            // HaoDaHelper.Instance.BindWeChatAppId("1490230", "21622558", AppConfig.Haoda.SubAppId);

            // HaoDaHelper.Instance.OrderDivideAccountsQuery("FZ2023110315225748140470708", "1492500"); //查询分账结果
            // WebCMSEntities db = new WebCMSEntities();

            // List<int> ids = new List<int>();
            // foreach(int id in ids)
            // {
            //     ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == id) ?? new ConsumerOrders();
            //     MerchantAddInfo merchantAdd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantAddInfo();
            //     string applyNo = "FZ" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8); //批次号
            //     string mchtNo = merchantAdd.OutMchtNo; //慧掌柜商户号
            //     string orderNo = order.SeoTitle; //交易订单号（好哒平台订单号，G开头）
            //     string acctNo = AppConfig.Haoda.AcctNo; //账户号，分账接收方账户号
            //     string sacctNo = merchantAdd.MchtNo; //账户号，收款商户号
            //     string acctType = "0"; //账户类型（0：商户收款账户（大B），1：分账接收方账户（小B））
            //     // decimal hdfee = 0.0038M * order.PayMoney;
            //     // hdfee = decimal.Parse(hdfee.ToString("f2"));
            //     // decimal servicefee = 0.01M * order.PayMoney;
            //     // servicefee = decimal.Parse(servicefee.ToString("f2"));
            //     // decimal amount = order.PayMoney - hdfee - servicefee;
            //     // amount = amount * 100; //金额（分）
            //     // servicefee = servicefee * 100;
            //     // string seviceAmount = servicefee.ToString("f0"); //服务费
            //     string result = HaoDaHelper.Instance.OrderDivideAccounts(OrderDivideAccountsUtil.AddValue(applyNo, mchtNo, orderNo, acctNo, sacctNo, acctType, "1", "0"));
            // }

            // string content = function.ReadInstance("content.txt");
            // string[] list = content.Split('\n');
            // foreach(string sub in list)
            // {
            //     JsonData jsonObj = JsonMapper.ToObject(sub);
            //     string orderNo = jsonObj["orderNo"].ToString();

            //     JsonData detail = jsonObj["detail"];
            //     string me = detail[0]["amount"].ToString();
            //     string mer = detail[1]["amount"].ToString();
            //     ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.SeoTitle == orderNo) ?? new ConsumerOrders();
            //     if(order.SettleAmount > 0)
            //     {
            //         MerchantParamSet set = Newtonsoft.Json.JsonConvert.DeserializeObject<MerchantParamSet>(order.SeoDescription);
            //         MerchantAddInfo merchantAdd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantAddInfo();
            //         string applyNo = "FZ" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8); //批次号
            //         string mchtNo = merchantAdd.OutMchtNo; //慧掌柜商户号
            //         string acctNo = AppConfig.Haoda.AcctNo; //账户号，分账接收方账户号
            //         string sacctNo = merchantAdd.MchtNo; //账户号，收款商户号

            //         decimal settleAmount = (decimal)order.SettleAmount / 100M;
            //         decimal divideAmt = (1 - 0.0038M) * order.PayMoney;
            //         divideAmt = decimal.Parse(divideAmt.ToString("f2"));
            //         decimal hdfee = 0.0038M * order.PayMoney * (1 - set.GetPercent / 100 - 0.01M);
            //         hdfee = decimal.Parse(hdfee.ToString("f2"));
            //         decimal servicefee = 0.01M * order.PayMoney - hdfee;
            //         servicefee = decimal.Parse(servicefee.ToString("f2"));
            //         decimal amount = order.PayMoney*(1-0.0038M) - servicefee;
            //         amount = decimal.Parse(amount.ToString("f2"));
            //         decimal otherAmt = settleAmount - servicefee - amount;
            //         if(otherAmt != 0)
            //         {
            //             amount += otherAmt;
            //         }

            //         amount -= decimal.Parse(mer) / 100M;
            //         servicefee -= decimal.Parse(me) / 100M;
            //         if(amount > 0)
            //         {
            //             if(servicefee < 0) servicefee = 0;

            //             amount = amount * 100 - 1; //金额（分）
            //             servicefee = servicefee * 100;

            //             string seviceAmount = servicefee.ToString("f0"); //服务费
            //             string amountAmount = amount.ToString("f0");

            //             string result = HaoDaHelper.Instance.OrderDivideAccounts(OrderDivideAccountsUtil.AddValue(applyNo, mchtNo, orderNo, acctNo, sacctNo, "0", amountAmount, seviceAmount));
            //         }
            //     }
            // }

            // List<string> list = new List<string>();
            // list.Add("{\"orderNo\":\"G2231124C02180937731\",\"settle\":\"29687\",\"part\":\"29575\"}");
            // foreach(string sub in list)
            // {
            //     JsonData jsonObj = JsonMapper.ToObject(sub);
            //     string orderNo = jsonObj["orderNo"].ToString();
            //     string settle = jsonObj["settle"].ToString();
            //     string part = jsonObj["part"].ToString();
            //     ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.SeoTitle == orderNo) ?? new ConsumerOrders();
            //     if(order.SettleAmount > 0)
            //     {
            //         MerchantParamSet set = Newtonsoft.Json.JsonConvert.DeserializeObject<MerchantParamSet>(order.SeoDescription);
            //         MerchantAddInfo merchantAdd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantAddInfo();
            //         string applyNo = "FZ" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8); //批次号
            //         string mchtNo = merchantAdd.OutMchtNo; //慧掌柜商户号
            //         string acctNo = AppConfig.Haoda.AcctNo; //账户号，分账接收方账户号
            //         string sacctNo = merchantAdd.MchtNo; //账户号，收款商户号

            //         decimal settleamount = decimal.Parse(settle);
            //         decimal partamount = decimal.Parse(part);
            //         decimal amount = settleamount - partamount;
            //         if(amount > 0)
            //         {
            //             decimal servicefee = amount / 100M;
            //             servicefee = decimal.Parse(servicefee.ToString("f0"));
            //             amount -= servicefee;
            //             string seviceAmount = servicefee.ToString("f0"); //服务费
            //             string amountAmount = amount.ToString("f0");

            //             string result = HaoDaHelper.Instance.OrderDivideAccounts(OrderDivideAccountsUtil.AddValue(applyNo, mchtNo, orderNo, acctNo, sacctNo, "0", amountAmount, seviceAmount));
            //         }
            //     }
            // }

            // db.Dispose();
        }

        /// <summary>
        /// 从ftp服务器上获得文件列表
        /// </summary>
        /// <param name="RequedstPath">服务器下的相对路径</param>
        /// <returns></returns>
        public static List<string> GetFTPListInfo(string RequedstPath = "/haoda-trade")
        {
            // 47.108.253.46
            // 用户名：hdftp
            // 密：haodatradeftp2024
            // 目录：/haoda-trade
            List<string> strs = new List<string>();
            try
            {
                string uri = "ftp://47.108.253.46" + RequedstPath;   //目标路径 path为服务器地址　　　　　　　　②
                FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(uri));
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential("hdftp", "haodatradeftp2024");
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名

                string line = reader.ReadLine();
                while (line != null)
                {
                    if (!line.Contains("<DIR>"))
                    {
                        string msg = line.Substring(0).Trim();
                        msg = msg.Substring(msg.Length - 24, 24);
                        strs.Add(msg);
                    }
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return strs;
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "获取好哒FTP文件数据异常");
            }
            return strs;
        }

        public static void GetFTPDataInfo()
        {
            // 47.108.253.46
            // 用户名：hdftp
            // 密：haodatradeftp2024
            // 目录：/haoda-trade

            // FTP服务器的地址
            string ftpServerAddress = "ftp://47.108.253.46";
            // FTP登录凭证
            string ftpUser = "hdftp";
            string ftpPassword = "haodatradeftp2024";
            // 要下载的文件路径
            string filePath = "/haoda-trade/20240513.csv";

            try
            {
                // 创建FtpWebRequest对象
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServerAddress + filePath);
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential(ftpUser, ftpPassword);

                // 使用WebResponse获取响应
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                // 打开数据流
                Stream responseStream = response.GetResponseStream();
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    WebCMSEntities db = new WebCMSEntities();
                    // 读取数据
                    string fileContents = reader.ReadToEnd();
                    if (!string.IsNullOrEmpty(fileContents))
                    {
                        var DataInfo = fileContents.TrimEnd('\n').Split('\n', 2);
                        var DataList = DataInfo[1].Split('\n');
                        foreach (var DataListItem in DataList)
                        {
                            var DataListInfo = DataListItem.Split(',');

                            var MerchantNo = ""; // 商户号
                            var BaseNo = ""; // 设备号
                            var OrderNo = ""; // 订单号
                            var PayWay = ""; // 支付方式(微信 支付宝)
                            var TradeType = ""; // 交易类型
                            var TradeAmount = ""; // 交易金额
                            var TradeFee = ""; // 交易手续费
                            var TradeDate = ""; // 交易时间
                            var TradeCycle = ""; // 结算周期

                            MerchantNo = DataListInfo[0];
                            BaseNo = DataListInfo[1];
                            OrderNo = DataListInfo[2];
                            PayWay = DataListInfo[3];
                            TradeType = DataListInfo[4];
                            TradeAmount = DataListInfo[5];
                            TradeFee = DataListInfo[6];
                            TradeDate = DataListInfo[7];
                            TradeCycle = DataListInfo[8];

                            TradeDate = TradeDate.Substring(0, 4) + "-" + TradeDate.Substring(4, 2) + "-" + TradeDate.Substring(6, 2) + " " + TradeDate.Substring(8, 2) + ":" + TradeDate.Substring(10, 2) + ":" + TradeDate.Substring(12, 2);

                            var PayMode = 0;
                            if (PayWay.Contains("支付宝")) PayMode = 1;
                            if (PayWay.Contains("微信")) PayMode = 2;

                            var merchantAddInfo = db.MerchantAddInfo.FirstOrDefault(m => m.MchtNo == MerchantNo) ?? new MerchantAddInfo();
                            if (merchantAddInfo.Id > 0)
                            {
                                var merchantInfo = db.MerchantInfo.FirstOrDefault(m => m.Id == merchantAddInfo.Id) ?? new MerchantInfo();
                                var orders = db.ConsumerOrders.FirstOrDefault(m => m.SeoTitle == OrderNo && OrderNo == OrderNo) ?? new ConsumerOrders();
                                if (orders.Id == 0)
                                {
                                    var query = db.ConsumerOrders.Add(new ConsumerOrders()
                                    {
                                        Status = 1,
                                        CreateDate = DateTime.Parse(TradeDate),
                                        UpdateDate = DateTime.Parse(TradeDate),
                                        SnNo = BaseNo,
                                        PayMoney = decimal.Parse(TradeAmount),
                                        PayMode = PayMode,
                                        SeoTitle = OrderNo,
                                        OrderNo = OrderNo,
                                        MerchantId = merchantAddInfo.Id,
                                        UserId = merchantInfo.UserId
                                    }).Entity;
                                }
                            }
                        }
                        db.SaveChanges();
                        db.Dispose();
                    }

                    // 关闭响应
                    response.Close();
                }

                // 关闭响应
                response.Close();
            }
            catch (WebException ex)
            {
                // 如果抛出WebException，则可能是文件不存在
                // 根据响应状态码判断是否文件不存在
                if (((FtpWebResponse)ex.Response).StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                {
                    function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString() + "文件" + filePath + "不存在", "获取好哒FTP文件数据异常"); // 文件不存在，返回false
                }
                else
                {
                    // 其他错误
                    function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "获取好哒FTP文件数据异常");
                }
            }
        }

        public void StartProfitShareListen()
        {
            bool op = true;
            while (op)
            {
                try
                {
                    WebCMSEntities db = new WebCMSEntities();
                    var list = db.ConsumerOrders.Where(m => m.Status == 1 && m.IsAct == 0).OrderByDescending(m => m.Id).ToList();
                    foreach (var sub in list)
                    {
                        ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == sub.Id);
                        if (order != null)
                        {
                            int Status = 2;
                            MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantInfo();
                            MerchantParamSet set = db.MerchantParamSet.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantParamSet();

                            MerchantAddInfo merchantAdd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantAddInfo();
                            //发起分账
                            string applyNo = "FZ" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8); //批次号
                            string mchtNo = merchantAdd.OutMchtNo; //慧掌柜商户号
                            string orderNo = order.SeoTitle; //交易订单号（好哒平台订单号，G开头）
                            string acctNo = AppConfig.Haoda.AcctNo; //账户号，分账接收方账户号
                            string sacctNo = merchantAdd.MchtNo; //账户号，收款商户号
                            string acctType = "0"; //账户类型（0：商户收款账户（大B），1：分账接收方账户（小B））
                            decimal amount = order.PayMoney * (1M - 0.0038M) * 100;
                            string result = HaoDaHelper.Instance.OrderDivideAccounts(OrderDivideAccountsUtil.AddValue(applyNo, mchtNo, orderNo, acctNo, sacctNo, acctType, amount.ToString().Split('.')[0], "0"));
                            if (result.Contains("\"resultCode\":\"0\"") && result.Contains("分账金额不足"))
                            {
                                Status = 1;
                            }
                            order.Status = Status;
                        }
                    }
                    db.SaveChanges();
                    db.Dispose();
                }
                catch (Exception ex)
                {
                    LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "好哒分账队列异常");
                }
                Thread.Sleep(2000);
            }
        }

        //新建商户查询状态
        public void QueryMerchantStatus(int MerchantId)
        {
            WebCMSEntities db = new WebCMSEntities();
            MerchantAddInfo AddInfo = db.MerchantAddInfo.FirstOrDefault(m => m.Id == MerchantId);

            var BrhCode = HaodaUnionParam.BrhCode;
            if (AddInfo.BrandId == 1) BrhCode = HaodaParam.BrhCode;
            var returnInfo = HaoDaHelper.Instance.QueryMerchantStatus(BrhCode, AddInfo.MchtNo);
            // string result = HaoDaHelper.Instance.AddNewMerchant(AddNewMerchantSetUtil.SetValue(AddInfo));
            db.Dispose();
        }

        //提交支付宝开户意愿申请单
        public void AlipayAddInfo(int Id)
        {
            try
            {
                WebCMSEntities db = new WebCMSEntities();
                MerchantAddInfo info = db.MerchantAddInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantAddInfo();
                string result = AlipayFunctionForHD.Instance.AuthOrderCreate(info, info.AlipayAuthToken);
                JsonData jsonObj = JsonMapper.ToObject(result);

                Dictionary<string, object> reqdic = new Dictionary<string, object>();
                reqdic.Add("Id", Id); // 商户Id
                string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
                LogHelper.Instance.WriteLog(req, "提交支付宝商户意愿申请单");
                Dictionary<string, string> headdic = HaoDaHelper.Instance.GetHeader(req);
                string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
                LogHelper.Instance.WriteLog("请求参数\n" + req, "提交支付宝商户意愿申请单");

                LogHelper.Instance.WriteLog(result, "提交支付宝商户意愿申请单");
                if (jsonObj["alipay_merchant_indirect_authorder_create_response"]["code"].ToString() == "10000")
                {
                    LogHelper.Instance.WriteLog("success", "提交支付宝商户意愿申请单");
                    string order_no = jsonObj["alipay_merchant_indirect_authorder_create_response"]["order_no"].ToString();
                    // RedisDbconn.Instance.AddList("AlipayResultForHaoDaQueue", "{\"MerchantId\":\"" + Id + "\",\"order_no\":\"" + order_no + "\"}");
                    LogHelper.Instance.WriteLog("end", "提交支付宝商户意愿申请单");
                }
                else
                {
                    LogHelper.Instance.WriteLog("false", "提交支付宝商户意愿申请单");
                    MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                    info.QueryCount = -1;
                    merchant.QueryCount = -1;
                    info.AlipayRemark = jsonObj["alipay_merchant_indirect_authorder_create_response"]["msg"].ToString();
                    LogHelper.Instance.WriteLog("end", "提交支付宝商户意愿申请单");
                    db.SaveChanges();

                }
                db.Dispose();
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "支付宝开户意愿申请异常");
            }
        }
        //查询支付宝开户意愿申请状态
        public void AlipayAddInfo(int Id, string OrderNo)
        {
            try
            {
                LogHelper.Instance.WriteLog("start", "查询支付宝商户意愿申请状态");
                WebCMSEntities db = new WebCMSEntities();
                MerchantAddInfo info = db.MerchantAddInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantAddInfo();
                string result = AlipayFunctionForHD.Instance.AuthOrderQuery(OrderNo);
                JsonData jsonObj = JsonMapper.ToObject(result);

                Dictionary<string, object> reqdic = new Dictionary<string, object>();
                reqdic.Add("Id", Id); // 商户Id
                reqdic.Add("OrderNo", OrderNo); // 商户Id
                string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
                LogHelper.Instance.WriteLog(req, "查询支付宝商户意愿申请状态");
                Dictionary<string, string> headdic = HaoDaHelper.Instance.GetHeader(req);
                string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
                LogHelper.Instance.WriteLog("请求参数\n" + req, "查询支付宝商户意愿申请状态");

                LogHelper.Instance.WriteLog(result, "查询支付宝商户意愿申请状态");
                if (jsonObj["alipay_merchant_indirect_authorder_querystatus_response"]["code"].ToString() == "10000")
                {
                    LogHelper.Instance.WriteLog("start1", "查询支付宝商户意愿申请状态");
                    string order_status = jsonObj["alipay_merchant_indirect_authorder_querystatus_response"]["order_status"].ToString();
                    if (order_status == "CONTACT_CONFIRM")
                    {
                        LogHelper.Instance.WriteLog("start1", "查询支付宝商户意愿申请状态");
                        MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                        info.QueryCount = 1;
                        merchant.QueryCount = 1;
                        info.AlipayRemark = "";
                        info.AlipaySignUrl = jsonObj["alipay_merchant_indirect_authorder_querystatus_response"]["qr_code"].ToString();
                        db.SaveChanges();
                        // RedisDbconn.Instance.AddList("HaoDaAuthQueryHelper", "{\"MerchantId\":\"" + Id + "\",\"MchtNo\":\"" + info.MchtNo + "\",\"StoreNo\":\"" + info.StoreNo + "\"}");
                        LogHelper.Instance.WriteLog("start1end", "查询支付宝商户意愿申请状态");
                    }
                    else if (order_status == "AUDIT_REJECT" || order_status == "AUDIT_FREEZE")
                    {
                        LogHelper.Instance.WriteLog("start2", "查询支付宝商户意愿申请状态");
                        MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                        info.QueryCount = -1;
                        merchant.QueryCount = -1;
                        info.AlipayRemark = jsonObj["alipay_merchant_indirect_authorder_querystatus_response"]["msg"].ToString();
                        LogHelper.Instance.WriteLog("start2end", "查询支付宝商户意愿申请状态");
                        db.SaveChanges();
                    }
                    else if (order_status == "AUDIT_PASS")
                    {
                        LogHelper.Instance.WriteLog("start2", "查询支付宝商户意愿申请状态");
                        MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                        info.QueryCount = 2;
                        merchant.QueryCount = 2;
                        info.AlipayRemark = "";
                        LogHelper.Instance.WriteLog("start2end", "查询支付宝商户意愿申请状态");
                        if (merchant.Latitude == 0)
                        {
                            //签约成功调用腾讯地图接口获取地址
                            RedisDbconn.Instance.AddList("GetTencentAddressInfoQueueHd", "{\"MerChantId\":\"" + merchant.Id + "\",\"Address\":\"" + merchant.Areas + merchant.Address + "\"}");
                        }
                        db.SaveChanges();
                    }
                    // else
                    // {
                    //     RedisDbconn.Instance.AddList("AlipayResultForHaoDaQueue", "{\"MerchantId\":\"" + Id + "\",\"order_no\":\"" + OrderNo + "\"}");
                    // }
                }
                else
                {
                    MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                    info.QueryCount = -1;
                    merchant.QueryCount = -1;
                    info.AlipayRemark = jsonObj["alipay_merchant_indirect_authorder_querystatus_response"]["msg"].ToString();
                    db.SaveChanges();
                }
                db.Dispose();
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "支付宝开户意愿申请异常");
            }
        }

        //提交微信开户意愿申请单
        public void WeChatAddInfo(int Id)
        {
            try
            {
                WebCMSEntities db = new WebCMSEntities();
                MerchantAddInfo info = db.MerchantAddInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantAddInfo();
                string result = WeChatFunctionForHD.Instance.MerchantApply(info);

                Dictionary<string, object> reqdic = new Dictionary<string, object>();
                reqdic.Add("Id", Id); // 商户Id
                string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
                LogHelper.Instance.WriteLog(req, "提交微信商户意愿申请单");
                Dictionary<string, string> headdic = HaoDaHelper.Instance.GetHeader(req);
                string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
                LogHelper.Instance.WriteLog("请求参数\n" + req, "提交微信商户意愿申请单");

                LogHelper.Instance.WriteLog(result, "提交微信商户意愿申请单");
                if (result.Contains("\"applyment_id\":"))
                {
                    LogHelper.Instance.WriteLog("success", "提交微信商户意愿申请单");
                    JsonData json = JsonMapper.ToObject(result);
                    string applyment_id = json["applyment_id"].ToString();
                    // RedisDbconn.Instance.AddList("WeChatResultForHaoDaQueue", "{\"MerchantId\":\"" + Id + "\",\"ApplymentId\":\"" + applyment_id + "\"}");
                    LogHelper.Instance.WriteLog("end", "提交微信商户意愿申请单");
                }
                else if (result.Contains("\"message\":"))
                {
                    LogHelper.Instance.WriteLog("false", "提交微信商户意愿申请单");
                    MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                    JsonData jsonObj = JsonMapper.ToObject(result);
                    info.Status = -1;
                    merchant.Status = -1;
                    info.WeChatRemark = jsonObj["message"].ToString();
                    LogHelper.Instance.WriteLog("end", "提交微信商户意愿申请单");
                    db.SaveChanges();
                }
                db.Dispose();
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "微信开户意愿申请异常");
            }
        }

        //查询微信开户意愿申请状态
        public void WeChatAddInfo(int Id, string ApplymentId)
        {
            try
            {
                WebCMSEntities db = new WebCMSEntities();
                MerchantAddInfo info = db.MerchantAddInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantAddInfo();
                string result = WeChatFunctionForHD.Instance.QueryMerchant(ApplymentId);

                Dictionary<string, object> reqdic = new Dictionary<string, object>();
                reqdic.Add("Id", Id); // 商户Id
                reqdic.Add("ApplymentId", ApplymentId); // 商户Id
                string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);
                LogHelper.Instance.WriteLog(req, "提交微信商户意愿申请单");
                Dictionary<string, string> headdic = HaoDaHelper.Instance.GetHeader(req);
                string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
                LogHelper.Instance.WriteLog("请求参数\n" + req, "提交微信商户意愿申请单");

                JsonData jsonObj = JsonMapper.ToObject(result);
                if (jsonObj["applyment_state"].ToString() == "APPLYMENT_STATE_WAITTING_FOR_CONFIRM_CONTACT")
                {
                    MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                    info.Status = 1;
                    merchant.Status = 1;
                    info.WeChatRemark = "";
                    info.WeChatSignUrl = jsonObj["qrcode_data"].ToString();
                    db.SaveChanges();
                    // RedisDbconn.Instance.AddList("HaoDaAuthQueryHelper", "{\"MerchantId\":\"" + Id + "\",\"MchtNo\":\"" + info.MchtNo + "\",\"StoreNo\":\"" + info.StoreNo + "\"}");
                }
                else if (jsonObj["applyment_state"].ToString() == "APPLYMENT_STATE_REJECTED")
                {
                    MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                    info.Status = -1;
                    merchant.Status = -1;
                    info.WeChatRemark = jsonObj["reject_reason"].ToString();
                    db.SaveChanges();
                }
                // else
                // {
                //     RedisDbconn.Instance.AddList("WeChatResultForHaoDaQueue", "{\"MerchantId\":\"" + Id + "\",\"ApplymentId\":\"" + ApplymentId + "\"}");
                // }
                db.Dispose();
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "微信开户意愿申请异常");
            }
        }

        //添加分账接收方账户
        public void AddOpenDivideAccounts(int MerchantId)
        {
            WebCMSEntities db = new WebCMSEntities();
            MerchantAddInfo AddInfo = db.MerchantAddInfo.FirstOrDefault(m => m.Id == MerchantId);
            string result = HaoDaHelper.Instance.AddOpenDivideAccounts(AddOpenDivideAccountsUtil.AddValue(AddInfo));
            db.Dispose();
        }

        public void ConfiemMer(int MerchantId)
        {
            WebCMSEntities db = new WebCMSEntities();
            Models.Main1.WebCMSEntities db1 = new Models.Main1.WebCMSEntities();
            MerchantAddInfo AddInfo = db.MerchantAddInfo.FirstOrDefault(m => m.Id == MerchantId);
            MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId);
            if (AddInfo != null && merchant != null)
            {
                string BusinessCode = AddInfo.BusinessCode;
                if (string.IsNullOrEmpty(BusinessCode))
                {
                    BusinessCode = "LKB" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(5);
                    AddInfo.BusinessCode = BusinessCode;
                }
                string pwd = AddInfo.MobilePhone.Substring(5);
                merchant.LoginPwd = function.MD532(pwd);
                MerchantParamSet query = db.MerchantParamSet.FirstOrDefault(m => m.Id == MerchantId);
                if (query == null)
                {
                    query = new MerchantParamSet();
                    query.IsAll = 1;
                    db.MerchantParamSet.Add(query);
                    db.SaveChanges();
                }
                MerchantForMobile merchantForMobile = db.MerchantForMobile.FirstOrDefault(m => m.Mobile == AddInfo.MobilePhone);
                if (merchantForMobile == null)
                {
                    merchantForMobile = db.MerchantForMobile.Add(new MerchantForMobile()
                    {
                        Mobile = AddInfo.MobilePhone,
                    }).Entity;
                    db.SaveChanges();
                }
                merchantForMobile.MerchantId = MerchantId;
                db.SaveChanges();
                Models.Main1.MerchantLoginInfo info = db1.MerchantLoginInfo.FirstOrDefault(m => m.LoginMobile == AddInfo.MobilePhone);
                if (info == null)
                {
                    info = db1.MerchantLoginInfo.Add(new Models.Main1.MerchantLoginInfo()
                    {
                        LoginMobile = AddInfo.MobilePhone,
                    }).Entity;
                    db1.SaveChanges();
                }
                info.LoginPwd = function.MD532(pwd);
                db1.SaveChanges();
                Models.Main1.MerchantAccountLinkInfo infolink = db1.MerchantAccountLinkInfo.FirstOrDefault(m => m.LoginId == info.Id && m.MerchantId == MerchantId && m.Kind == 2);
                if (infolink == null)
                {
                    infolink = db1.MerchantAccountLinkInfo.Add(new Models.Main1.MerchantAccountLinkInfo()
                    {
                        LoginId = info.Id,
                        MerchantId = MerchantId,
                        Kind = 2,
                    }).Entity;
                    db1.SaveChanges();
                }
                if (AddInfo.Status <= 0)
                {
                    //好哒新建商户
                    string result = HaoDaHelper.Instance.AddNewMerchant(AddNewMerchantSetUtil.SetValue(AddInfo));
                    JsonData jsonObj = JsonMapper.ToObject(result);
                    //创建成功
                    if (jsonObj["resultCode"].ToString() == "1")
                    {
                        AddInfo.WeChatRemark = "";
                        if (string.IsNullOrEmpty(AddInfo.MchtNo))
                        {
                            AddInfo.MchtNo = jsonObj["data"]["mchtNo"].ToString();
                        }
                        AddInfo.Status = 0;
                        merchant.Status = 0;
                        db.SaveChanges();
                        QueryMerchantStatus queryMerchantStatus = new QueryMerchantStatus();
                        queryMerchantStatus.MerchantId = MerchantId.ToString();
                        queryMerchantStatus.MerchantNo = AddInfo.MchtNo;
                        // RedisDbconn.Instance.AddList("WeChatSignHdQueue", queryMerchantStatus);
                    }
                    //创建失败
                    else
                    {
                        AddInfo.Status = -1;
                        merchant.Status = -1;
                        AddInfo.WeChatRemark = jsonObj["errorDesc"].ToString();
                        // if (string.IsNullOrEmpty(AddInfo.MchtNo))
                        // {
                        //     if (jsonObj.ToJson().Contains("mchtNo"))
                        //     {
                        //         AddInfo.MchtNo = jsonObj["data"]["mchtNo"].ToString();
                        //     }
                        // }
                        db.SaveChanges();
                    }
                }
            }
            db.Dispose();
            db1.Dispose();
        }

        //商户开通分账
        public void OpenDivideAccounts(int MerchantId)
        {
            WebCMSEntities db = new WebCMSEntities();
            MerchantAddInfo AddInfo = db.MerchantAddInfo.FirstOrDefault(m => m.Id == MerchantId);
            string result = HaoDaHelper.Instance.OpenDivideAccounts(AddInfo.OutMchtNo, AddInfo.StoreNo);
            db.Dispose();
        }

        //分账接收方签约
        public void DivideAccountsSign(int MerchantId)
        {
            WebCMSEntities db = new WebCMSEntities();
            MerchantAddInfo AddInfo = db.MerchantAddInfo.FirstOrDefault(m => m.Id == MerchantId);
            string result = HaoDaHelper.Instance.DivideAccountsSign("230817000000000278", AddInfo.OutMchtNo, AddInfo.StoreNo);
            db.Dispose();
        }

        //查询实名认证状态
        public void QueryAuthStatus(int MerchantId)
        {
            WebCMSEntities db = new WebCMSEntities();
            MerchantAddInfo AddInfo = db.MerchantAddInfo.FirstOrDefault(m => m.Id == MerchantId);
            string result = HaoDaHelper.Instance.QueryAuthStatus(AddInfo.OutMchtNo, AddInfo.StoreNo);
            db.Dispose();
        }

        //商户修改银行卡
        public void ChangeMerchantCard(int MerchantId)
        {
            WebCMSEntities db = new WebCMSEntities();
            MerchantAddInfo AddInfo = db.MerchantAddInfo.FirstOrDefault(m => m.Id == MerchantId);
            var request = TestChangeMerchantCardSetUtil.SetValue(AddInfo);
            JsonData Infos = JsonMapper.ToObject(HaoDaHelper.Instance.ChangeMerchantCard(request));
            JsonData results = JsonMapper.ToObject(HaoDaHelper.Instance.QueryChangeCardStatus(AddInfo.MchtNo, Infos["data"]["taskId"].ToString()));
            //TODO:修改结算卡变更商户相关信息
            // AccountNumber
            // BankName
            // BankBranchId
            // BankAddressCode
            // BankAccountType
            // OpenUnionNo
            // OpenCollectBankCode
            // OpenBankRegionCode
            // OpenBankAccout
            // OpenBankAccName
            // ZbankRegionCode
            // ZBankNo
            db.Dispose();
        }


        //获取商户经纬坐标
        public void GetTencentAddressInfo(int Id)
        {
            WebCMSEntities db = new WebCMSEntities();
            MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == Id);
            string Address = merchant.Areas + merchant.Address;
            string Key = Library.ConfigurationManager.AppSettings["TencentKey"].ToString();
            LogHelper.Instance.WriteLog("商户Id\n" + Id + "\n\n", "获取商户经纬坐标");
            LogHelper.Instance.WriteLog("请求参数\n" + Address + "\n\n", "获取商户经纬坐标");
            var info = function.GetWebRequest("https://apis.map.qq.com/ws/geocoder/v1/?address=" + Address + "&key=" + Key);
            JsonData result = JsonMapper.ToObject(info);
            //创建成功
            if (result["status"].ToString() == "0")
            {
                var merInfo = db.MerchantInfo.FirstOrDefault(m => m.Id == Id) ?? new MerchantInfo();
                if (merInfo.Id > 0)
                {
                    merInfo.Longitude = decimal.Parse(result["result"]["location"]["lng"].ToString());
                    merInfo.Latitude = decimal.Parse(result["result"]["location"]["lat"].ToString());
                    db.SaveChanges();
                    db.Dispose();
                }
            }
            LogHelper.Instance.WriteLog("返回\n" + info + "\n\n", "获取商户经纬坐标");
            db.Dispose();
        }

        public void QueryChangeCardStatus(int MerchantId)
        {
            WebCMSEntities db = new WebCMSEntities();
            MerchantAddInfo AddInfo = db.MerchantAddInfo.FirstOrDefault(m => m.Id == MerchantId);
            // JsonData results = JsonMapper.ToObject(HaoDaHelper.Instance.QueryChangeCardStatus(AddInfo.MchtNo, Infos["data"]["taskId"].ToString()));
            JsonData results = JsonMapper.ToObject(HaoDaHelper.Instance.QueryChangeCardStatus(AddInfo.MchtNo, "16592654"));
        }
        public void refund()
        {
            Thread th = new Thread(refunddo);
            th.IsBackground = true;
            th.Start();
        }
        public void refunddo()
        {
            for (int month = 10; month <= 11; month++)
            {
                for (int day = 1; day <= 31; day++)
                {
                    string content = function.ReadInstance("/log/好哒聚合支付退款/2023/" + month + "/" + day + "/content.log");
                    if (!string.IsNullOrEmpty(content))
                    {
                        content = content.Replace("\n\n\n", "####");
                        content = content.Replace("\n", "");
                        content = content.Replace("####", "\n");
                        MatchCollection mc = Regex.Matches(content, "请求参数.*?退款次数超出限制");
                        foreach (Match m in mc)
                        {
                            string mchtNo = Regex.Match(m.Value, "\"mchtNo\":\".*?\"").Value.Replace("\"mchtNo\":\"", "").Replace("\"", "");
                            string storeNo = Regex.Match(m.Value, "\"storeNo\":\".*?\"").Value.Replace("\"storeNo\":\"", "").Replace("\"", "");
                            string outOrderNo = Regex.Match(m.Value, "\"outOrderNo\":\".*?\"").Value.Replace("\"outOrderNo\":\"", "").Replace("\"", "");
                            string refundAmount = Regex.Match(m.Value, "\"refundAmount\":\".*?\"").Value.Replace("\"refundAmount\":\"", "").Replace("\"", "");
                            function.WriteLog("mchtNo:" + mchtNo + ";storeNo:" + storeNo + ";outOrderNo:" + outOrderNo + ";refundAmount:" + refundAmount + ";", "补充退款日志");
                            var info = HaoDaHelper.Instance.AggregatedPayRefund(mchtNo, storeNo, "HDTK" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8), outOrderNo, refundAmount);
                            function.WriteLog(info + "\n\n", "补充退款日志");
                            Thread.Sleep(1000);
                        }
                    }
                }
            }
        }

    }
}