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

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

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

        // 统计数据条件
        // 1.下单成功统计当前直推并未开机的创客表数据
        // 2.推荐创客认证成功，统计直推创客表数据
        // 3.机具激活，统计激活机具交易表
        // 4.交易，统计激活机具交易表
        public void dosomething()
        {
            while (true)
            {
                string data = RedisDbconn.Instance.RPop<string>("RecommendActStatQueue");
                if (!string.IsNullOrEmpty(data))
                {
                    try
                    {
                        JsonData jsonObj = JsonMapper.ToObject(data);
                        string Kind = jsonObj["Kind"].ToString(); //数据类型：1-购买推荐王订单，2-用户认证，3-机具激活，4-机具交易
                        JsonData jsonData = jsonObj["Data"];
                        WebCMSEntities db = new WebCMSEntities();
                        if(Kind == "1")
                        {
                            int UserId = int.Parse(jsonData["UserId"].ToString());
                            string TradeMonth = jsonData["TradeMonth"].ToString();
                            DateTime StartTime = DateTime.Parse(TradeMonth.Substring(0, 4) + "-" + TradeMonth.Substring(4, 2) + "-01 00:00:00");
                            DateTime EndTime = StartTime.AddMonths(1);
                            List<Users> users = db.Users.Where(m => m.ParentUserId == UserId && m.AuthFlag == 1).ToList();
                            foreach(Users user in users)
                            {
                                bool posCheck = db.PosMachinesTwo.Any(m => m.BuyUserId == user.Id && m.ActivationState == 1 && m.ActivationTime < StartTime);
                                if(!posCheck)
                                {
                                    bool check = db.RecommendDirectUser.Any(m => m.UserId == UserId && m.DirectUserId == user.Id && m.TradeMonth == TradeMonth);
                                    if(!check)
                                    {
                                        db.RecommendDirectUser.Add(new RecommendDirectUser()
                                        {
                                            CreateDate = DateTime.Now,
                                            UserId = UserId,
                                            DirectUserId = user.Id,
                                            TradeMonth = TradeMonth,
                                        });
                                        db.SaveChanges();
                                    }
                                    var poslist = db.PosMachinesTwo.Select(m => new { m.BuyUserId, m.BindMerchantId, m.PosSn, m.ActivationState, m.ActivationTime }).Where(m => m.BuyUserId == user.Id && m.ActivationState == 1 && m.ActivationTime >= StartTime && m.ActivationTime < EndTime).ToList();
                                    foreach(var pos in poslist)
                                    {
                                        bool chk = db.RecommendTradeSummary.Any(m => m.UserId == user.Id && m.TradeMonth == TradeMonth && m.PosSn == pos.PosSn);
                                        if(!chk)
                                        {
                                            PosMerchantTradeSummay tradeSummay = db.PosMerchantTradeSummay.FirstOrDefault(m => m.MerchantId == pos.BindMerchantId && m.TradeMonth == TradeMonth) ?? new PosMerchantTradeSummay();
                                            db.RecommendTradeSummary.Add(new RecommendTradeSummary()
                                            {
                                                CreateDate = DateTime.Now,
                                                UserId = user.Id,
                                                TradeMonth = TradeMonth,
                                                PosSn = pos.PosSn,
                                                TradeAmount = tradeSummay.TradeAmount,
                                            });
                                            db.SaveChanges();
                                        }
                                    }
                                }
                            }
                        }
                        else if(Kind == "2")
                        {
                            int UserId = int.Parse(jsonData["UserId"].ToString());
                            int DirectUserId = int.Parse(jsonData["DirectUserId"].ToString());
                            string TradeMonth = jsonData["TradeMonth"].ToString();
                            bool check = db.RecommendDirectUser.Any(m => m.UserId == UserId && m.DirectUserId == DirectUserId && m.TradeMonth == TradeMonth);
                            if(!check)
                            {
                                db.RecommendDirectUser.Add(new RecommendDirectUser()
                                {
                                    CreateDate = DateTime.Now,
                                    UserId = UserId,
                                    DirectUserId = DirectUserId,
                                    TradeMonth = TradeMonth,
                                });
                                db.SaveChanges();
                            }
                        }
                        else if(Kind == "3")
                        {
                            int UserId = int.Parse(jsonData["UserId"].ToString());
                            int PosId = int.Parse(jsonData["PosId"].ToString());
                            string TradeMonth = jsonData["TradeMonth"].ToString();
                            PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == PosId);
                            if(pos != null)
                            {
                                bool chk = db.RecommendTradeSummary.Any(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.PosSn == pos.PosSn);
                                if(!chk)
                                {
                                    PosMerchantTradeSummay tradeSummay = db.PosMerchantTradeSummay.FirstOrDefault(m => m.MerchantId == pos.BindMerchantId && m.TradeMonth == TradeMonth) ?? new PosMerchantTradeSummay();
                                    db.RecommendTradeSummary.Add(new RecommendTradeSummary()
                                    {
                                        CreateDate = DateTime.Now,
                                        UserId = UserId,
                                        TradeMonth = TradeMonth,
                                        PosSn = pos.PosSn,
                                        TradeAmount = tradeSummay.TradeAmount,
                                    });
                                    db.SaveChanges();
                                }
                            }
                        }
                        else if(Kind == "4")
                        {
                            int PosId = int.Parse(jsonData["PosId"].ToString());
                            string TradeMonth = jsonData["TradeMonth"].ToString();
                            decimal TradeAmount = decimal.Parse(jsonData["TradeAmount"].ToString());
                            PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == PosId);
                            if(pos != null)
                            {
                                RecommendTradeSummary tradeSummay = db.RecommendTradeSummary.FirstOrDefault(m => m.PosSn == pos.PosSn && m.TradeMonth == TradeMonth);
                                if(tradeSummay != null)
                                {
                                    tradeSummay.TradeAmount += TradeAmount;
                                    db.SaveChanges();
                                }
                            }
                        }
                        db.Dispose();
                    }
                    catch (Exception ex)
                    {
                        function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "推荐王数据统计异常");
                    }
                    Thread.Sleep(100);
                }
                else
                {
                    Thread.Sleep(600);
                }
            }
        }
    }
}