using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Threading;
using Library;
using LitJson;
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.Hour > 10 && 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());
                        GetDepositData(DateTime.Now.AddDays(-1).ToString("yyyyMMdd"));
                        Thread.Sleep(60000);
                        GetTradeData(DateTime.Now.AddDays(-1).ToString("yyyyMMdd"));
                    }
                }
                Thread.Sleep(7200000);
            }
        }

        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:05:00"))
                {
                    GetDepositData("d_" + DateTime.Now.ToString("yyyyMMdd"));
                }
                GetTradeData(DateTime.Now.ToString("yyyyMMdd"));
                Thread.Sleep(1800000);
            }
        }

        public void StartListen()
        {
            //每天凌晨执行获取好哒FTP昨日交易数据
            Thread th2 = new Thread(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))
                {
                    GetDepositData2(content);
                    Thread.Sleep(2000);
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
        }
        public void GetDepositData(string Date)
        {
            // 要下载的文件路径
            string filePath = "/haoda-deposit/deposit_" + Date + ".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();
                StreamReader reader = new StreamReader(responseStream);
                // 读取数据
                string fileContents = reader.ReadToEnd();
                if (!string.IsNullOrEmpty(fileContents))
                {
                    WebCMSEntities db = new WebCMSEntities();
                    MpMainModels2.WebCMSEntities mpdb2 = new MpMainModels2.WebCMSEntities();
                    var DataInfo = fileContents.TrimEnd('\n').Split('\n', 2);
                    if(DataInfo.Length > 1)
                    {
                        var DataList = DataInfo[1].Split('\n');
                        foreach (var DataListItem in DataList)
                        {
                            var DataListInfo = DataListItem.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 = ""; //商户类型
                            if(Date.StartsWith("d_"))
                            {
                                MerName = DataListInfo[5]; //商户名称
                                PassDate = DataListInfo[6]; //审核通过时期
                                MerKind = DataListInfo[7]; //商户类型
                            }
                            else
                            {
                                PrizeAmt = DataListInfo[5]; //奖励金额
                                PrizeDate = DataListInfo[6]; //奖励发放时间
                                Name = DataListInfo[7]; //发放人姓名
                                MerName = DataListInfo[8]; //商户名称
                                PassDate = DataListInfo[9]; //审核通过时期
                            }

                            string ActDateString = ActDate.Substring(0, 4) + "-" + ActDate.Substring(4, 2) + "-" + ActDate.Substring(6, 2);
                            if(DateTime.Parse(ActDateString) >= DateTime.Parse(DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd")))
                            {
                                string PrizeDateString = "";
                                if(PrizeDate == "None")
                                {
                                    PrizeDate = Date.Replace("d_", "");
                                }
                                else
                                {
                                    PrizeDateString = PrizeDate.Substring(0, 4) + "-" + PrizeDate.Substring(4, 2) + "-" + PrizeDate.Substring(6, 2);
                                }

                                if(!db.BindRecord.Any(m => m.MerSnNo == SnNo))
                                {
                                    string ProductType = "0";
                                    if(PosKind == "好哒语音王Y512") ProductType = "18";
                                    if(PosKind == "4G收款王M820") ProductType = "19";
                                    if(PosKind == "4G收款王M826") ProductType = "20";
                                    if(PosKind == "好哒S312") ProductType = "21";
                                    if(PosKind == "好哒扫码通M837") ProductType = "29";

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

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

                                    Thread.Sleep(1000);

                                    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,
                                    });
                                    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");
                                    }
                                }
                            }
                        }
                    }
                    db.Dispose();
                    mpdb2.Dispose();
                }

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

        public void GetDepositData2(string Date)
        {
            // 要下载的文件路径
            string filePath = "/haoda-deposit/deposit_" + Date + ".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();
                StreamReader reader = new StreamReader(responseStream);
                // 读取数据
                string fileContents = reader.ReadToEnd();
                if (!string.IsNullOrEmpty(fileContents))
                {
                    WebCMSEntities db = new WebCMSEntities();
                    MpMainModels2.WebCMSEntities mpdb2 = new MpMainModels2.WebCMSEntities();
                    var DataInfo = fileContents.TrimEnd('\n').Split('\n', 2);
                    if(DataInfo.Length > 1)
                    {
                        var DataList = DataInfo[1].Split('\n');
                        foreach (var DataListItem in DataList)
                        {
                            var DataListInfo = DataListItem.Split(',');

                            string SnNo = DataListInfo[0]; //sn
                            string MerNo = DataListInfo[1]; //商户编号
                            string PosKind = DataListInfo[2]; //机具型号
                            string ActDate = DataListInfo[3]; //激活时间
                            string Deposit = DataListInfo[4]; //押金金额
                            string PrizeAmt = DataListInfo[5]; //奖励金额
                            string PrizeDate = DataListInfo[6]; //奖励发放时间
                            string Name = DataListInfo[7]; //发放人姓名

                            string ActDateString = ActDate.Substring(0, 4) + "-" + ActDate.Substring(4, 2) + "-" + ActDate.Substring(6, 2);
                            string PrizeDateString = "";
                            if(PrizeDate == "None")
                            {
                                PrizeDate = Date;
                            }
                            else
                            {
                                PrizeDateString = PrizeDate.Substring(0, 4) + "-" + PrizeDate.Substring(4, 2) + "-" + PrizeDate.Substring(6, 2);
                            }

                            string ProductType = "0";
                            if(PosKind == "好哒语音王Y512") ProductType = "18";
                            if(PosKind == "4G收款王M820") ProductType = "19";
                            if(PosKind == "4G收款王M826") ProductType = "20";
                            if(PosKind == "好哒S312") ProductType = "21";

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

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

                            Thread.Sleep(1000);

                            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,
                            });
                            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");
                            }
                        }
                    }
                    db.Dispose();
                    mpdb2.Dispose();
                }

                // 关闭响应
                reader.Dispose();
                responseStream.Dispose();
                response.Close();
            }
            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());
                        GetTradeData(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))
                {
                    GetTradeData(content);
                    Thread.Sleep(2000);
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
        }
        public void GetTradeData(string Date)
        {
            // 要下载的文件路径
            string filePath = "/haoda-trade/" + Date + ".csv";
            function.WriteLog(DateTime.Now.ToString() + ":" + filePath, "获取好哒FTP文件交易数据");
            
            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();
                function.WriteLog("fileContents:" + fileContents, "获取好哒FTP文件交易数据");
                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');
                        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[3];
                            PayWay = DataListInfo[4];
                            TradeType = DataListInfo[5];
                            TradeAmount = DataListInfo[6];
                            TradeFee = DataListInfo[7];
                            TradeDate = DataListInfo[8];
                            TradeCycle = DataListInfo[9];

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

                            if(DateTime.Parse(TradeDate) > DateTime.Parse(DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd") + " 00:00:00"))
                            {
                                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;
                                    }
                                    var orders = db.ConsumerOrders.FirstOrDefault(m => m.SeoTitle == OrderNo && m.OrderNo == OrderNo) ?? new MpMainModels2.ConsumerOrders();
                                    if (orders.Id == 0)
                                    {
                                        function.WriteLog("订单号不存在，开始入库", "获取好哒FTP文件交易数据");
                                        decimal FeeRate = decimal.Parse(function.CheckNum(merchantAddInfo.FeeRate)) * 100;
                                        var query = db.ConsumerOrders.Add(new MpMainModels2.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,
                                            SeoKeyword = merchantAddInfo.CybMakerCode,
                                            Sort = (int)FeeRate,
                                        }).Entity;
                                        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);
                                                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);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    db.Dispose();
                }

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

    }
}