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

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

    public void StartEverDay()
    { 
        OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].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)
    {
        LogHelper.Instance.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)
        {
            LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "统计商户的交易额");
        }
        db.Dispose();
        LogHelper.Instance.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行商户交易额日志");
    }

}