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 GetHaoDaBlueCircleBindService
    {
        public readonly static GetHaoDaBlueCircleBindService Instance = new GetHaoDaBlueCircleBindService();
        private GetHaoDaBlueCircleBindService()
        { }

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

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

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

        public void SaveBlueCircleBindData(string Date, bool IsRedis = false)
        {
            // 要下载的文件路径
            string filePath = "/haoda-deposit/xlh_bind_" + Date + ".csv";

            try
            {
                // 创建FtpWebRequest对象
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(GetHaoDaFTPInfoService.Instance.ftpServerAddress + filePath);
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential(GetHaoDaFTPInfoService.Instance.ftpUser, GetHaoDaFTPInfoService.Instance.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();
                    List<string> SnNos = db.HdBlueCircleTmp.Select(m => m.SnNo).ToList();
                    List<string> ChkSnNos = new List<string>();
                    var DataInfo = fileContents.TrimEnd('\n').Split('\n', 2);
                    if (DataInfo.Length > 1)
                    {
                        int index = 0;
                        var DataList = DataInfo[1].Split('\n');
                        foreach (var DataListItem in DataList)
                        {
                            if(IsRedis)
                            {
                                RedisDbconn.Instance.AddList("ListenBlueCircleBindDataByOneQueue", DataListItem);
                            }
                            else
                            {
                                SaveBlueCircleBindDataOneReady(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 StartBlueCircleBindListenBridge()
        {
            Thread th2 = new Thread(ListenBlueCircleBindDataBridgeReady);
            th2.IsBackground = true;
            th2.Start();
        }
        public void ListenBlueCircleBindDataBridgeReady()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("cache:ListenBlueCircleBindDataByOneQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    RedisDbconn.Instance.AddList("ListenBlueCircleBindDataByOneQueue", content);
                }
                else
                {
                    Thread.Sleep(10000);
                }
            }
        }
        public void StartBlueCircleBindListenByOne()
        {
            //每天凌晨执行获取好哒FTP昨日交易数据
            Thread th2 = new Thread(ListenBlueCircleBindDataByOneReady);
            th2.IsBackground = true;
            th2.Start();
        }
        /// <summary>
        /// 获取好哒FTP昨日交易数据
        /// </summary>
        public void ListenBlueCircleBindDataByOneReady()
        {
            int index = 0;
            MpMainModels2.WebCMSEntities db = new MpMainModels2.WebCMSEntities();
            bool dbConn = true;
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("ListenBlueCircleBindDataByOneQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    if(!dbConn)
                    {
                        db = new MpMainModels2.WebCMSEntities();
                        dbConn = true;
                    }
                    SaveBlueCircleBindDataOneReady(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 void SaveBlueCircleBindDataOneReady(MpMainModels2.WebCMSEntities db, string content)
        {
            try
            {
                var DataListInfo = content.Split(',');

                string sn_no = DataListInfo[0]; //SN号
                string bind_date = DataListInfo[1]; //绑定日期
                string bind_date_detail = DataListInfo[2]; //绑定时间
                string mcht_no = DataListInfo[3]; //商户号
                string mcht_nm = DataListInfo[4]; //商户名称
                string through_date = DataListInfo[5]; //截止日期
                string channel_kind = DataListInfo[6]; //商户类型

                MpMainModels2.HdBlueCircleTmp edit = db.HdBlueCircleTmp.FirstOrDefault(m => m.SnNo == sn_no);
                if(edit == null)
                {
                    function.WriteLog(DateTime.Now.ToString() + ":add:" + sn_no, "好哒小蓝环绑定");
                    db.HdBlueCircleTmp.Add(new MpMainModels2.HdBlueCircleTmp()
                    {
                        SnNo = sn_no,
                        BindDate = bind_date,
                        BindDateDetail = bind_date_detail,
                        MchtNo = mcht_no,
                        MchtNm = mcht_nm,
                        ThroughDate = through_date,
                        ChannelKind = channel_kind,
                    });
                }
                else
                {
                    function.WriteLog(DateTime.Now.ToString() + ":update:" + sn_no, "好哒小蓝环绑定");
                    edit.Status = 0;
                    edit.BindDate = bind_date;
                    edit.BindDateDetail = bind_date_detail;
                    edit.MchtNo = mcht_no;
                    edit.MchtNm = mcht_nm;
                    edit.ThroughDate = through_date;
                    edit.ChannelKind = channel_kind;
                }
                db.SaveChanges();
            }
            catch(Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "好哒小蓝环绑定异常");
            }
        }

    }
}