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

public class TestHelper
{
    public readonly static TestHelper Instance = new TestHelper();
    private TestHelper()
    {
    }
    
    public void Start()
    {
        Thread th = new Thread(tmpgo);
        th.IsBackground = true;
        th.Start();
    }

    public void StartEverDay()
    { 
        OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["Pxc1SqlConnStr"].ToString();
        DateTime end = DateTime.Parse("2022-04-19 00:00:00");
        DateTime check = DateTime.Parse("2022-03-11");
        while (check <= end)
        {
            StatMerchantTrade(check.ToString("yyyy-MM-dd"));
            check = check.AddDays(1);
        }
    }

    private void StatMerchantTrade(string date)
    {
        Utils.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "执行商户交易额日志");
        WebCMSEntities db = new WebCMSEntities();
        try
        {
            DataTable selfdt = OtherMySqlConn.dtable("select MerchantId,BrandId,DATE_FORMAT(CreateDate,'%Y-%m-%d') as TradeDate,sum(TradeAmount) as TradeAmount from TradeRecord group by MerchantId,BrandId,DATE_FORMAT(CreateDate,'%Y-%m-%d') order by MerchantId,BrandId,DATE_FORMAT(CreateDate,'%Y-%m-%d')");
            foreach (DataRow selfDr in selfdt.Rows)
            {
                int BrandId = int.Parse(selfDr["BrandId"].ToString());
                int MerchantId = int.Parse(selfDr["MerchantId"].ToString());
                string TradeDate = selfDr["TradeDate"].ToString();
                TradeDate = TradeDate.Replace("-", "");
                string TradeMonth = TradeDate.Substring(0, 6);
                decimal TradeAmount = decimal.Parse(selfDr["TradeAmount"].ToString());
                PosMerchantTradeSummay merStat = db.PosMerchantTradeSummay.FirstOrDefault(m => m.MerchantId == MerchantId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId);
                if (merStat == null)
                {
                    merStat = db.PosMerchantTradeSummay.Add(new PosMerchantTradeSummay()
                    {
                        MerchantId = MerchantId,
                        TradeMonth = TradeMonth,
                        TradeDate = TradeDate,
                        BrandId = BrandId,
                    }).Entity;
                    db.SaveChanges();
                }
                merStat.TradeAmount += TradeAmount;
                db.SaveChanges();
            }
        }
        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", "执行商户交易额日志");
    }

    private void setLdFee()
    {
        // DataTable dt = CustomerSqlConn.dtable("select KqMerNo,BrandId from PosMerchantInfo where Id in (select BindMerchantId from PosMachinesTwo where BrandId in (10,11) and DownFeeFlag=1 and BindingTime<'2023-08-06 00:00:00')", "server=rm-2vcs4j67tla603c9d5o.mysql.cn-chengdu.rds.aliyuncs.com;port=3306;user=KxsProfitServer;password=FrW8ZfxlcaVdm1r0;database=KxsProfitServer;charset=utf8;");
        // foreach(DataRow dr in dt.Rows)
        // {
        //     Utils.WriteLog(dr["KqMerNo"].ToString(), "临时设置联动费率日志");
        //     string result = SetDepositPostService.Instance.LDFeeRate(dr["KqMerNo"].ToString(), "0.0063", int.Parse(dr["BrandId"].ToString()), 0);
        //     Utils.WriteLog(result + "\n\n", "临时设置联动费率日志");
        // }

        // Utils.WriteLog("000006026200825805", "临时设置费率日志");
        // string result = SetDepositPostService.Instance.SetFeeForSft("40585414", "0.6300", "0");
        // Utils.WriteLog(result + "\n\n", "临时设置费率日志");

        // Utils.WriteLog("0000320226626450030145", "临时设置费率日志");
        // result = SetDepositPostService.Instance.LDFeeRate("110000004265069", "0.0063", 1, 3);
        // Utils.WriteLog(result + "\n\n", "临时设置费率日志");
        // Utils.WriteLog("0000320226624650409066", "临时设置费率日志");
        // result = SetDepositPostService.Instance.LDFeeRate("110000004842951", "0.0063", 1, 3);
        // Utils.WriteLog(result + "\n\n", "临时设置费率日志");

        // Utils.WriteLog("0000320226636450184893", "临时设置费率日志");
        // result = SetDepositPostService.Instance.LDFeeRate("110000004744970", "0.0063", 3, 0);
        // Utils.WriteLog(result + "\n\n", "临时设置费率日志");
        // Utils.WriteLog("0000320226636450180288", "临时设置费率日志");
        // result = SetDepositPostService.Instance.LDFeeRate("110000004760326", "0.0063", 3, 0);
        // Utils.WriteLog(result + "\n\n", "临时设置费率日志");
        
        // Utils.WriteLog("00003102702303069483466", "临时设置费率日志");
        // string result = SetDepositPostService.Instance.SetFee("M7000615224RVXMbk7", "00003102702303069483466", 0.63M, 300);
        // Utils.WriteLog(result + "\n\n", "临时设置费率日志");
        // Utils.WriteLog("00000302JBNL01471793", "临时设置费率日志");
        // result = SetDepositPostService.Instance.SetFee("M900065131JVMYUBl5", "00000302JBNL01471793", 0.63M, 0);
        // Utils.WriteLog(result + "\n\n", "临时设置费率日志");

        // return;
        bool op = true;
        while(op)
        {
            int page = int.Parse(function.CheckInt(function.ReadInstance("/TmpSetLdFee/page.txt")));
            if(page < 1) page = 50;
            int skip = (page - 1) * 100;
            DataTable dt = CustomerSqlConn.dtable("select KqMerNo,BrandId from PosMerchantInfo where Id in (select BindMerchantId from PosMachinesTwo where BrandId in (10,11) and DownFeeFlag=0 and BindingTime<'2023-08-06 00:00:00') limit " + skip + ",100", "server=rm-2vcs4j67tla603c9d5o.mysql.cn-chengdu.rds.aliyuncs.com;port=3306;user=KxsProfitServer;password=FrW8ZfxlcaVdm1r0;database=KxsProfitServer;charset=utf8;");
            if(dt.Rows.Count > 0)
            {
                foreach(DataRow dr in dt.Rows)
                {
                    Utils.WriteLog(dr["KqMerNo"].ToString(), "临时设置联动费率日志");
                    string result = SetDepositPostService.Instance.LDFeeRate(dr["KqMerNo"].ToString(), "0.0063", int.Parse(dr["BrandId"].ToString()), 3);
                    Utils.WriteLog(result + "\n\n", "临时设置联动费率日志");
                }
                page += 1;
                function.WritePage("/TmpSetLdFee/", "page.txt", page.ToString());
            }
            else
            {
                op = false;
                Utils.WriteLog("执行结束\n\n", "临时设置联动费率日志");
            }
            dt.Dispose();
            dt.Clear();
        }
    }



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

    private void setJkFee()
    {
        bool op = true;
        while(op)
        {
            int page = int.Parse(function.CheckInt(function.ReadInstance("/TmpSetJkFee/page.txt")));
            if(page < 1) page = 1;
            int skip = (page - 1) * 100;
            DataTable dt = CustomerSqlConn.dtable("select KqMerNo,KqSnNo from PosMerchantInfo where Id in (select BindMerchantId from PosMachinesTwo where BrandId in (1,3) and (DownFeeFlag=1 or UpFeeFlag=0) and BindingState=1 and BindingTime<'" + DateTime.Now.AddDays(-90).ToString("yyyy-MM-dd HH:mm:ss") + "') limit " + skip + ",100", "server=rm-2vcs4j67tla603c9d5o.mysql.cn-chengdu.rds.aliyuncs.com;port=3306;user=KxsProfitServer;password=FrW8ZfxlcaVdm1r0;database=KxsProfitServer;charset=utf8;");
            if(dt.Rows.Count > 0)
            {
                foreach(DataRow dr in dt.Rows)
                {
                    Utils.WriteLog(dr["KqMerNo"].ToString(), "临时设置金控费率日志");
                    Utils.WriteLog(dr["KqSnNo"].ToString(), "临时设置金控费率日志");
                    string merNo = dr["KqMerNo"].ToString();
                    string sn = dr["KqSnNo"].ToString();
                    string result = SetDepositPostService.Instance.SetFee(merNo, sn, 0.63M, 0);
                    Utils.WriteLog(result + "\n\n", "临时设置金控费率日志");
                }
                page += 1;
                function.WritePage("/TmpSetJkFee/", "page.txt", page.ToString());
            }
            else
            {
                op = false;
                Utils.WriteLog("执行结束\n\n", "临时设置金控费率日志");
            }
            dt.Dispose();
            dt.Clear();
        }
    }


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

    private void setSftFee()
    {
        bool op = true;
        while(op)
        {
            int page = int.Parse(function.CheckInt(function.ReadInstance("/TmpSetSftFee/page.txt")));
            if(page < 1) page = 1;
            int skip = (page - 1) * 100;
            DataTable dt = CustomerSqlConn.dtable("select mer.KqMerNo,DownFeeFlag,UpFeeFlag from (select BindMerchantId,DownFeeFlag,UpFeeFlag from PosMachinesTwo where BrandId=7 and BindingState=1 and BindingTime<'" + DateTime.Now.AddDays(-90).ToString("yyyy-MM-dd HH:mm:ss") + "') tb left join PosMerchantInfo mer on tb.BindMerchantId=mer.Id limit " + skip + ",100", "server=rm-2vcs4j67tla603c9d5o.mysql.cn-chengdu.rds.aliyuncs.com;port=3306;user=KxsProfitServer;password=FrW8ZfxlcaVdm1r0;database=KxsProfitServer;charset=utf8;");
            if(dt.Rows.Count > 0)
            {
                foreach(DataRow dr in dt.Rows)
                {
                    Utils.WriteLog(dr["KqMerNo"].ToString(), "临时设置盛付通费率日志");
                    string merNo = dr["KqMerNo"].ToString();
                    string DownFeeFlag = dr["DownFeeFlag"].ToString();
                    string UpFeeFlag = dr["UpFeeFlag"].ToString();
                    string addRate = "0";
                    string Fee = "0.6300";
                    if(UpFeeFlag == "1" && DownFeeFlag == "0")
                    {
                        addRate = "3";
                    }
                    string result = SetDepositPostService.Instance.SetFeeForSft(merNo, Fee, addRate);
                    Utils.WriteLog(result + "\n\n", "临时设置盛付通费率日志");
                }
                page += 1;
                function.WritePage("/TmpSetSftFee/", "page.txt", page.ToString());
            }
            else
            {
                op = false;
                Utils.WriteLog("执行结束\n\n", "临时设置盛付通费率日志");
            }
            dt.Dispose();
            dt.Clear();
        }
    }



    List<string> PosSns = new List<string>();
    public void leaderflag()
    {
        WebCMSEntities db = new WebCMSEntities();
        List<int> ids = new List<int>();
        // List<PosCouponRecord> records = db.PosCouponRecord.Where(m => m.FromUserId == 597).ToList();
        // foreach(PosCouponRecord record in records)
        // {
        //     ids.Add(record.PosCouponId);
        // }
        ids.Add(37335);
        PosSns = db.PosCoupons.Where(m => ids.Contains(m.Id) && m.IsUse == 1).ToList().Select(m => m.ExchangeCode).ToList();
        List<PosCoupons> coupons = db.PosCoupons.Where(m => ids.Contains(m.Id) && m.IsUse == 1).ToList();
        foreach (PosCoupons coupon in coupons)
        {
            ChildNo(db, coupon.ExchangeCode, coupon.ExchangeCode, coupon.OpenPrizeUserId);
        }
        // db.SaveChanges();
        db.Dispose();
    }
    List<string> nos = new List<string>();
    private void ChildNo(WebCMSEntities db, string RootCheckNo, string CheckNo, int LeaderUserId)
    {
        MachineApply apply = db.MachineApply.FirstOrDefault(m => m.SwapSnExpand.Contains(CheckNo));
        if(apply != null)
        {
            int len = 0;
            string[] SnList = apply.SwapSnExpand.TrimEnd('\n').Split('\n');
            foreach(string sn in SnList)
            {
                if(PosSns.Contains(sn.Split(':')[0]) || nos.Contains(sn.Split(':')[0]))
                {
                    len += 1;
                }
            }
            Orders order = db.Orders.FirstOrDefault(m => m.Id == apply.QueryCount);
            if(order != null)
            {
                if(!string.IsNullOrEmpty(order.SnNos))
                {
                    if(order.SnNos.Contains(","))
                    {
                        string[] SwapSnExpands = order.SnNos.TrimEnd(',').Split(',');
                        int index = 0;
                        foreach(string no in SwapSnExpands)
                        {
                            if(!nos.Contains(no) && index < len)
                            {
                                index += 1;
                                nos.Add(no);
                                ChildNo(db, RootCheckNo, no, LeaderUserId);
                            }
                        }
                    }
                    else
                    {
                        string[] SwapSnExpands = order.SnNos.TrimEnd('\n').Split('\n');
                        int index = 0;
                        foreach(string no in SwapSnExpands)
                        {
                            if(!nos.Contains(no) && index < len)
                            {
                                index += 1;
                                nos.Add(no);
                                ChildNo(db, RootCheckNo, no, LeaderUserId);
                            }
                        }
                    }
                }
                else
                {
                    MachineForSnNo forSnNo = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == CheckNo) ?? new MachineForSnNo();
                    PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == forSnNo.SnId);
                    if(pos != null)
                    {
                        // pos.LeaderUserId = LeaderUserId;
                        // Utils.WriteLog(LeaderUserId + ":" + pos.PosSn + ":" + apply.SwapSnExpand.TrimEnd('\n').Split('\n').Length, "大盟主奖励标记机具");
                        // Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId) ?? new Users();
                        // Utils.WriteLog(pos.PosSn + ":" + RootCheckNo + ":" + user.MakerCode + ":" + user.RealName, "大盟主奖励标记机具");
                        Utils.WriteLog(pos.Id + ":" + LeaderUserId, "开机奖励标记机具");
                    }
                }
            }
        }
        else
        {
            MachineForSnNo forSnNo = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == CheckNo) ?? new MachineForSnNo();
            PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m=>m.Id == forSnNo.SnId);
            if(pos != null)
            {
                // pos.LeaderUserId = LeaderUserId;
                // Utils.WriteLog(LeaderUserId + ":" + pos.PosSn, "大盟主奖励标记机具");
                // Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId) ?? new Users();
                // Utils.WriteLog(pos.PosSn + ":" + RootCheckNo + ":" + user.MakerCode + ":" + user.RealName, "大盟主奖励标记机具");
                Utils.WriteLog(pos.Id + ":" + LeaderUserId, "开机奖励标记机具");
            }
        }
    }

    public void tmpdo()
    {
        string check = function.ReadInstance("/tmpdo.txt");
        if(!string.IsNullOrEmpty(check))
        {
            return;
        }
        function.WritePage("/", "tmpdo.txt", DateTime.Now.ToString());
        WebCMSEntities db = new WebCMSEntities();
        List<string> list = new List<string>();
        list.Add("2024-10-19 21:04:55,119.00,360,1182462634");
        List<int> bids = new List<int>();
        bids.Add(23);
        bids.Add(24);
        bids.Add(25);
        bids.Add(26);
        bids.Add(32);
        List<Users> users = db.Users.Where(m => m.AuthFlag == 1).ToList();
        Utils.WriteLog("1--" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "统计来量吧漏掉的交易");
        List<PosMachinesTwo> posList = db.PosMachinesTwo.Where(m => bids.Contains(m.BrandId)).ToList();
        Utils.WriteLog("2--" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "统计来量吧漏掉的交易");
        List<WifiTradeRecord> tradeList = db.WifiTradeRecord.ToList();
        Utils.WriteLog("3--" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "统计来量吧漏掉的交易");
        List<TradeDaySummary> statList = db.TradeDaySummary.Where(m => m.Id >= 22361221 && bids.Contains(m.BrandId)).ToList();
        Utils.WriteLog("4--" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "统计来量吧漏掉的交易");
        statNew = new List<TradeDaySummary>();
        foreach(string sub in list)
        {
            string[] data = sub.Split(',');
            string PosSn = data[3];
            DateTime TradeTime = DateTime.Parse(data[0]);
            decimal TradeAmount = decimal.Parse(data[1]);
            int Months = int.Parse(data[2]) / 30;
            decimal TradeAmt = TradeAmount / Months;
            TradeAmt = PublicFunction.NumberFormat(TradeAmt);
            string TradeMonth = TradeTime.AddMonths(-1).ToString("yyyyMM");
            PosMachinesTwo pos = posList.FirstOrDefault(m => m.PosSn == PosSn) ?? new PosMachinesTwo();
            bool statFlag = tradeList.Any(m => m.SnNo == PosSn && m.CreateDate < TradeTime);
            if(statFlag)
            {
                TradeDaySummary stat = statList.Where(m => m.UserId == pos.BuyUserId && m.BrandId == pos.BrandId).OrderByDescending(m => m.Id).FirstOrDefault() ?? new TradeDaySummary();
                TradeMonth = string.IsNullOrEmpty(stat.TradeMonth) ? TradeTime.AddMonths(-1).ToString("yyyyMM") : stat.TradeMonth;
            }
            DateTime StartMonth = DateTime.Parse(TradeMonth.Substring(0, 4) + "-" + TradeMonth.Substring(4, 2) + "-01 00:00:00");
            for (int i = 1; i <= Months; i++)
            {
                StartMonth = StartMonth.AddMonths(1);
                StatTrade(users, pos.BuyUserId, pos.BrandId, StartMonth.ToString("yyyyMM"), TradeAmt);
            }
            Utils.WriteLog(sub, "统计来量吧漏掉的交易");
        }
        int index = 0;
        foreach(TradeDaySummary subData in statNew)
        {
            index += 1;
            if(index > 8740)
            {
                RedisDbconn.Instance.AddList("TmpAddTradeDaySummaryQueue", subData);
                Utils.WriteLog(index.ToString(), "统计来量吧漏掉的交易");
            }
        }
        db.Dispose();
        Utils.WriteLog("end", "统计来量吧漏掉的交易");
    }

    public void tmpgo()
    {
        WebCMSEntities db = new WebCMSEntities();
        bool op = true;
        int index = 0;
        while(op)
        {
            TradeDaySummary trade = RedisDbconn.Instance.RPop<TradeDaySummary>("TmpAddTradeDaySummaryQueue");
            if(trade != null)
            {
                index += 1;
                db.TradeDaySummary.Add(trade);
                if(index % 20 == 0)
                {
                    db.SaveChanges();
                }
            }
            else
            {
                op = false;
            }
        }
        db.Dispose();
    }

    List<TradeDaySummary> statNew = new List<TradeDaySummary>();
    public void StatTrade(List<Users> users, int UserId, int BrandId, string TradeMonth, decimal TradeAmount)
    {
        Users user = users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
        string ParentNav = user.ParentNav;
        string TradeDate = TradeMonth + "01";
        ParentNav += "," + UserId + ",";

        TradeDaySummary selfStat = statNew.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.SeoTitle == "self");
        if (selfStat == null)
        {
            statNew.Add(new TradeDaySummary()
            {
                UserId = UserId,
                TradeMonth = TradeMonth,
                TradeDate = TradeDate,
                BrandId = BrandId,
                SeoTitle = "self",
                HelpDirectTradeAmt = TradeAmount
            });
        }
        else
        {
            selfStat.HelpDirectTradeAmt += TradeAmount;
        }
        if (!string.IsNullOrEmpty(ParentNav))
        {
            string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
            foreach (string NavUserIdString in ParentNavList)
            {
                int NavUserId = int.Parse(NavUserIdString);
                TradeDaySummary teamStat = statNew.FirstOrDefault(m => m.UserId == NavUserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.SeoTitle == "team");
                if (teamStat == null)
                {
                    statNew.Add(new TradeDaySummary()
                    {
                        UserId = NavUserId,
                        TradeMonth = TradeMonth,
                        TradeDate = TradeDate,
                        BrandId = BrandId,
                        SeoTitle = "team",
                        HelpNonDirectTradeAmt = TradeAmount
                    });
                }
                else
                {
                    teamStat.HelpNonDirectTradeAmt += TradeAmount;
                }
            }
        }
    }

}