using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using MySystem.Models;
using Library;
using System.Threading;
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;

namespace MySystem
{
    public class HelpProfitHelper
    {
        public readonly static HelpProfitHelper Instance = new HelpProfitHelper();
        private HelpProfitHelper()
        {
        }
        
        public void Start()
        {
            Thread th = new Thread(StartFor);
            th.IsBackground = true;
            th.Start();
        }
        public void StartFor()
        {
            while (true)
            {
                if(DateTime.Now.Day == 1 && DateTime.Now.Hour >= 2 && DateTime.Now.Hour <= 3)
                {
                    StatProfitEveryDay(DateTime.Now.AddMonths(-1).ToString("yyyyMM"));
                }
                Thread.Sleep(600000);
            }
        }
        // public void StatProfitEveryDay(string Month)
        // {
        //     // string check = function.ReadInstance("/HelpProfitStat/" + Month + ".txt");
        //     // if (!string.IsNullOrEmpty(check))
        //     // {
        //     //     return;
        //     // }
        //     // function.WritePage("/HelpProfitStat/", Month + ".txt", DateTime.Now.ToString());
        //     WebCMSEntities db = new WebCMSEntities();
        //     var orders = db.Orders.Select(m => new { m.UserId, m.Status, m.ProductId }).Where(m => m.Status > 0 && m.ProductId == 34).ToList();
        //     int StartId = 0;
        //     bool op = true;
        //     while(op)
        //     {
        //         List<HelpProfitMerTradeSummay> list = db.HelpProfitMerTradeSummay.Where(m => m.Id > StartId && m.TradeMonth == Month).OrderBy(m => m.Id).Take(50).ToList();
        //         if(list.Count > 0)
        //         {
        //             LogHelper.Instance.WriteLog("开始：" + DateTime.Now.ToString(), "助利宝分润日志");
        //             LogHelper.Instance.WriteLog("总数：" + list.Count(), "助利宝分润日志");
        //             int index = 0;
        //             foreach(HelpProfitMerTradeSummay sub in list)
        //             {
        //                 index += 1;
        //                 int MerchantId = sub.MerchantId;
        //                 decimal TradeAmount = sub.TradeAmount;
        //                 string TradeDate = sub.TradeDate;
        //                 HelpProfitMerchantForUser merchant = db.HelpProfitMerchantForUser.FirstOrDefault(m => m.MerchantId == MerchantId);
        //                 if(merchant != null)
        //                 {
        //                     int UserId = merchant.UserId;
        //                     PosMerchantInfo mer = db.PosMerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new PosMerchantInfo();
        //                     MachineForMerNo merFor = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == mer.KqMerNo) ?? new MachineForMerNo();
        //                     PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == merFor.SnId) ?? new PosMachinesTwo();
                            
        //                     Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
        //                     decimal money = TradeAmount * 0.0005M;
        //                     decimal money2 = TradeAmount * 0.00005M;
                            
        //                     AddProfitRecord(db, user, pos, mer, TradeAmount, money, TradeDate, 1);
        //                     db.SaveChanges();

        //                     int ParentUserId = user.ParentUserId;
        //                     while(ParentUserId > 0)
        //                     {
        //                         Users puser = db.Users.FirstOrDefault(m => m.Id == ParentUserId);
        //                         if(puser != null)
        //                         {
        //                             bool checkorder = orders.Any(m => m.UserId == ParentUserId);
        //                             if(checkorder)
        //                             {
        //                                 AddProfitRecord(db, puser, pos, mer, TradeAmount, money2, TradeDate, 112);
        //                                 db.SaveChanges();
        //                                 ParentUserId = 0;
        //                             }
        //                             else
        //                             {
        //                                 ParentUserId = puser.ParentUserId;
        //                             }
        //                         }
        //                         else
        //                         {
        //                             ParentUserId = 0;
        //                         }
        //                     }
        //                 }
        //                 LogHelper.Instance.WriteLog(index + "--Id:" + sub.Id + "；MerchantId:" + sub.MerchantId + "；" + DateTime.Now.ToString(), "助利宝分润日志");
        //             }
        //         }
        //         else
        //         {
        //             op = false;
        //         }
        //     }
        //     db.Dispose();
        //     LogHelper.Instance.WriteLog("结束：" + DateTime.Now.ToString(), "助利宝分润日志");
        // }

        // private void AddProfitRecord(WebCMSEntities db, Users puser, PosMachinesTwo pos, PosMerchantInfo merchant, decimal TradeAmount, decimal Prize, string TradeDate, int RewardType)
        // {
        //     if(Prize == 0)
        //     {
        //         return;
        //     }
        //     string RewardDesc = "助利宝分润";
        //     if(RewardType == 112)
        //     {
        //         RewardDesc = "助利宝推荐分润";
        //     }
        //     string TradeMonth = TradeDate.Substring(0, 6);
        //     HelpProfitRewardDetail detail = db.HelpProfitRewardDetail.Add(new HelpProfitRewardDetail()
        //     {
        //         CreateDate = DateTime.Now,
        //         UpdateDate = DateTime.Now,
        //         TradeMonth = TradeMonth, //交易月
        //         SeoTitle = TradeDate,
        //         UserId = puser.Id, //创客
        //         BrandId = pos.BrandId, //品牌
        //         ProductName = RelationClass.GetKqProductsInfo(pos.BrandId), //产品名称
        //         MerchantId = pos.BindMerchantId, //商户
        //         DirectUserId = merchant.UserId, //商户直属人
        //         SnNo = pos.PosSn, //SN号
        //         MerNo = merchant.KqMerNo, //渠道商户号
        //         SnType = pos.PosSnType, //机具类型
        //         StandardDate = pos.ActivationTime, //商户的激活日期
        //         SnStoreId = pos.StoreId, //SN仓库
        //         MerBuddyType = puser.MerchantType, //商户创客类型
        //         RewardType = RewardType, //奖励类型
        //         RewardTips = RewardDesc, //奖励描述
        //         CreditTradeAmt = TradeAmount, //贷记卡交易总金额
        //         CreditRewardAmount = Prize, //贷记卡交易奖励金额
        //         RewardDesc = RewardDesc, //奖励描述
        //     }).Entity;
        //     db.HelpProfitReward.Add(new HelpProfitReward()
        //     {
        //         CreateDate = DateTime.Now,
        //         UpdateDate = DateTime.Now,
        //         TradeMonth = TradeMonth, //交易月
        //         SeoTitle = TradeDate,
        //         UserId = puser.Id, //创客
        //         BrandId = pos.BrandId, //品牌
        //         RewardType = RewardType, //奖励类型
        //         CreditTradeAmt = TradeAmount, //贷记卡交易总金额
        //         CreditRewardAmount = Prize, //贷记卡交易奖励金额
        //         RewardDesc = RewardDesc, //奖励描述
        //     });
        // }

        public void StatProfitEveryDay(string Month)
        {
            string check = function.ReadInstance("/HelpProfitStat/" + Month + ".txt");
            if (!string.IsNullOrEmpty(check))
            {
                return;
            }
            function.WritePage("/HelpProfitStat/", Month + ".txt", DateTime.Now.ToString());
            WebCMSEntities db = new WebCMSEntities();
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            var orders = db.Orders.Select(m => new { m.UserId, m.Status, m.ProductId }).Where(m => m.Status > 0 && m.ProductId == 34).ToList();
            DataTable list = OtherMySqlConn.dtable("select UserId,sum(TradeAmount) from HelpProfitMerchantForUser u,HelpProfitMerTradeSummay s where u.MerchantId=s.MerchantId and TradeMonth='" + Month + "' group by UserId");
            LogHelper.Instance.WriteLog("开始：" + DateTime.Now.ToString(), "助利宝分润日志");
            LogHelper.Instance.WriteLog("总数：" + list.Rows.Count, "助利宝分润日志");
            int index = 0;
            foreach (DataRow sub in list.Rows)
            {
                index += 1;
                int UserId = int.Parse(sub["UserId"].ToString());
                decimal TradeAmount = decimal.Parse(sub[1].ToString());

                Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                decimal money = TradeAmount * 0.0005M;
                decimal money2 = TradeAmount * 0.00005M;

                AddProfitRecord(db, user, TradeAmount, money, Month, 1);
                db.SaveChanges();

                int ParentUserId = user.ParentUserId;
                while (ParentUserId > 0)
                {
                    Users puser = db.Users.FirstOrDefault(m => m.Id == ParentUserId);
                    if (puser != null)
                    {
                        bool checkorder = orders.Any(m => m.UserId == ParentUserId);
                        if (checkorder)
                        {
                            AddProfitRecord(db, puser, TradeAmount, money2, Month, 112);
                            db.SaveChanges();
                            ParentUserId = 0;
                        }
                        else
                        {
                            ParentUserId = puser.ParentUserId;
                        }
                    }
                    else
                    {
                        ParentUserId = 0;
                    }
                }
                LogHelper.Instance.WriteLog(index + "--UserId:" + UserId + "；TradeAmount:" + TradeAmount + "；" + DateTime.Now.ToString(), "助利宝分润日志");
            }
            db.Dispose();
            LogHelper.Instance.WriteLog("结束：" + DateTime.Now.ToString(), "助利宝分润日志");
        }

        private void AddProfitRecord(WebCMSEntities db, Users puser, decimal TradeAmount, decimal Prize, string TradeMonth, int RewardType)
        {
            if(Prize == 0)
            {
                return;
            }
            string RewardDesc = "助利宝分润";
            if(RewardType == 112)
            {
                RewardDesc = "助利宝推荐分润";
            }
            db.HelpProfitReward.Add(new HelpProfitReward()
            {
                CreateDate = DateTime.Now,
                UpdateDate = DateTime.Now,
                TradeMonth = TradeMonth, //交易月
                UserId = puser.Id, //创客
                RewardType = RewardType, //奖励类型
                CreditTradeAmt = TradeAmount, //贷记卡交易总金额
                CreditRewardAmount = Prize, //贷记卡交易奖励金额
                RewardDesc = RewardDesc, //奖励描述
            });
        }
    }
}