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

namespace MySystem
{
    public class RecommandKingHelper
    {
        public readonly static RecommandKingHelper Instance = new RecommandKingHelper();
        private RecommandKingHelper()
        { }
    
    
        public void Start()
        {
            Thread th = new Thread(StartFor);
            th.IsBackground = true;
            th.Start();
        }
        public void StartFor()
        {
            while (true)
            {
                if(DateTime.Now.Hour > 0 && DateTime.Now.Hour < 6)
                {
                    Recommend();
                }
                Thread.Sleep(600000);
            }
        }
        public void Recommend()
        {
            string today = DateTime.Now.ToString("yyyy-MM-dd");
            string checkFlag = function.ReadInstance("/RecommandKing/" + today + ".txt");
            if(!string.IsNullOrEmpty(checkFlag))
            {
                function.WritePage("/RecommandKing/", today + ".txt", DateTime.Now.ToString());
            }
            List<int> Historys = new List<int>();
            Historys.Add(565);
            Historys.Add(139473);
            Historys.Add(173790);
            Historys.Add(174506);
            string TradeMonth = DateTime.Now.AddMonths(-0).ToString("yyyyMM");
            DateTime check = DateTime.Parse("2023-10-01 00:00:00");
            DateTime start = DateTime.Parse(DateTime.Now.AddMonths(-0).ToString("yyyy-MM") + "-01 00:00:00");
            DateTime end = start.AddMonths(1);
            CustomerSqlConn.op("delete from RecommendDirectUser where TradeMonth='" + TradeMonth + "'", MysqlConn.SqlConnStr);
            string PreTradeMonth = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            List<int> ProductIds = new List<int>();
            ProductIds.Add(10);
            ProductIds.Add(11);
            ProductIds.Add(77);
            ProductIds.Add(78);
            ProductIds.Add(79);
            ProductIds.Add(27);
            ProductIds.Add(28);
            ProductIds.Add(39);
            ProductIds.Add(40);
            WebCMSEntities db = new WebCMSEntities();
            ReadModels.WebCMSEntities readdb = new ReadModels.WebCMSEntities();
            //统计当月下单名单
            List<int> uids = readdb.Orders.Where(m => m.PayDate >= check && m.Status > 0 && m.Sort == 0 && ProductIds.Contains(m.ProductId)).ToList().Select(m => m.UserId).Distinct().ToList();
            foreach(int uid in uids)
            {
                int ActCount = 0;
                if(ActCount == 0)
                {
                    if(readdb.UserTradeMonthSummary.Any(m => m.UserId == uid && m.TradeMonth == TradeMonth && m.SeoTitle == "team" && m.BrandId != 14))
                    {
                        ActCount += readdb.UserTradeMonthSummary.Where(m => m.UserId == uid && m.TradeMonth == TradeMonth && m.SeoTitle == "team" && m.BrandId != 14).Sum(m => m.ActiveBuddyMerStatus);
                    }
                }
                if(ActCount == 0)
                {
                    MpMainModels.WebCMSEntities mpdb = new MpMainModels.WebCMSEntities();
                    ActCount += mpdb.MerchantDepositOrder.Count(m => m.UserId == uid && m.CreateDate >= start && m.CreateDate < end && m.Status > 0 && m.UserId == uid);
                    mpdb.Dispose();
                }
                if(ActCount == 0)
                {
                    MpMainModels2.WebCMSEntities mpdb = new MpMainModels2.WebCMSEntities();
                    ActCount += mpdb.MerchantDepositOrder.Count(m => m.UserId == uid && m.CreateDate >= start && m.CreateDate < end && m.Status > 0 && m.UserId == uid);
                    mpdb.Dispose();
                }
                if(ActCount > 0)
                {
                    Users user = db.Users.FirstOrDefault(m => m.Id == uid);
                    if(user != null)
                    {
                        string ParentNav = user.ParentNav;
                        if(!string.IsNullOrEmpty(ParentNav))
                        {
                            string[] ParentNavList = ParentNav.Replace(",,", ",").Trim(',').Split(',');
                            Array.Reverse(ParentNavList);
                            bool PassFlag = true;
                            foreach(string UserIdString in ParentNavList)
                            {
                                int UserId = int.Parse(UserIdString);
                                //判断是否历史达标创客
                                if(PassFlag)
                                {
                                    if(db.RecommendDirectUser.Any(m => m.UserId == UserId && m.TradeMonth != TradeMonth && m.QueryCount >= 50) || Historys.Contains(UserId))
                                    {
                                        PassFlag = false;
                                    }
                                }
                                if(PassFlag)
                                {
                                    RecommendDirectUser item = db.RecommendDirectUser.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth);
                                    if(item == null)
                                    {
                                        item = db.RecommendDirectUser.Add(new RecommendDirectUser()
                                        {
                                            UserId = UserId,
                                            TradeMonth = TradeMonth,
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    item.QueryCount += 1;
                                    db.SaveChanges();
                                }
                                //判断上月交易额是否满3000W
                                if(PassFlag)
                                {
                                    if(GetTradeAmt(UserId, PreTradeMonth) >= 30000000)
                                    {
                                        PassFlag = false;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            db.Dispose();
            readdb.Dispose();
        }

        public decimal GetTradeAmt(int UserId, string TradeMonth)
        {
            ReadModels.WebCMSEntities rdb = new ReadModels.WebCMSEntities();
            MpMainModels.WebCMSEntities mpmaindb = new MpMainModels.WebCMSEntities();
            MpMainModels2.WebCMSEntities mpmaindb2 = new MpMainModels2.WebCMSEntities();
            decimal TradeAmount = 0;
            //创客团队交易额
            bool check = rdb.TradeDaySummary.Any(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.SeoTitle == "team");
            if (check)
            {
                TradeAmount += rdb.TradeDaySummary.Where(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.SeoTitle == "team").Sum(m => m.HelpNonDirectTradeAmt + m.HelpNonDirectDebitTradeAmt + m.NotHelpNonDirectTradeAmt + m.NotHelpNonDirectDebitTradeAmt + m.ProfitNonDirectTradeAmt + m.ProfitNonDirectDebitTradeAmt);
            }
            check = rdb.TradeDaySummary2.Any(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.SeoTitle == "team");
            if (check)
            {
                TradeAmount += rdb.TradeDaySummary2.Where(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.SeoTitle == "team").Sum(m => m.ProfitTradeAmt + m.ProfitDebitTradeAmt);
            }
            //码牌团队交易额（直联）
            check = mpmaindb.UserAmountSummary.Any(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.SeoTitle == "team");
            if (check)
            {
                TradeAmount += mpmaindb.UserAmountSummary.Where(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.SeoTitle == "team" && m.IsAct == 1).Sum(m => m.TotalAmount) * 4;
            }
            //码牌团队交易额（银联）
            check = mpmaindb2.UserAmountSummary.Any(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.SeoTitle == "team");
            if (check)
            {
                TradeAmount += mpmaindb2.UserAmountSummary.Where(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.SeoTitle == "team" && m.IsAct == 1).Sum(m => m.TotalAmount) * 4;
            }
            //广电卡扶持期按1万/张计入职级
            check = rdb.UserTradeMonthSummary.Any(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.SeoTitle == "team" && m.BrandId == 14);
            if (check)
            {
                TradeAmount += rdb.UserTradeMonthSummary.Where(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.SeoTitle == "team" && m.BrandId == 14).Sum(m => m.ActiveBuddyMerStatus) * 10000;
            }
            return TradeAmount;
        }
    }
}