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

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

        public void Start(JobMqMsg jobInfo)
        {
            string content = "";
            try
            {
                dosomething();
                // string Msg = "success";
                // jobInfo.Status = Msg == "success" ? 1 : 0;
                // jobInfo.Msg = Msg == "success" ? "执行完成" : Msg;
                // RabbitMQClient.Instance.SendMsg(Newtonsoft.Json.JsonConvert.SerializeObject(jobInfo), "PublicBack");
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrEmpty(content))
                {
                    Dictionary<string, string> data = new Dictionary<string, string>();
                    data.Add("ErrTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    data.Add("ErrMsg", ex.ToString());
                    function.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(data), "public_err");
                }
                else
                {
                    function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "public_service");
                }
            }
        }

        public void dosomething()
        {
            bool op = true;
            while (op)
            {
                int OrderId = RedisDbconn.Instance.RPop<int>("ConsumerOrdersStat");
                if (OrderId > 0)
                {
                    WebCMSEntities db = new WebCMSEntities();
                    using (var tran = db.Database.BeginTransaction())
                    {
                        try
                        {
                            ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == OrderId);
                            if (order != null)
                            {
                                int PayMode = order.PayMode;
                                decimal PayMoney = order.PayMoney;
                                string TradeMonth = order.UpdateDate.Value.ToString("yyyyMM");
                                string TradeDate = order.UpdateDate.Value.ToString("yyyyMMdd");
                                MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == order.MerchantId);
                                if (merchant != null)
                                {
                                    merchant.LastConsumeDate = order.UpdateDate;
                                    merchant.TotalConsumeCount += 1;
                                    merchant.TotalOrder += 1;
                                    merchant.TotalAmount += PayMoney;
                                    db.SaveChanges();

                                    RedisDbconn.Instance.AddNumber("TotalAmount:" + merchant.UserId, PayMoney);
                                    decimal TotalAmount = RedisDbconn.Instance.Get<decimal>("TotalAmount:" + merchant.UserId);
                                    RedisDbconn.Instance.AddNumber("TotalAmount:" + merchant.UserId + ":" + TradeMonth, PayMoney);
                                    // 微信/支付宝
                                    if (order.PayMode == 1)
                                    {
                                        RedisDbconn.Instance.AddInt("TotalOrder:Alipay:" + merchant.UserId + ":" + TradeMonth);
                                    }
                                    else if (order.PayMode == 2)
                                    {
                                        RedisDbconn.Instance.AddInt("TotalOrder:WeChat:" + merchant.UserId + ":" + TradeMonth);
                                    }
                                    // 活动、非活动
                                    if (order.IsAct == 1)
                                    {
                                        RedisDbconn.Instance.AddNumber("TotalAmount:Active:" + merchant.UserId + ":" + TradeMonth, PayMoney);
                                    }
                                    else
                                    {
                                        RedisDbconn.Instance.AddNumber("TotalAmount:UnActive:" + merchant.UserId + ":" + TradeMonth, PayMoney);
                                    }
                                    // 判断激活商户，从绑定音箱码开始，30天内，活动交易额满1000为激活
                                    int ActivationStatus = 0;
                                    if (merchant.BindStatus == 1 && merchant.BindDate > DateTime.Now.AddDays(-30) && TotalAmount >= 1000)
                                    {
                                        merchant.ActivationStatus = 1;
                                        merchant.ActivationDate = DateTime.Now;
                                        db.SaveChanges();
                                        ActivationStatus = 1;
                                        RedisDbconn.Instance.AddInt("ActMerchantCount:" + merchant.UserId + ":" + TradeMonth);
                                        RedisDbconn.Instance.AddInt("ActMerchantCount:" + merchant.UserId + ":" + TradeDate);
                                        RedisDbconn.Instance.AddInt("ActMerchantCount:" + merchant.UserId + ":" + PayMode + ":" + TradeMonth);
                                        RedisDbconn.Instance.AddInt("ActMerchantCount:" + merchant.UserId + ":" + PayMode + ":" + TradeDate);
                                    }

                                    // 遍历上级，累加团队数据
                                    int UserId = merchant.UserId;
                                    int Level = 0;
                                    while (UserId > 0)
                                    {
                                        Level += 1;
                                        Users user = db.Users.FirstOrDefault(m => m.Id == UserId);
                                        if (user != null)
                                        {
                                            if (Level >= 1)
                                            {
                                                RedisDbconn.Instance.AddNumber("TeamTotalAmount:" + UserId + ":" + TradeMonth, PayMoney);
                                                // 微信/支付宝
                                                if (order.PayMode == 1)
                                                {
                                                    RedisDbconn.Instance.AddInt("TeamTotalOrder:Alipay:" + UserId + ":" + TradeMonth);
                                                }
                                                else if (order.PayMode == 2)
                                                {
                                                    RedisDbconn.Instance.AddInt("TeamTotalOrder:WeChat:" + UserId + ":" + TradeMonth);
                                                }
                                                // 活动、非活动
                                                if (order.IsAct == 1)
                                                {
                                                    RedisDbconn.Instance.AddNumber("TeamTotalAmount:Active:" + UserId + ":" + TradeMonth, PayMoney);
                                                }
                                                else
                                                {
                                                    RedisDbconn.Instance.AddNumber("TeamTotalAmount:UnActive:" + UserId + ":" + TradeMonth, PayMoney);
                                                }

                                                // 创客的激活商户累计
                                                if (ActivationStatus == 1)
                                                { 
                                                    RedisDbconn.Instance.AddInt("ActMerchantCount:" + UserId + ":" + TradeMonth);
                                                    RedisDbconn.Instance.AddInt("ActMerchantCount:" + UserId + ":" + TradeDate);
                                                    RedisDbconn.Instance.AddInt("ActMerchantCount:" + UserId + ":" + PayMode + ":" + TradeMonth);
                                                    RedisDbconn.Instance.AddInt("ActMerchantCount:" + UserId + ":" + PayMode + ":" + TradeDate);
                                                }
                                            }
                                            UserId = user.ParentUserId;
                                        }
                                        else
                                        {
                                            UserId = 0;
                                        }
                                    }
                                    
                                    //创客所属商户交易额数据
                                    RedisDbconn.Instance.AddNumber("MerchantTradeAmount:" + order.MerchantId + ":" + TradeMonth, order.PayMoney);
                                    RedisDbconn.Instance.AddNumber("MerchantTradeAmount:" + order.MerchantId + ":" + TradeDate, order.PayMoney);
                                    List<string> TradeMonths = RedisDbconn.Instance.GetList<string>("MerchantTradeList:" + order.MerchantId + ":" + TradeMonth, 1, 1000);
                                    if (!TradeMonths.Contains(TradeDate))
                                    {
                                        RedisDbconn.Instance.AddList("MerchantTradeList:" + order.MerchantId + ":" + TradeMonth, TradeDate);
                                    }
                                }
                                tran.Commit();
                            }
                        }
                        catch (Exception ex)
                        {
                            tran.Rollback();
                            function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "public_service");
                        }
                    }
                    db.Dispose();
                }
                else
                {
                    op = false;
                }
            }
        }

        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);
        }
    }
}