using System;
using System.Threading;
using System.Data;
using StackExchange.Redis;
using CSharpUtil;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Diagnostics;

namespace DataTransfer
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("言灵数据传输开始........");

            Thread t1 = new Thread(transfer);         
            t1.Start();
            
        }
        public static int mask = 0;

        public static void transfer()
        {
            Console.WriteLine("transfer............");
            while (true)
            {
                try
                {                               
                    int hour = DateTime.Now.Hour;            
                    if (hour == 11 && mask == 0)//正式的是晚上2点进行数据传输
                    {
                        Console.WriteLine("数据传输的时间到了开始执行程序.......");
                        //进行数据传输
                        mask = 1;                        
                        dataTransfer();                      
                    }

                    if (hour != 11 && mask != 0)
                    {
                        mask = 0;
                    }
                }
                catch (Exception ex)
                {                  
                    Console.WriteLine(ex.Message);  // 提示套接字监听异常     
                    break;
                }
            }                 
        } 

        public static void dataTransfer()
        {
            Console.WriteLine("进入dataTransfer方法..............");
            
            TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970,1,1);            
            float day = MathF.Floor((long)ts.TotalSeconds / 24 / 60 / 60);
            Console.WriteLine("当前天是："+ day);

            var mem = Redis.Ins.GetDatabase(0);

            int zoneid = 1;//暂时先这样
            if (mem.KeyExists(MemKey_Statistics.GamerunLoginUser(zoneid,day)))
            {              
                string[] list = mem.HashKeys(MemKey_Statistics.GamerunLoginUser(zoneid, day)).ToStringArray();                          
                foreach (string k in list)
                {                 
                    redisToSql(k,zoneid);
                }          
            }
        }

        const string Userbaseparams_TableName = "tab_userbaseparams";

        /// <summary>
        /// redis数据传输到mysql中
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="zoneid"></param>
        public static void redisToSql(string uid,int zoneid)
        {
            Console.WriteLine("数据传输开始..........：" );

            var mem = Redis.Ins.GetDatabase(0);
            string key = MemKey_Statistics.UserBaseParams(uid,zoneid);

            if (mem.KeyExists(key))
            {
                long length = mem.ListLength(key);              
                var ctxList = mem.ListRange(key, 0, length);         

                int num = 0;
                foreach (var item in ctxList)
                {
                    num += 1;
                    JObject dic = JObject.Parse(item.ToString());
                    int cmd =  int.Parse(dic["cmd"].ToString());
                    int type = int.Parse(dic["type"].ToString());
                    string curVal = dic["curVal"].ToString();
                    string changeVal = dic["changeVal"].ToString();
                    string endVal = dic["endVal"].ToString();
                    string desc = dic["desc"].ToString();
                    //Console.WriteLine("desc..........："+ desc);
                    string ts = dic["ts"].ToString();

                    //continue;

                    var sql = $" Insert Into {Userbaseparams_TableName} (`uid`, `zoneid`, `cmd`, `type`, `curVal`, `endVal`, `changeVal`, `desc`, `ts`) " +
                $"values('{uid}',{zoneid},{cmd},{type},'{curVal}','{changeVal}','{endVal}','{desc}','{ts}')";

                    var n = MysqlUtil.Ins.ExecuteSqlNonQuery(sql);
                    //Debug.Assert(n > 0, $"{sql} 执行失败!");

                    if (num>=length)
                    {
                        Console.WriteLine("总共执行条数：" + num);
                        break;
                    }

                }
            }
        }
    }
}
