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

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


        public void Start()
        {
            Thread th = new Thread(Listen);
            th.IsBackground = true;
            th.Start();
        }
        
        private void Listen()
        { 
            while (true)
            {
                try
                {
                    DoSomething();
                }
                catch(Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "商户达标奖异常");
                }
                Thread.Sleep(600000);
            }
        }

        public void DoSomething()
        { 
            WebCMSEntities db = new WebCMSEntities();
            DateTime start = DateTime.Parse(DateTime.Now.AddMonths(-1).ToString("yyyy-MM") + "-01 00:00:00");
            DateTime end = DateTime.Parse(DateTime.Now.ToString("yyyy-MM") + "-01 00:00:00");
            string month = DateTime.Now.ToString("yyyyMM");
            function.WriteLog(DateTime.Now.ToString() + "-start", "达标奖励日志");
            var orders = db.MerchantDepositOrder.Where(m => m.Status > 0 && m.Version == 0 && m.UpdateDate >= start && m.UpdateDate < end).ToList();
            foreach(var order in orders)
            {
                function.WriteLog("MerchantId:" + order.MerchantId, "达标奖励日志");
                decimal TradeMoney = 0;
                bool has = db.MerchantAmountSummay.Any(m => m.MerchantId == order.MerchantId && m.IsAct == 1 && m.TradeMonth == month);
                if(has)
                {
                    TradeMoney = db.MerchantAmountSummay.Where(m => m.MerchantId == order.MerchantId && m.IsAct == 1 && m.TradeMonth == month).Sum(m => m.TradeAmount);
                }
                function.WriteLog("TradeMoney:" + TradeMoney, "达标奖励日志");
                if(TradeMoney >= 10000)
                {
                    RedisDbconn.Instance.AddList("StandardProfitQueue2", "{\"MerchantId\":\"" + order.MerchantId + "\",\"Prize\":\"50\"}");
                    MerchantDepositOrder edit = db.MerchantDepositOrder.FirstOrDefault(m => m.Id == order.Id);
                    if(edit != null)
                    {
                        edit.Version = 1;
                    }
                }
                db.SaveChanges();
            }
            function.WriteLog(DateTime.Now.ToString() + "-end", "达标奖励日志");
            db.Dispose();
        }





        public void StartThree()
        {
            Thread th = new Thread(ListenThree);
            th.IsBackground = true;
            th.Start();
        }
        
        private void ListenThree()
        { 
            while (true)
            {
                try
                {
                    DoSomethingThree();
                }
                catch(Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "商户连续3月达标奖异常");
                }
                Thread.Sleep(605000);
            }
        }

        public void DoSomethingThree()
        { 
            WebCMSEntities db = new WebCMSEntities();
            DateTime start = DateTime.Parse(DateTime.Now.AddMonths(-3).ToString("yyyy-MM") + "-01 00:00:00");
            DateTime end = DateTime.Parse(DateTime.Now.AddMonths(-2).ToString("yyyy-MM") + "-01 00:00:00");
            string month = DateTime.Now.AddMonths(-2).ToString("yyyyMM");
            string month2 = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            string month3 = DateTime.Now.ToString("yyyyMM");
            var orders = db.MerchantDepositOrder.Where(m => m.Status > 0 && m.Version == 1 && m.UpdateDate >= start && m.UpdateDate < end).ToList();
            foreach(var order in orders)
            {
                decimal TradeMoney = 0, TradeMoney2 = 0, TradeMoney3 = 0;
                bool has = db.MerchantAmountSummay.Any(m => m.MerchantId == order.MerchantId && m.IsAct == 1 && m.TradeMonth == month);
                if(has)
                {
                    TradeMoney = db.MerchantAmountSummay.Where(m => m.MerchantId == order.MerchantId && m.IsAct == 1 && m.TradeMonth == month).Sum(m => m.TradeAmount);
                }
                has = db.MerchantAmountSummay.Any(m => m.MerchantId == order.MerchantId && m.IsAct == 1 && m.TradeMonth == month2);
                if(has)
                {
                    TradeMoney2 = db.MerchantAmountSummay.Where(m => m.MerchantId == order.MerchantId && m.IsAct == 1 && m.TradeMonth == month2).Sum(m => m.TradeAmount);
                }
                has = db.MerchantAmountSummay.Any(m => m.MerchantId == order.MerchantId && m.IsAct == 1 && m.TradeMonth == month3);
                if(has)
                {
                    TradeMoney3 = db.MerchantAmountSummay.Where(m => m.MerchantId == order.MerchantId && m.IsAct == 1 && m.TradeMonth == month3).Sum(m => m.TradeAmount);
                }
                if(TradeMoney >= 10000 && TradeMoney2 >= 10000 && TradeMoney3 >= 10000)
                {
                    RedisDbconn.Instance.AddList("StandardProfitQueue2", "{\"MerchantId\":\"" + order.MerchantId + "\",\"Prize\":\"100\"}");
                    MerchantDepositOrder edit = db.MerchantDepositOrder.FirstOrDefault(m => m.Id == order.Id);
                    if(edit != null)
                    {
                        edit.Version = 2;
                    }
                }
                db.SaveChanges();
            }
            db.Dispose();
        }





        #region 达标奖励队列
        public void StartActive()
        { 
            Thread th = new Thread(StartListenActive);
            th.IsBackground = true;
            th.Start();
        }
        public void StartListenActive()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("StandardProfitQueue2");
                if (!string.IsNullOrEmpty(content))
                {
                    StartListenActiveDo(content);
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
        }
        public void StartListenActiveDo(string content)
        { 
            try
            {
                JsonData jsonObj = JsonMapper.ToObject(content);
                int MerchantId = int.Parse(jsonObj["MerchantId"].ToString());
                decimal Prize = decimal.Parse(jsonObj["Prize"].ToString());
                Models.KxsMain.WebCMSEntities kxsdb = new Models.KxsMain.WebCMSEntities();
                WebCMSEntities db = new WebCMSEntities();
                MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new MerchantInfo();                
                string IdBrand = merchant.UserId + "_0";
                UserMachineData userData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
                if (userData == null)
                {
                    userData = db.UserMachineData.Add(new UserMachineData()
                    {
                        IdBrand = IdBrand,
                    }).Entity;
                    db.SaveChanges();
                }
                userData.OtherProfit += Prize;
                db.SaveChanges();

                int GetUserId = merchant.UserId;
                Models.KxsMain.UserAccount account = kxsdb.UserAccount.FirstOrDefault(m => m.Id == GetUserId);
                if (account == null)
                {
                    account = kxsdb.UserAccount.Add(new Models.KxsMain.UserAccount()
                    {
                        Id = GetUserId,
                        UserId = GetUserId,
                    }).Entity;
                    kxsdb.SaveChanges();
                }
                decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                account.BalanceAmount += Prize;
                account.TotalAmount += Prize;
                decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                Models.KxsMain.UserAccountRecord userAccountRecord = kxsdb.UserAccountRecord.Add(new Models.KxsMain.UserAccountRecord()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,
                    UserId = GetUserId, //创客
                    ChangeType = 315, //变动类型
                    ChangeAmount = Prize, //变更金额
                    BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                    AfterTotalAmount = AfterTotalAmount, //变更后总金额
                    BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                    AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                    BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                    AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                }).Entity;
                kxsdb.SaveChanges();
                kxsdb.Dispose();
                db.Dispose();
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.ToString(), "达标奖励服务异常");
            }
        }
        #endregion

    }
}