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

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


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

        public void StartListenProfitDo()
        {
            while(true)
            {
                if(DateTime.Now.Day < 10 && DateTime.Now.Hour > 2 && DateTime.Now.Hour < 23)
                {
                    try
                    {
                        DoProfit();
                    }
                    catch(Exception ex)
                    {
                        LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "来客吧区域代理分润异常");
                    }
                    Thread.Sleep(600000);
                }
                else
                {
                    Thread.Sleep(3600000);
                }
            }
        }

        //分润算法
        public void DoProfit()
        {
            string TradeMonth = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            string check = function.ReadInstance("/AgentProfitFlag/" + TradeMonth + ".txt");
            if(!string.IsNullOrEmpty(check))
            {
                return;
            }
            function.WritePage("/AgentProfitFlag/", TradeMonth + ".txt", DateTime.Now.ToString());
            MySystem.Models.Main1.WebCMSEntities dbnew1 = new MySystem.Models.Main1.WebCMSEntities();
            WebCMSEntities dbnew = new WebCMSEntities();
            List<AgentProfit> ProfitList = new List<AgentProfit>();
            DataTable dt = CustomerSqlConn.dtable("select IsAct,ManageAreas,AgentLevel,TotalAmount,(case when IsAct=1 then l.Percent else l.UnActPercent end) Percent,(case when IsAct=1 then l.Percent*TotalAmount else l.UnActPercent*TotalAmount end) Profit from (select IsAct,ManageAreas,(LENGTH(ManageAreas)-LENGTH(REPLACE(ManageAreas,',',''))+1) AgentLevel,sum(TotalAmount) TotalAmount from AgentTradeStatSummary where TradeMonth='" + TradeMonth + "' group by IsAct,ManageAreas) tb left join AgentLevels l on tb.AgentLevel=l.Id", AppConfig.Base.SqlConnStr);
            foreach(DataRow dr in dt.Rows)
            {
                ProfitList.Add(new AgentProfit()
                {
                    IsAct = int.Parse(dr["IsAct"].ToString()),
                    ManageAreas = dr["ManageAreas"].ToString(),
                    AgentLevel = int.Parse(dr["IsAct"].ToString()),
                    TotalAmount = decimal.Parse(dr["TotalAmount"].ToString()),
                    Percent = decimal.Parse(dr["Percent"].ToString()),
                    Profit = decimal.Parse(dr["Profit"].ToString()),
                });
            }
            foreach(AgentProfit SubProfit in ProfitList)
            {
                int SubLevel = SubProfit.AgentLevel + 1;
                decimal SubProfitAmt = 0;
                if(ProfitList.Any(m => m.ManageAreas.StartsWith(SubProfit.ManageAreas) && m.AgentLevel == SubLevel && m.IsAct == SubProfit.IsAct))
                {
                    SubProfitAmt = ProfitList.Where(m => m.ManageAreas.StartsWith(SubProfit.ManageAreas) && m.AgentLevel == SubLevel && m.IsAct == SubProfit.IsAct).Sum(m => m.Profit);
                }
                if(SubProfitAmt > 0) SubProfit.ProfitResult -= SubProfitAmt;
            }
            foreach(AgentProfit SubProfit in ProfitList)
            {
                MySystem.Models.Main1.UserAgent user = dbnew1.UserAgent.FirstOrDefault(m => m.ManageAreas == SubProfit.ManageAreas);
                if(user != null)
                {
                    dbnew.AgentProfitRecord.Add(new AgentProfitRecord()
                    {
                        CreateDate = DateTime.Now,
                        UpdateDate = DateTime.Now,
                        TradeMonth = TradeMonth,
                        Remark = "来客吧区域代理奖励\n" + SubProfit.ManageAreas,
                        TradeProfit = SubProfit.ProfitResult,
                        CreditTradeAmt = SubProfit.TotalAmount,
                        UserId = user.UserId,
                    });
                    dbnew.Dispose();
                }
            }
            dbnew1.Dispose();
            dbnew.Dispose();
        }
    }
}