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

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

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

        public void StartDo()
        {
            while(true)
            {
                try
                {
                    if(DateTime.Now.Hour > 0)
                    {
                        string doDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                        string flag = function.ReadInstance("/UpUserSave/" + doDate + ".txt");
                        if (string.IsNullOrEmpty(flag))
                        {
                            function.WritePage("/UpUserSave/", doDate + ".txt", DateTime.Now.ToString("HH:mm:ss"));
                            doSomething(doDate);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Utils.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "异常");
                }
                Thread.Sleep(3600000);
            }
        }

        public void doSomething(string date = "")
        {
            WebCMSEntities db = new WebCMSEntities();
            var users = db.Users.Select(m => new { m.Id, m.ParentNav, m.CreateDate });
            if(!string.IsNullOrEmpty(date))
            {
                DateTime start = DateTime.Parse(date + " 00:00:00");
                DateTime end = start.AddDays(1);
                users = users.Where(m => m.CreateDate >= start && m.CreateDate < end);
            }
            string sql = "";
            int num = 0;
            foreach(var user in users.ToList())
            {
                if(!string.IsNullOrEmpty(user.ParentNav))
                {
                    string[] ParentNavList = user.ParentNav.Replace(",,", ",").Trim(',').Split(',');
                    int i = 0;
                    foreach(string ParentUserId in ParentNavList)
                    {
                        i += 1;
                        num += 1;
                        sql += "insert into UpUserRelation (UserId,UpUserId,Floor) values (" + user.Id + ", " + ParentUserId + ", " + i + ");";
                        if(num % 200 == 0)
                        {
                            CustomerSqlConn.op(sql, MysqlConn.SqlConnStr);
                            sql = "";
                        }
                    }
                }
            }
            if(!string.IsNullOrEmpty(sql))
            {
                CustomerSqlConn.op(sql, MysqlConn.SqlConnStr);
                sql = "";
            }
        }
    }
}