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

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

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

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

        public void SaveOrderCodeBindData(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.HdOrderCodeTmp.Select(m => m.Sn).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("ListenOrderCodeBindDataByOneQueue", DataListItem);
                            }
                            else
                            {
                                SaveOrderCodeBindDataOneReady(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 StartOrderCodeBindListenBridge()
        {
            Thread th2 = new Thread(ListenOrderCodeBindDataBridgeReady);
            th2.IsBackground = true;
            th2.Start();
        }
        public void ListenOrderCodeBindDataBridgeReady()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("cache:ListenOrderCodeBindDataByOneQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    RedisDbconn.Instance.AddList("ListenOrderCodeBindDataByOneQueue", content);
                }
                else
                {
                    Thread.Sleep(10000);
                }
            }
        }
        public void StartOrderCodeBindListenByOne()
        {
            //每天凌晨执行获取好哒FTP昨日交易数据
            Thread th2 = new Thread(ListenOrderCodeBindDataByOneReady);
            th2.IsBackground = true;
            th2.Start();
        }
        /// <summary>
        /// 获取好哒FTP昨日交易数据
        /// </summary>
        public void ListenOrderCodeBindDataByOneReady()
        {
            int index = 0;
            MpMainModels2.WebCMSEntities db = new MpMainModels2.WebCMSEntities();
            bool dbConn = true;
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("ListenOrderCodeBindDataByOneQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    if(!dbConn)
                    {
                        db = new MpMainModels2.WebCMSEntities();
                        dbConn = true;
                    }
                    SaveOrderCodeBindDataOneReady(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 SaveOrderCodeBindDataOneReady(MpMainModels2.WebCMSEntities db, string content)
        {
            try
            {
                var DataListInfo = content.Split(',');

                string sn = DataListInfo[0]; //SN号
                string create_time = DataListInfo[1]; //创建时间
                string mcht_no = DataListInfo[2]; //商户号
                string mcht_nm = DataListInfo[3]; //商户名称
                string through_date = DataListInfo[4]; //截止日期
                string channel_kind = DataListInfo[5]; //商户类型
                string opr_name = DataListInfo[6]; //操作员
                string opr_invite_code = DataListInfo[7]; //邀请码
                string sync_status = DataListInfo[8]; //同步状态

                MpMainModels2.HdOrderCodeTmp edit = db.HdOrderCodeTmp.FirstOrDefault(m => m.Sn == sn);
                if(edit == null)
                {
                    function.WriteLog(DateTime.Now.ToString() + ":add:" + sn, "好哒点餐码绑定");
                    db.HdOrderCodeTmp.Add(new MpMainModels2.HdOrderCodeTmp()
                    {
                        Sn = sn,
                        CreateTime = DateTime.Parse(create_time),
                        MchtNo = mcht_no,
                        MchtNm = mcht_nm,
                        ThroughDate = through_date,
                        ChannelKind = channel_kind,
                        OprName = opr_name,
                        OprInviteCode = opr_invite_code,
                        SyncStatus = sync_status,
                    });
                }
                else
                {
                    function.WriteLog(DateTime.Now.ToString() + ":update:" + sn, "好哒点餐码绑定");
                    edit.Status = 0;
                    edit.CreateTime = DateTime.Parse(create_time);
                    edit.MchtNo = mcht_no;
                    edit.MchtNm = mcht_nm;
                    edit.ThroughDate = through_date;
                    edit.ChannelKind = channel_kind;
                    edit.OprName = opr_name;
                    edit.OprInviteCode = opr_invite_code;
                    edit.SyncStatus = sync_status;
                }
                db.SaveChanges();
            }
            catch(Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "好哒点餐码绑定异常");
            }
        }

    }
}