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

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

        /// <summary>
        /// 获取好哒FTP昨日交易数据
        /// </summary>
        public void GetTouchRewardBindDataReady()
        {
            while (true)
            {
                if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 15:35:00"))
                {
                    string date = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
                    string check = function.ReadInstance("/TouchReward/check" + date + ".txt");
                    if (string.IsNullOrEmpty(check))
                    {
                        function.WritePage("/TouchReward/", "check" + date + ".txt", DateTime.Now.ToString());
                        SaveTouchRewardData(date);
                    }
                }
                Thread.Sleep(180000);
            }
        }

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

        public void SaveTouchRewardData(string Date, bool IsRedis = false)
        {
            // 要下载的文件路径
            string filePath = "/haoda-deposit/pyp_reward_" + 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();
                    JavaProductModels.WebCMSEntities javauserdb = new JavaProductModels.WebCMSEntities();
                    List<string> SnNos = db.HdTouchRewardTmp.Select(m => m.SnNo).ToList();
                    List<string> ChkSnNos = new List<string>();
                    var DataInfo = fileContents.TrimEnd('\n').Split('\n', 2);
                    if (DataInfo.Length > 1)
                    {
                        var DataList = DataInfo[1].Split('\n');
                        foreach (var DataListItem in DataList)
                        {
                            if(IsRedis)
                            {
                                RedisDbconn.Instance.AddList("ListenTouchRewardBindDataByOneQueue", DataListItem);
                            }
                            else
                            {
                                SaveTouchRewardDataOneReady(db, javauserdb, DataListItem);
                            }
                        }
                    }
                    db.Dispose();
                    javauserdb.Dispose();
                }

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




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

                string sn_no = DataListInfo[0]; //SN号
                string light_up_time = DataListInfo[1]; //点亮时间
                string reward = DataListInfo[2]; //奖励
                string effective_date = DataListInfo[3]; //生效日期
                string acct_nm = DataListInfo[4]; //活动名称
                string bonus_type = DataListInfo[5]; //奖励类型

                MpMainModels2.HdTouchRewardTmp item = db.HdTouchRewardTmp.FirstOrDefault(m => m.SnNo == sn_no && m.BonusType == bonus_type);
                if(item == null)
                {
                    function.WriteLog(DateTime.Now.ToString() + ":add:" + sn_no, "好哒碰一碰奖励");
                    db.HdTouchRewardTmp.Add(new MpMainModels2.HdTouchRewardTmp()
                    {
                        SnNo = sn_no,
                        LightUpTime = DateTime.Parse(light_up_time),
                        Reward = decimal.Parse(reward),
                        EffectiveDate = effective_date,
                        AcctNm = acct_nm,
                        BonusType = bonus_type,
                        Status = 1,
                    });

                    // JavaProductModels.KxsMachine pos = javauserdb.KxsMachine.FirstOrDefault(m => m.PosSn == sn_no && m.UserId > 0);
                    // if(pos != null)
                    // {
                    //     Dictionary<string, object> prizeData = new Dictionary<string, object>();
                    //     prizeData.Add("brand_id", 29);
                    //     prizeData.Add("ext_field", bonus_type);
                    //     prizeData.Add("pos_sn", sn_no);
                    //     prizeData.Add("user_id", pos.UserId);
                    //     if (bonus_type == "830_21" || bonus_type == "830_22" || bonus_type == "833_01" || bonus_type == "833_02" || bonus_type == "995_21" || bonus_type == "995_22")
                    //     {
                    //         prizeData.Add("prize", reward);
                    //     }
                    //     RedisDbconn.Instance.AddList("HaoDaPrizeDataQueue", Newtonsoft.Json.JsonConvert.SerializeObject(prizeData));
                    // }
                }
                else if(bonus_type == "995")
                {
                    function.WriteLog("\n\n\n" + DateTime.Now.ToString() + ":" + sn_no, "好哒碰一碰995奖励");
                    if(item.Status != 2)
                    {
                        function.WriteLog(DateTime.Now.ToString() + ":ok", "好哒碰一碰995奖励");
                        // JavaProductModels.KxsMachine pos = javauserdb.KxsMachine.FirstOrDefault(m => m.PosSn == sn_no && m.UserId > 0);
                        // if(pos != null)
                        // {
                        //     function.WriteLog(DateTime.Now.ToString() + ":找到机具", "好哒碰一碰995奖励");
                        //     RedisDbconn.Instance.AddList("HaoDaPrizeDataQueue", "{\"brand_id\":29,\"ext_field\":\"" + bonus_type + "\",\"pos_sn\":\"" + sn_no + "\",\"user_id\":" + pos.UserId + "}");
                        // }
                        item.Status = 2;
                        function.WriteLog(DateTime.Now.ToString() + ":执行结束", "好哒碰一碰995奖励");
                    }
                }
                db.SaveChanges();
            }
            catch(Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "好哒碰一碰奖励异常");
            }
        }

    }
}