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

namespace MySystem
{
    /// <summary>
    /// 运营中心定时程序
    /// </summary>
    public class OperateService
    {
        public readonly static OperateService Instance = new OperateService();
        private OperateService()
        { }


        #region 每天统计一次数据
        public void Start()
        {
            Thread th = new Thread(doSomething);
            th.IsBackground = true;
            th.Start();
        }

        public void doSomething()
        {
            while (true)
            {
                if (DateTime.Now.Hour > 0 && DateTime.Now.Hour < 4)
                {
                    try
                    {
                        string Month = DateTime.Now.ToString("yyyyMM");
                        string Date = DateTime.Now.ToString("yyyyMMdd");
                        string check = function.ReadInstance("/Operate/" + Date + ".txt");
                        if (string.IsNullOrEmpty(check))
                        {
                            function.WritePage("/Operate/", "" + Date + ".txt", DateTime.Now.ToString("HH:mm:ss"));
                            WebCMSEntities db = new WebCMSEntities();

                            //统计发货量
                            DataTable dt = CustomerSqlConn.dtable("select CONCAT('update Users set ThisMonthSend=(select count(Id) from StoreStockChange where CreateDate>=\'" + DateTime.Now.ToString("yyyy-MM") + "-01 00:00:00\' and TransType in (10,11) and OpId=',Id,') where Id=',Id,';') from Users where UserType=1", MysqlConn.SqlConnStr);
                            foreach(DataRow dr in dt.Rows)
                            {
                                CustomerSqlConn.op(dr[0].ToString(), MysqlConn.SqlConnStr);
                            }
                            dt = CustomerSqlConn.dtable("select distinct CONCAT('update Users set ThisMonthSend=(select count(Id) from StoreStockChange where CreateDate>=\'" + DateTime.Now.ToString("yyyy-MM") + "-01 00:00:00\' and TransType in (10,11) and StoreId in (select Id from StoreHouse where UserId=',QueryCount,') and OpId=',OpId,') where Id=', QueryCount,';') from StoreForOperate where Sort=0 and Status>-1", MysqlConn.OpSqlConnStr);
                            foreach(DataRow dr in dt.Rows)
                            {
                                CustomerSqlConn.op(dr[0].ToString(), MysqlConn.SqlConnStr);
                            }

                            //统计库存
                            Dictionary<int, int> StoreList = db.StoreHouse.Select(m => new { m.UserId, m.LaveNum }).Where(m => m.LaveNum > 0).GroupBy(m => m.UserId).Select(m => new { UserId = m.Key, Count = m.Count() }).ToDictionary(m => m.UserId, m => m.Count);
                            foreach(int UserId in StoreList.Keys)
                            {
                                Users user = db.Users.FirstOrDefault(m => m.Id == UserId);
                                if(user != null)
                                {
                                    user.StoreStock += StoreList[UserId];
                                }
                            }
                            db.SaveChanges();

                            db.Dispose();
                        }
                    }
                    catch (Exception ex)
                    {
                        function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "运营中心重置本月发货量异常");
                    }
                }
                Thread.Sleep(800000);
            }
        }
        #endregion
    }
}