using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Threading;
using Library;
using System.Net;
using System.IO;
using MySystem.SpModels;

namespace MySystem
{
    /// <summary>
    /// 获取好哒ftp数据
    /// </summary>
    public class GetHaoDaFTPInfoService
    {
        public readonly static GetHaoDaFTPInfoService Instance = new GetHaoDaFTPInfoService();
        private GetHaoDaFTPInfoService()
        { }

        // 47.108.253.46
        // 用户名：hdftp
        // 密：haodatradeftp2024
        // 目录：/haoda-trade

        public string ftpServerAddress = "ftp://47.108.253.46";
        public string ftpUser = "hdftp";
        public string ftpPassword = "haodatradeftp2024";


        public void Start()
        {
            //每天凌晨执行获取好哒FTP昨日交易数据
            Thread th2 = new Thread(GetDepositDataReady);
            th2.IsBackground = true;
            th2.Start();
        }


        /// <summary>
        /// 获取好哒FTP昨日交易数据
        /// </summary>
        public void GetDepositDataReady()
        {
            while (true)
            {
                if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 10:02:00") && DateTime.Now.Hour < 22)
                {
                    string check = function.ReadInstance("/GetFTPDepositYesterday/check" + DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") + ".txt");
                    if (string.IsNullOrEmpty(check))
                    {
                        function.WritePage("/GetFTPDepositYesterday/", "check" + DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") + ".txt", DateTime.Now.ToString());
                        function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "----start", "监控头一天数据");
                        SaveDepositData(DateTime.Now.AddDays(-1).ToString("yyyyMMdd"), true);
                        function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "----end\n\n\n\n", "监控头一天数据");
                        Thread.Sleep(2000);
                        // GetDepositData();
                        // Thread.Sleep(60000);
                        SaveTradeData(DateTime.Now.AddDays(-1).ToString("yyyyMMdd"), true);
                    }
                }
                Thread.Sleep(900000);
            }
        }

        public void Start2()
        {
            //每天凌晨执行获取好哒FTP昨日交易数据
            Thread th2 = new Thread(GetDepositDataReady2);
            th2.IsBackground = true;
            th2.Start();
        }

        /// <summary>
        /// 获取好哒FTP昨日交易数据
        /// </summary>
        public void GetDepositDataReady2()
        {
            while (true)
            {
                if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 10:20:00"))
                {
                    SaveDepositData("d_" + DateTime.Now.ToString("yyyyMMdd"));
                    Thread.Sleep(2000);
                    GetDepositData();
                }
                SaveTradeData(DateTime.Now.ToString("yyyyMMdd"));
                Thread.Sleep(180000);
            }
        }

        public void StartListen()
        {
            //每天凌晨执行获取好哒FTP昨日交易数据
            Thread th2 = new Thread(start: ListenDepositDataReady);
            th2.IsBackground = true;
            th2.Start();
        }
        /// <summary>
        /// 获取好哒FTP昨日交易数据
        /// </summary>
        public void ListenDepositDataReady()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("ListenDepositDataQueue2");
                if (!string.IsNullOrEmpty(content))
                {
                    SaveDepositData(content);
                    Thread.Sleep(2000);
                    GetDepositData();
                    Thread.Sleep(2000);
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
        }

        public void SaveDepositData(string Date, bool IsRedis = false)
        {
            // 要下载的文件路径
            string filePath = "/haoda-deposit/deposit_" + Date + ".csv";
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "----" + filePath, "监控头一天数据");

            try
            {
                function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "----ok", "监控头一天数据");
                // 创建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();
                StreamReader reader = new StreamReader(responseStream);
                // 读取数据
                string fileContents = reader.ReadToEnd();
                function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "----ready", "监控头一天数据");
                if (!string.IsNullOrEmpty(fileContents))
                {
                    function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "----have content", "监控头一天数据");
                    MpMainModels2.WebCMSEntities db = new MpMainModels2.WebCMSEntities();
                    List<string> SnNos = db.HdDepositTmp.Select(m => m.SnNo).ToList();
                    List<string> ChkSnNos = new List<string>();
                    var DataInfo = fileContents.TrimEnd('\n').Split('\n', 2);
                    function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "----count:" + DataInfo.Length, "监控头一天数据");
                    if (DataInfo.Length > 1)
                    {
                        function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "----have record", "监控头一天数据");
                        int index = 0;
                        var DataList = DataInfo[1].Split('\n');
                        function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "----record count:" + DataList.Length, "监控头一天数据");
                        foreach (var DataListItem in DataList)
                        {
                            if(IsRedis)
                            {
                                var DataListInfo = DataListItem.Split(',');
                                string ActDate = DataListInfo[3]; //激活时间
                                if(ActDate == DateTime.Now.AddDays(-1).ToString("yyyyMMdd"))
                                {
                                    function.WriteLog(DataListItem, "监控头一天数据");
                                }
                                RedisDbconn.Instance.AddList("ListenDepositDataByOneQueue", DataListItem);
                            }
                            else
                            {
                                SaveDepositDataOneReady(db, DataListItem);
                                index += 1;
                                if(index % 200 == 0 && index > 0)
                                {
                                    index = 0;
                                    db.SaveChanges();
                                }
                            }
                        }
                        if(!IsRedis)
                        {
                            index = 0;
                            db.SaveChanges();
                        }
                        function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "----read data end", "监控头一天数据");
                    }
                    db.Dispose();
                }

                // 关闭响应
                reader.Dispose();
                responseStream.Dispose();
                response.Close();
            }
            catch (WebException ex)
            {
                function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "----err", "监控头一天数据");
                function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "获取好哒FTP押金数据异常");
            }
        }

        public void GetDepositData()
        {
            try
            {
                WebCMSEntities db = new WebCMSEntities();
                MpMainModels2.WebCMSEntities mpdb2 = new MpMainModels2.WebCMSEntities();
                JavaProductModels.WebCMSEntities javauserdb = new JavaProductModels.WebCMSEntities();
                List<MpMainModels2.HdDepositTmp> deposits = mpdb2.HdDepositTmp.Where(m => m.Status == 0).ToList();
                if (deposits.Count > 0)
                {
                    foreach (var deposit in deposits)
                    {
                        string SnNo = deposit.SnNo; //sn
                        string MerNo = deposit.MerNo; //商户编号
                        string PosKind = deposit.DeviceKind; //机具型号
                        string ActDate = deposit.ActDate; //激活时间
                        string Deposit = deposit.DepositAmount.ToString(); //押金金额
                        string PrizeAmt = deposit.PrizeAmount.ToString(); //奖励金额
                        string PrizeDate = deposit.PrizeDate; //奖励发放时间
                        string Name = deposit.SendMan; //发放人姓名
                        string MerName = deposit.MerName; //商户名称
                        string PassDate = deposit.PassDate; //审核通过时期
                        string MerKind = deposit.MerKind; //商户类型
                        string DepositActCode = deposit.DepositActCode; //商户类型
                        string PrizeKind = deposit.PrizeKind; //奖励类型

                        string ProductType = "0";
                        if (PosKind == "好哒语音王Y512") ProductType = "18";
                        if (PosKind == "4G收款王M820") ProductType = "19";
                        if (PosKind == "4G收款王M826") ProductType = "20";
                        if (PosKind == "好哒S312" || PosKind == "S305") ProductType = "21";
                        if (PosKind == "好哒扫码通M837") ProductType = "29";
                        if (PosKind == "好哒语音王Y518") ProductType = "36";

                        if (!db.ActivateRecord.Any(m => m.SnNo == SnNo && m.MerNo == MerNo))
                        {
                            MpMainModels2.MerchantAddInfo meradd = mpdb2.MerchantAddInfo.FirstOrDefault(m => m.MchtNo == MerNo) ?? new MpMainModels2.MerchantAddInfo();
                            MpMainModels2.MerchantInfo merchant = mpdb2.MerchantInfo.FirstOrDefault(m => m.Id == meradd.Id) ?? new MpMainModels2.MerchantInfo();

                            if (!string.IsNullOrEmpty(meradd.CertMerchantName)) MerName = meradd.CertMerchantName;

                            string ActDateString = ActDate.Substring(0, 4) + "-" + ActDate.Substring(4, 2) + "-" + ActDate.Substring(6, 2);

                            BindRecord mer = db.BindRecord.Add(new BindRecord()
                            {
                                CreateDate = DateTime.Now,
                                UpdateTime = DateTime.Now, //机具绑定、解绑时间
                                CreateTime = DateTime.Now, //商户操作时间
                                MerSnNo = SnNo, //序列号
                                MerNo = MerNo, //商户编号
                                MerName = MerName,
                                SeoTitle = PrizeAmt,
                                SeoKeyword = ActDateString,
                                ProductType = ProductType,
                                Field1 = Deposit,
                                Field2 = PrizeDate,
                                Field3 = Name,
                                Field4 = PassDate,
                                Field5 = MerKind,
                                Status = 1,
                                QueryCount = merchant.UserId,
                            }).Entity;

                            db.Merchants.Add(new Merchants()
                            {
                                SnNo = SnNo,
                                CreateTime = DateTime.Now,
                                UpdateTime = DateTime.Now,
                                AgentName = Name,
                                MerRealName = Name,
                                MerNo = MerNo,
                                MerName = MerName,
                                ProductType = ProductType,
                                Status = 1,
                                QueryCount = merchant.UserId,
                            });
                            db.SaveChanges();

                            Thread.Sleep(1000);

                            ActivateRecord act = db.ActivateRecord.Add(new ActivateRecord()
                            {
                                SnNo = SnNo,
                                CreateDate = DateTime.Now,
                                SeoTitle = Deposit,
                                ActivateDate = DateTime.Now,
                                AgentNo = MerNo,
                                MerRealName = Name,
                                MerNo = MerNo,
                                MerName = MerName,
                                ProductType = ProductType,
                                ChannelSerial = DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8),
                                Status = 1,
                                Field1 = PassDate,
                                Field2 = MerKind,
                                Field3 = PrizeAmt,
                                Field4 = DepositActCode,
                                Field5 = ActDateString,
                                QueryCount = merchant.UserId,
                            }).Entity;
                            db.SaveChanges();

                            //推送MQ给创业帮
                            var merchantAddInfo = mpdb2.MerchantAddInfo.FirstOrDefault(m => m.MchtNo == MerNo) ?? new MpMainModels2.MerchantAddInfo();
                            if (merchantAddInfo.BrandId == 1 && !string.IsNullOrEmpty(merchantAddInfo.CybMakerCode))
                            {
                                SortedList<string, string> obj = new SortedList<string, string>();
                                obj.Add("create_time", ActDateString);
                                obj.Add("sn", SnNo);
                                obj.Add("deposit", Deposit);
                                obj.Add("subject_type", merchantAddInfo.SubjectType);
                                obj.Add("merch_no", merchantAddInfo.MchtNo);
                                obj.Add("maker_code", merchantAddInfo.CybMakerCode);
                                PushHelper.Instance.Do(obj, "cashNotify");

                                // PosPushDataNewHelper.Bind(mer, PosKind);
                                // PosPushDataNewHelper.Deposit(act);
                            }
                        }
                        else if (PosKind == "好哒语音王Y518")
                        {
                            ActivateRecord act = db.ActivateRecord.Add(new ActivateRecord()
                            {
                                SnNo = SnNo,
                                CreateDate = DateTime.Now,
                                SeoTitle = Deposit,
                                ActivateDate = DateTime.Now,
                                AgentNo = MerNo,
                                MerRealName = Name,
                                MerNo = MerNo,
                                MerName = Name,
                                ProductType = ProductType,
                                ChannelSerial = DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8),
                                Status = 1,
                                Field1 = PassDate,
                                Field2 = MerKind,
                                Field3 = PrizeAmt,
                                Field4 = DepositActCode,
                            }).Entity;
                            db.SaveChanges();
                        }

                        if ((PrizeKind == "830_21" || PrizeKind == "830_22" || PrizeKind == "833_01" || PrizeKind == "833_02" || PrizeKind == "995_21" || PrizeKind == "995_22" || PrizeKind == "995") && !string.IsNullOrEmpty(PrizeAmt) && decimal.Parse(function.CheckInt(PrizeAmt)) > 0)
                        {
                            JavaProductModels.KxsMachine pos = javauserdb.KxsMachine.FirstOrDefault(m => m.PosSn == SnNo && m.UserId > 0);
                            if(pos != null)
                            {
                                Dictionary<string, object> prizeData = new Dictionary<string, object>();
                                prizeData.Add("brand_id", 29);
                                prizeData.Add("ext_field", PrizeKind);
                                prizeData.Add("pos_sn", SnNo);
                                prizeData.Add("user_id", pos.UserId);
                                prizeData.Add("prize", PrizeAmt);
                                string req = Newtonsoft.Json.JsonConvert.SerializeObject(prizeData);
                                if(PrizeKind == "833_01" || PrizeKind == "833_02")
                                {
                                    string ids = PrizeKind == "833_01" ? "81" : "82";
                                    function.GetWebRequest("http://logic-executor-api.kexiaoshuang.com/noauth/prize/pushbyone?n=QUEUE_KXS_HAODA_PRIZE_CONFIG_DIVISION&m=" + req + "&ids=" + ids + ",83");
                                }
                                else
                                {
                                    RedisDbconn.Instance.AddList("HaoDaPrizeDataQueue", req);
                                }
                            }
                        }

                        MpMainModels2.HdDepositTmp edit = mpdb2.HdDepositTmp.FirstOrDefault(m => m.SnNo == SnNo);
                        if (edit != null)
                        {
                            edit.Status = 1;
                            mpdb2.SaveChanges();
                        }
                    }
                }
                db.Dispose();
                mpdb2.Dispose();
                javauserdb.Dispose();
            }
            catch (WebException ex)
            {
                function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "获取好哒FTP文件数据异常");
            }
        }









        public void StartTrade()
        {
            //每天凌晨执行获取好哒FTP昨日交易数据
            Thread th2 = new Thread(GetTradeDataReady);
            th2.IsBackground = true;
            th2.Start();
        }
        /// <summary>
        /// 获取好哒FTP昨日交易数据
        /// </summary>
        public void GetTradeDataReady()
        {
            while (true)
            {
                if (DateTime.Now.Hour > 10 && DateTime.Now.Hour < 22)
                {
                    string check = function.ReadInstance("/GetFTPTradeYesterday/check" + DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") + ".txt");
                    if (string.IsNullOrEmpty(check))
                    {
                        function.WritePage("/GetFTPTradeYesterday/", "check" + DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") + ".txt", DateTime.Now.ToString());
                        SaveTradeData(DateTime.Now.AddDays(-1).ToString("yyyyMMdd"));
                        Thread.Sleep(600000);
                    }
                }
                else
                {
                    Thread.Sleep(1800000);
                }
            }
        }
        public void StartTradeListen()
        {
            //每天凌晨执行获取好哒FTP昨日交易数据
            Thread th2 = new Thread(ListenTradeDataReady);
            th2.IsBackground = true;
            th2.Start();
        }
        /// <summary>
        /// 获取好哒FTP昨日交易数据
        /// </summary>
        public void ListenTradeDataReady()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("ListenTradeDataQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    SaveTradeData(content, true);
                    Thread.Sleep(2000);
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
        }
        public void SaveTradeData(string Date, bool IsRedis = false)
        {
            // 要下载的文件路径
            string filePath = "/haoda-trade/" + Date + ".csv";
            function.WriteLog(DateTime.Now.ToString() + ":" + Date + ":" + filePath, "好哒交易数据入库2");

            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();
                StreamReader reader = new StreamReader(responseStream);
                // 读取数据
                string fileContents = reader.ReadToEnd();
                if (!string.IsNullOrEmpty(fileContents))
                {
                    MpMainModels2.WebCMSEntities db = new MpMainModels2.WebCMSEntities();
                    var DataInfo = fileContents.TrimEnd('\n').Split('\n', 2);
                    if (DataInfo.Length > 1)
                    {
                        var DataList = DataInfo[1].Split('\n');
                        function.WriteLog("数量:" + Date + ":" + DataList.Length, "好哒交易数据入库2");
                        int index = 0;
                        foreach (var DataListItem in DataList)
                        {
                            if(IsRedis)
                            {
                                RedisDbconn.Instance.AddList("ListenTradeDataByOneQueue", DataListItem);
                            }
                            else
                            {
                                if(SaveTradeDataOneReady(db, DataListItem))
                                {
                                    index += 1;
                                }
                                if(index % 200 == 0 && index > 0)
                                {
                                    index = 0;
                                    db.SaveChanges();
                                }
                            }
                        }
                        if(!IsRedis)
                        {
                            index = 0;
                            db.SaveChanges();
                        }
                    }
                    db.Dispose();
                }

                // 关闭响应
                reader.Dispose();
                responseStream.Dispose();
                response.Close();
            }
            catch (WebException ex)
            {
                function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "获取好哒FTP文件交易数据入库异常");
            }
        }



        public void StartTradeListenBridge()
        {
            Thread th2 = new Thread(ListenTradeDataBridgeReady);
            th2.IsBackground = true;
            th2.Start();
        }
        public void ListenTradeDataBridgeReady()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("cache:ListenTradeDataByOneQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    RedisDbconn.Instance.AddList("ListenTradeDataByOneQueue", content);
                }
                else
                {
                    Thread.Sleep(10000);
                }
            }
        }
        public void StartTradeListenByOne()
        {
            Thread th2 = new Thread(ListenTradeDataByOneReady);
            th2.IsBackground = true;
            th2.Start();
        }
        /// <summary>
        /// 获取好哒FTP昨日交易数据
        /// </summary>
        public void ListenTradeDataByOneReady()
        {
            int index = 0;
            MpMainModels2.WebCMSEntities db = new MpMainModels2.WebCMSEntities();
            bool dbConn = true;
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("ListenTradeDataByOneQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    if(!dbConn)
                    {
                        db = new MpMainModels2.WebCMSEntities();
                        dbConn = true;
                    }
                    if(SaveTradeDataOneReady(db, content))
                    {
                        index += 1;
                    }
                    if(index % 200 == 0 && index > 0)
                    {
                        index = 0;
                        db.SaveChanges();
                    }
                }
                else
                {
                    index = 0;
                    if(dbConn)
                    {
                        db.SaveChanges();
                        db.Dispose();
                        dbConn = false;
                    }
                }
            }
        }
        public bool SaveTradeDataOneReady(MpMainModels2.WebCMSEntities db, string content)
        {
            bool result = false;
            try
            {
                var DataListInfo = content.Split(',');

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

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

                if(!db.HdOrderTmp.Any(m => m.OrderNo == OrderNo))
                {
                    function.WriteLog(DateTime.Now.ToString() + ":" + OrderNo, "好哒交易数据入库new");
                    db.HdOrderTmp.Add(new MpMainModels2.HdOrderTmp()
                    {
                        OrderNo = OrderNo,
                        SettleDuration = TradeCycle,
                        TradeTime = TradeDate,
                        TradeFee = decimal.Parse(function.CheckNum(TradeFee)),
                        TradeAmount = decimal.Parse(function.CheckNum(TradeAmount)),
                        TradeType = TradeType,
                        PayMode = PayWay,
                        DeviceKind = DeviceKind,
                        SnNo = BaseNo,
                        MerNo = MerchantNo,
                    });
                    result = true;
                }
            }
            catch(Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "好哒交易数据入库new异常");
            }
            return result;
        }



        public void StartDepositListenBridge()
        {
            Thread th2 = new Thread(ListenDepositDataBridgeReady);
            th2.IsBackground = true;
            th2.Start();
        }
        public void ListenDepositDataBridgeReady()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("cache:ListenDepositDataByOneQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    RedisDbconn.Instance.AddList("ListenDepositDataByOneQueue", content);
                }
                else
                {
                    Thread.Sleep(10000);
                }
            }
        }
        public void StartDepositListenByOne()
        {
            //每天凌晨执行获取好哒FTP昨日交易数据
            Thread th2 = new Thread(ListenDepositDataByOneReady);
            th2.IsBackground = true;
            th2.Start();
        }
        /// <summary>
        /// 获取好哒FTP昨日交易数据
        /// </summary>
        public void ListenDepositDataByOneReady()
        {
            int index = 0;
            MpMainModels2.WebCMSEntities db = new MpMainModels2.WebCMSEntities();
            bool dbConn = true;
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("ListenDepositDataByOneQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    if(!dbConn)
                    {
                        db = new MpMainModels2.WebCMSEntities();
                        dbConn = true;
                    }
                    SaveDepositDataOneReady(db, content);
                    index += 1;
                    if(index % 200 == 0 && index > 0)
                    {
                        index = 0;
                        db.SaveChanges();
                    }
                }
                else
                {
                    index = 0;
                    if(dbConn)
                    {
                        db.SaveChanges();
                        db.Dispose();
                        dbConn = false;
                    }
                    Thread.Sleep(5000);
                }
            }
        }
        public void SaveDepositDataOneReady(MpMainModels2.WebCMSEntities db, string content)
        {
            try
            {
                var DataListInfo = content.Split(',');

                string SnNo = DataListInfo[0]; //sn
                string MerNo = DataListInfo[1]; //商户编号
                string PosKind = DataListInfo[2]; //机具型号
                string ActDate = DataListInfo[3]; //激活时间
                string Deposit = DataListInfo[4]; //押金金额
                string PrizeAmt = "0"; //奖励金额
                string PrizeDate = "None"; //奖励发放时间
                string Name = ""; //发放人姓名
                string MerName = ""; //商户名称
                string PassDate = ""; //审核通过时期
                string MerKind = ""; //商户类型
                string DepositActCode = ""; //押金活动编号
                string PrizeKind = ""; //奖励类型
                if(DataListInfo.Length > 9)
                {
                    PrizeAmt = DataListInfo[5]; //奖励金额
                    PrizeDate = DataListInfo[6]; //奖励发放时间
                    Name = DataListInfo[7]; //发放人姓名
                    MerName = DataListInfo[8]; //商户名称
                    PassDate = DataListInfo[9]; //审核通过时期
                    if (DataListInfo.Length > 10) MerKind = DataListInfo[10]; //商户类型
                    if (DataListInfo.Length > 11) DepositActCode = DataListInfo[11]; //押金活动编号
                    if (DataListInfo.Length > 12) PrizeKind = DataListInfo[12]; //奖励类型
                }
                else
                {
                    MerName = DataListInfo[5]; //商户名称
                    PassDate = DataListInfo[6]; //审核通过时期
                    if (DataListInfo.Length > 6) MerKind = DataListInfo[7]; //商户类型
                    if (DataListInfo.Length > 7) DepositActCode = DataListInfo[8]; //押金活动编号
                }
                if(!db.HdDepositTmp.Any(m => m.SnNo == SnNo))
                {
                    function.WriteLog(DateTime.Now.ToString() + ":" + SnNo, "好哒押金数据入库new");
                    if(MerKind == "待定")
                    {
                        MpMainModels2.MerchantAddInfo addInfo = db.MerchantAddInfo.FirstOrDefault(m => m.MchtNo == MerNo) ?? new MpMainModels2.MerchantAddInfo();
                        if(addInfo.SubjectType == "SUBJECT_TYPE_ENTERPRISE" || addInfo.SubjectType == "SUBJECT_TYPE_INDIVIDUAL")
                        {
                            MerKind = "000002";
                        }
                        else
                        {
                            MerKind = "000001";
                        }
                    }
                    db.HdDepositTmp.Add(new MpMainModels2.HdDepositTmp()
                    {
                        SnNo = SnNo,
                        MerKind = MerKind,
                        PassDate = PassDate,
                        MerName = MerName,
                        SendMan = Name,
                        PrizeDate = PrizeDate,
                        PrizeAmount = decimal.Parse(function.CheckNum(PrizeAmt)),
                        DepositAmount = decimal.Parse(function.CheckNum(Deposit)),
                        ActDate = ActDate,
                        DeviceKind = PosKind,
                        DepositActCode = DepositActCode,
                        PrizeKind = PrizeKind,
                        MerNo = MerNo,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    });
                }
                else
                {
                    MpMainModels2.HdDepositTmp edit = db.HdDepositTmp.FirstOrDefault(m => m.SnNo == SnNo);
                    if (edit != null)
                    {
                        if(edit.PrizeAmount == 0 && decimal.Parse(function.CheckNum(PrizeAmt)) > 0)
                        {
                            edit.Status = 0;
                            edit.MerKind = MerKind;
                            edit.PassDate = PassDate;
                            edit.MerName = MerName;
                            edit.SendMan = Name;
                            edit.PrizeDate = PrizeDate;
                            edit.PrizeAmount = decimal.Parse(function.CheckNum(PrizeAmt));
                            edit.DepositAmount = decimal.Parse(function.CheckNum(Deposit));
                            edit.ActDate = ActDate;
                            edit.DeviceKind = PosKind;
                            edit.DepositActCode = DepositActCode;
                            edit.PrizeKind = PrizeKind;
                            edit.MerNo = MerNo;
                            edit.UpdateTime = DateTime.Now;
                        }
                        if(ActDate == DateTime.Now.AddDays(-1).ToString("yyyyMMdd"))
                        {
                            function.WriteLog(content + "-update", "监控头一天数据");
                        }
                    }
                    if(ActDate == DateTime.Now.AddDays(-1).ToString("yyyyMMdd"))
                    {
                        function.WriteLog(content + "-update-end", "监控头一天数据");
                    }
                }
            }
            catch(Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "好哒押金数据入库new异常");
            }
        }









        

        public void StartGetTradeData()
        {
            //每天凌晨执行获取好哒FTP昨日交易数据
            Thread th2 = new Thread(ListenGetTradeData);
            th2.IsBackground = true;
            th2.Start();
        }
        /// <summary>
        /// 获取好哒FTP昨日交易数据
        /// </summary>
        public void ListenGetTradeData()
        {
            while (true)
            {
                // if(DateTime.Now.Hour < 9)
                // {
                GetTradeData();
                //     Thread.Sleep(2000);
                // }
                // else
                // {
                Thread.Sleep(10000);
                // }
            }
        }
        public void GetTradeData()
        {
            try
            {
                MpMainModels2.WebCMSEntities db = new MpMainModels2.WebCMSEntities();
                JavaProductModels.WebCMSEntities javadb = new JavaProductModels.WebCMSEntities();
                string today = DateTime.Now.ToString("yyyyMMdd");
                string beforeyesterday = DateTime.Now.AddDays(-2).ToString("yyyyMMdd");
                string yesterday = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
                List<MpMainModels2.HdOrderTmp> orders = db.HdOrderTmp.Where(m => (m.TradeTime.StartsWith(beforeyesterday) || m.TradeTime.StartsWith(yesterday) || m.TradeTime.StartsWith(today)) && m.Status == 0).Take(200).ToList();
                if (orders.Count > 0)
                {
                    foreach (var order in orders)
                    {
                        var MerchantNo = order.MerNo; // 商户号
                        var BaseNo = order.SnNo; // 设备号
                        var DeviceKind = order.DeviceKind; // 终端类型
                        var OrderNo = order.OrderNo; // 订单号
                        var PayWay = order.PayMode; // 支付方式(微信 支付宝)
                        var TradeType = order.TradeType; // 交易类型
                        var TradeAmount = order.TradeAmount; // 交易金额
                        var TradeFee = order.TradeFee; // 交易手续费
                        var TradeDate = order.TradeTime; // 交易时间
                        var TradeCycle = order.SettleDuration; // 结算周期

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

                        function.WriteLog("OrderNo:" + OrderNo, "获取好哒FTP文件交易数据");
                        function.WriteLog("MerchantNo:" + MerchantNo, "获取好哒FTP文件交易数据");

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

                        var merchantAddInfo = db.MerchantAddInfo.FirstOrDefault(m => m.MchtNo == MerchantNo) ?? new MpMainModels2.MerchantAddInfo();
                        if (merchantAddInfo.Id > 0)
                        {
                            function.WriteLog("找到商户", "获取好哒FTP文件交易数据");
                            var merchantInfo = db.MerchantInfo.FirstOrDefault(m => m.Id == merchantAddInfo.Id) ?? new MpMainModels2.MerchantInfo();
                            if (merchantInfo.IsAct == 0)
                            {
                                merchantInfo.IsAct = 1;
                            }

                            function.WriteLog("订单号不存在，开始入库", "获取好哒FTP文件交易数据");
                            var query = db.ConsumerOrders.FirstOrDefault(m => m.OrderNo == OrderNo);
                            if (query == null)
                            {
                                decimal FeeRate = decimal.Parse(function.CheckNum(merchantAddInfo.FeeRate)) * 100;
                                query = db.ConsumerOrders.Add(new MpMainModels2.ConsumerOrders()
                                {
                                    Status = 1,
                                    CreateDate = DateTime.Parse(TradeDate),
                                    UpdateDate = DateTime.Parse(TradeDate),
                                    SnNo = BaseNo,
                                    PayMoney = TradeAmount,
                                    PayMode = PayMode,
                                    SeoTitle = OrderNo,
                                    OrderNo = OrderNo,
                                    MerchantId = merchantAddInfo.Id,
                                    UserId = merchantInfo.UserId,
                                    SeoKeyword = merchantAddInfo.CybMakerCode,
                                    Sort = (int)FeeRate,
                                    TradePayNo = MerchantNo,
                                }).Entity;
                            }
                            MpMainModels2.HdOrderTmp edit = db.HdOrderTmp.FirstOrDefault(m => m.OrderNo == OrderNo);
                            if (edit != null)
                            {
                                edit.Status = 1;
                            }
                            db.SaveChanges();
                            function.WriteLog("入库完毕", "获取好哒FTP文件交易数据");

                            //推送MQ给创业帮
                            if (merchantAddInfo.BrandId == 1)
                            {
                                if (!string.IsNullOrEmpty(merchantAddInfo.CybMakerCode))
                                {
                                    SortedList<string, string> obj = new SortedList<string, string>();
                                    obj.Add("create_time", TradeDate);
                                    obj.Add("sn", BaseNo);
                                    obj.Add("pay_money", TradeAmount.ToString());
                                    obj.Add("pay_mode", PayMode.ToString());
                                    obj.Add("order_no", OrderNo);
                                    obj.Add("merch_no", merchantAddInfo.MchtNo);
                                    obj.Add("maker_code", merchantAddInfo.CybMakerCode);
                                    PushHelper.Instance.Do(obj);
                                }
                                OrderMessageHelper.SendOrderMsg(query);

                            }

                            if (DeviceKind.Contains("好哒设备"))
                            {
                                JavaProductModels.KxsMachine pos = javadb.KxsMachine.FirstOrDefault(m => m.PosSn == BaseNo) ?? new JavaProductModels.KxsMachine();
                                if(pos.BrandId == 18) DeviceKind = "好哒语音王";
                                if(pos.BrandId == 19) DeviceKind = "收款王M820";
                                if(pos.BrandId == 20) DeviceKind = "收款王M826";
                                if(pos.BrandId == 21) DeviceKind = "S312";
                                if(pos.BrandId == 29) DeviceKind = "好哒扫码通";
                                if(pos.BrandId == 20) DeviceKind = "好哒二维码";
                            }
                            PosPushDataNewHelper.Trade(query, DeviceKind);

                            if (DeviceKind.Contains("好哒二维码"))
                            {
                                if (!db.HdQrCodeTmp.Any(m => m.SnNo == BaseNo && m.MerNo == MerchantNo))
                                {
                                    db.HdQrCodeTmp.Add(new MpMainModels2.HdQrCodeTmp()
                                    {
                                        SnNo = BaseNo,
                                        MerNo = MerchantNo,
                                    });
                                    db.SaveChanges();
                                    // PosPushDataNewHelper.Bind(new SpModels.BindRecord()
                                    // {
                                    //     MerSnNo = BaseNo,
                                    //     MerNo = MerchantNo,
                                    //     MerName = merchantAddInfo.CertMerchantName,
                                    //     CreateTime = DateTime.Parse(TradeDate),
                                    //     QueryCount = merchantInfo.UserId,
                                    // }, "好哒二维码");
                                }
                            }

                            if(TradeAmount >= 2)
                            {
                                //小蓝环奖励
                                bool PrizeFlag = db.HdBlueCircleTmp.Any(m => m.MchtNo == MerchantNo && m.PrizeFlag == 0);
                                if(!PrizeFlag)
                                {
                                    MpMainModels2.HdBlueCircleTmp blueCircleTmp = db.HdBlueCircleTmp.FirstOrDefault(m => m.SnNo == BaseNo && m.PrizeFlag == 0);
                                    if(blueCircleTmp != null)
                                    {
                                        string BindDateDetail = blueCircleTmp.BindDateDetail;
                                        DateTime BindTime = DateTime.Parse(BindDateDetail.Substring(0, 4) + "-" + BindDateDetail.Substring(4, 2) + "-" + BindDateDetail.Substring(6, 2) + " " + BindDateDetail.Substring(8, 2) + ":" + BindDateDetail.Substring(10, 2) + ":" + BindDateDetail.Substring(12, 2));
                                        if(BindTime > DateTime.Now.AddDays(-30))
                                        {
                                            blueCircleTmp.PrizeFlag = 1;
                                            db.SaveChanges();
                                            MpMainModels2.MerchantAddInfo addInfo = db.MerchantAddInfo.FirstOrDefault(m => m.MchtNo == MerchantNo) ?? new MpMainModels2.MerchantAddInfo();
                                            MpMainModels2.MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == addInfo.Id) ?? new MpMainModels2.MerchantInfo();
                                            RedisDbconn.Instance.AddList("HaoDaPrizeDataQueue", "{\"brand_id\":201,\"ext_field\":\"xlh\",\"pos_sn\":\"" + BaseNo + "\",\"user_id\":" + merchant.UserId + "}");
                                        }
                                    }
                                }

                                //点餐码奖励
                                // MpMainModels2.HdOrderCodeTmp orderCodeTmp = db.HdOrderCodeTmp.FirstOrDefault(m => m.Sn == BaseNo && m.PrizeFlag == 0);
                                // if(orderCodeTmp != null)
                                // {
                                //     MpMainModels2.HdPrizeFlag flag = db.HdPrizeFlag.FirstOrDefault(m => m.MchtNo == orderCodeTmp.MchtNo) ?? new MpMainModels2.HdPrizeFlag();
                                //     DateTime BindTime = orderCodeTmp.CreateTime.Value;
                                //     if(BindTime > DateTime.Now.AddDays(-30) && flag.OrderCodePrize <= 10)
                                //     {
                                //         orderCodeTmp.PrizeFlag = 1;
                                //         flag.OrderCodePrize += 1;
                                //         db.SaveChanges();
                                //     }
                                // }
                            }
                        }
                        else
                        {
                            MpMainModels2.HdOrderTmp edit = db.HdOrderTmp.FirstOrDefault(m => m.OrderNo == OrderNo);
                            if (edit != null)
                            {
                                edit.Status = -1;
                            }
                            db.SaveChanges();
                        }
                        Thread.Sleep(100);
                    }
                }
                db.Dispose();
                javadb.Dispose();
            }
            catch (WebException ex)
            {
                function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "获取好哒FTP文件交易数据异常");
            }
        }

    }
}