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

public class ResetSmallStoreHelper
{
    public readonly static ResetSmallStoreHelper Instance = new ResetSmallStoreHelper();
    private ResetSmallStoreHelper()
    {
    }

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

    private void ListenDo()
    {
        while (true)
        {
            if(DateTime.Now.Day == 1 && DateTime.Now.Hour > 1 && DateTime.Now.Hour < 9)
            {
                RedisDbconn.Instance.AddList("ResetSmallStoreQueue", "1");
            }
            Thread.Sleep(600000);
        }
    }

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

    // 每月1号小分仓额度，额度为上个月实际发放的总分润
    private void DoWorks()
    {
        while (true)
        {
            Utils.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "计算小分仓额度日志");
            WebCMSEntities db = new WebCMSEntities();
            string connstr = Library.ConfigurationManager.AppSettings["Pxc1SqlConnStr"].ToString();
            try
            {
                string content = RedisDbconn.Instance.RPop<string>("ResetSmallStoreQueue");
                if(!string.IsNullOrEmpty(content))
                {
                    string Month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
                    string PreMonth = DateTime.Now.AddMonths(-2).ToString("yyyyMM");
                    string check = function.ReadInstance("/ResetSmallStore/" + Month + ".txt");
                    if(string.IsNullOrEmpty(check))
                    {
                        function.WritePage("/ResetSmallStore/", Month + ".txt", DateTime.Now.ToString());
                        CustomerSqlConn.op("update UserAccount set ThisMonthPreAmount=0,ValidPreAmount=0 where ThisMonthPreAmount>0", connstr);
                        string minId = "0";
                        DataTable minIdDt = CustomerSqlConn.dtable("select min(Id) from ProfitRecord where SeoTitle='" + PreMonth + "'", connstr);
                        if(minIdDt.Rows.Count > 0)
                        {
                            minId = minIdDt.Rows[0][0].ToString();
                        }
                        DoMethod(db, PreMonth, minId);
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "计算小分仓额度异常");
            }
            db.Dispose();
            Utils.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "计算小分仓额度日志");
            Thread.Sleep(60000);
        }
    }

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

    private void DoWorksReset()
    {
        while (true)
        {
            WebCMSEntities db = new WebCMSEntities();
            try
            {
                string content = RedisDbconn.Instance.RPop<string>("ResetSmallStoreByUserIdQueue");
                if(!string.IsNullOrEmpty(content))
                {
                    string Month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
                    string PreMonth = DateTime.Now.AddMonths(-2).ToString("yyyyMM");                    
                    string minId = "0";
                    DoMethod(db, PreMonth, minId, content);
                }
            }
            catch (Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "重置小分仓额度异常");
            }
            db.Dispose();
            Thread.Sleep(60000);
        }
    }

    public void DoMethod(WebCMSEntities db, string PreMonth, string minId = "0", string UId = "")
    {
        string sql = "";
        if(string.IsNullOrEmpty(UId))
        {
            sql = "select UserId,sum(ProfitAmount) from ProfitRecord where Id>=" + minId + " and UserId>0 and SeoTitle='" + PreMonth + "' group by UserId";
        }
        else
        {
            sql = "select UserId,sum(ProfitAmount) from ProfitRecord where Id>=" + minId + " and UserId=" + UId + " and SeoTitle='" + PreMonth + "' group by UserId";
        }
        string connstr = Library.ConfigurationManager.AppSettings["Pxc1SqlConnStr"].ToString();
        DataTable dt = CustomerSqlConn.dtable(sql, connstr);
        Utils.WriteLog("总数" + dt.Rows.Count, "计算小分仓额度日志");
        int index = 0;
        foreach (DataRow dr in dt.Rows)
        {
            index += 1;
            int UserId = int.Parse(function.CheckInt(dr["UserId"].ToString()));
            decimal ProfitAmount = decimal.Parse(function.CheckNum(dr[1].ToString()));
            decimal PreProfitAmount = ProfitAmount;
            var prelist = db.PreSendStockDetail.Select(m => new { m.Id, m.BrandId, m.ToUserId, m.Status, m.ApplyFlag, m.AuthFlag }).Where(m => m.ToUserId == UserId && m.Status == 1 && m.ApplyFlag == 0 && m.AuthFlag == 1).ToList();
            foreach (var prepos in prelist)
            {
                if (prepos.BrandId == 1 || prepos.BrandId == 2 || prepos.BrandId == 4 || prepos.BrandId == 6 || prepos.BrandId == 7 || prepos.BrandId == 8 || prepos.BrandId == 10 || prepos.BrandId == 12)
                {
                    if (ProfitAmount > 200)
                    {
                        ProfitAmount -= 200;
                        PreSendStockDetail edit = db.PreSendStockDetail.FirstOrDefault(m => m.Id == prepos.Id);
                        if (edit != null)
                        {
                            edit.AuthFlag = 1;
                        }
                    }
                }
                else if (prepos.BrandId == 3 || prepos.BrandId == 5 || prepos.BrandId == 9 || prepos.BrandId == 11)
                {
                    if (ProfitAmount > 300)
                    {
                        ProfitAmount -= 300;
                        PreSendStockDetail edit = db.PreSendStockDetail.FirstOrDefault(m => m.Id == prepos.Id);
                        if (edit != null)
                        {
                            edit.AuthFlag = 1;
                        }
                    }
                }
            }
            UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == UserId);
            if (account == null)
            {
                account = db.UserAccount.Add(new UserAccount()
                {
                    Id = UserId,
                    UserId = UserId,
                }).Entity;
                db.SaveChanges();
            }
            account.ThisMonthPreAmount = PreProfitAmount;
            account.ValidPreAmount = ProfitAmount + account.PreTempAmountForBalance + account.PreTempAmount;
            if (index % 200 == 0)
            {
                db.SaveChanges();
            }
            Utils.WriteLog(index.ToString(), "计算小分仓额度日志");
        }
        db.SaveChanges();
    }
}