using System;
using System.Collections.Generic;
using Library;
using LitJson;
using System.Linq;
using System.Data;
using System.Threading;
using MySystem.Models;

namespace MySystem
{
    public class StatDataService
    {
        public readonly static StatDataService Instance = new StatDataService();
        private StatDataService()
        { }

        public void Start()
        {
            Thread th = new Thread(dosomething2);
            th.IsBackground = true;
            th.Start();
        }

        public void dosomething()
        {
            bool op = true;
            while (op)
            {
                try
                {
                    string UserId = function.ReadInstance("/stat/UserIdFlag.txt");
                    if (string.IsNullOrEmpty(UserId))
                    {
                        UserId = "0";
                    }
                    WebCMSEntities db = new WebCMSEntities();
                    DataTable dt = dbconn.dtable("select * from TmpUsers where Id>" + UserId + " order by Id limit 1000");
                    foreach (DataRow dr in dt.Rows)
                    {
                        string Id = dr["Id"].ToString();
                        string MakerCode = dr["MakerCode"].ToString();
                        string RealName = dr["RealName"].ToString();
                        string Mobile = dr["Mobile"].ToString();
                        string UpRealName = dr["UpRealName"].ToString();
                        string UpMakerCode = dr["UpMakerCode"].ToString();
                        string TopRealName = dr["TopRealName"].ToString();
                        string TopMakerCode = dr["TopMakerCode"].ToString();
                        string UserLevel = dr["UserLevel"].ToString();
                        if (string.IsNullOrEmpty(UserLevel))
                        {
                            UserLevel = "K1";
                        }
                        string Withdraw = dr["Withdraw"].ToString();
                        string CreateDate = dr["CreateDate"].ToString();
                        ulong AuthFlag = 0;
                        DateTime AuthDate = DateTime.Parse("1900-01-01");
                        if (!string.IsNullOrEmpty(RealName))
                        { 
                            AuthFlag = 1;
                            AuthDate = DateTime.Now;
                        }
                        Users user = db.Users.Add(new Users()
                        {
                            LoginPwd = function.MD532(Mobile.Substring(7)),
                            MakerCode = MakerCode,
                            RealName = RealName,
                            Mobile = Mobile,
                            UserLevel = int.Parse(UserLevel.Replace("K", "")),
                            SettleAmount = decimal.Parse(Withdraw),
                            CreateDate = DateTime.Parse(CreateDate),
                            SeoTitle = UpMakerCode,
                            AuthFlag = AuthFlag,
                            AuthDate = AuthDate,
                        }).Entity;
                        db.SaveChanges();
                        // UserForMobile userFor = db.UserForMobile.FirstOrDefault(m => m.Mobile == Mobile);
                        // if (userFor == null)
                        // {
                        //     userFor = new UserForMobile()
                        //     {
                        //         Mobile = Mobile,
                        //     };
                        //     db.SaveChanges();
                        // }
                        // userFor.UserId = user.Id;
                        // UserForMakerCode userForCode = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode);
                        // if (userForCode == null)
                        // {
                        //     userForCode = new UserForMakerCode()
                        //     {
                        //        MakerCode = MakerCode,
                        //     };
                        //     db.SaveChanges();
                        // }
                        // userForCode.UserId = user.Id;
                        // db.SaveChanges();
                        function.WritePage("/stat/", "UserIdFlag.txt", Id);
                    }
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "导数据异常");
                }
                Thread.Sleep(200);
            }
        }

        public void dosomething2()
        {
            bool op = true;
            while (op)
            {
                try
                {
                    string UserId = function.ReadInstance("/stat/UIdFlag.txt");
                    if (string.IsNullOrEmpty(UserId))
                    {
                        UserId = "0";
                    }
                    int Uid = int.Parse(UserId);
                    WebCMSEntities db = new WebCMSEntities();
                    List<int> userids = db.Users.Select(m => m.Id).Where(m => m > Uid).OrderBy(m => m).Take(100).ToList();
                    foreach (int userid in userids)
                    {
                        int ParentUserId = userid;
                        string NavString = "";
                        while (ParentUserId > 0)
                        {
                            Users puser = db.Users.FirstOrDefault(m => m.Id == ParentUserId);
                            if (puser != null)
                            {
                                NavString = "," + ParentUserId + "," + NavString;
                                ParentUserId = puser.ParentUserId;
                            }
                            else
                            {
                                ParentUserId = 0;
                            }
                        }
                        if (!string.IsNullOrEmpty(NavString))
                        {
                            string[] useridlist = NavString.Trim(',').Replace(",,", ",").Split(',');
                            foreach (string useridstring in useridlist)
                            {
                                int SubUserId = int.Parse(useridstring);
                                Users subUser = db.Users.FirstOrDefault(m => m.Id == SubUserId);
                                if (subUser != null)
                                {
                                    subUser.ParentNav = NavString.Substring(0, NavString.IndexOf("," + useridstring + ","));
                                }
                            }
                        }
                        db.SaveChanges();
                        function.WritePage("/stat/", "UIdFlag.txt", userid.ToString());
                    }
                    db.SaveChanges();
                    db.Dispose();
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "执行上下级异常");
                }
                Thread.Sleep(200);
            }
        }

        public void StatCreatorData(int UserId, ConsumerOrders order)
        {
            string DateString = order.UpdateDate.Value.ToString("yyyyMMdd");
            string MonthString = order.UpdateDate.Value.ToString("yyyyMM");
            // RedisDbconn.Instance.AddNumber("TradeStat:" + UserId + ":" + DateString, order.PayMoney);
            // RedisDbconn.Instance.AddNumber("TradeStat:" + UserId + ":" + MonthString, order.PayMoney);
        }
    }
}