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

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



        public void CreateTable()
        {
            Thread th = new Thread(CreateTableDo);
            th.IsBackground = true;
            th.Start();
        }
        public void CreateTableDo()
        {
            while (true)
            {
                string TradeDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd");
                string TradeMonth = DateTime.Now.AddMonths(1).ToString("yyyyMM");

                CreateTableOp(TradeDate, 1, "MerchantTradeSummary");

                if(DateTime.Now.Day > 25)
                {
                    CreateTableOp(TradeMonth, 2, "MerchantTradeSummary");
                    CreateTableOp(TradeMonth, 2, "MerchantTradeSummaryList");
                }

                int timespan = 1000 * 60 * 60;
                Thread.Sleep(timespan);
            }
        }
        private void CreateTableOp(string TradeDate, int Kind, string TableName)
        {
            if(string.IsNullOrEmpty(RedisDbconn.Instance.Get<string>(TableName + TradeDate)))
            {
                string sql = "";
                if(TableName == "MerchantTradeSummary") sql = AppConfig.Base.CreateMerchantTradeSummary.Replace("#DateTime#", TradeDate);
                if(TableName == "MerchantTradeSummaryList") sql = AppConfig.Base.CreateMerchantTradeSummaryList.Replace("#DateTime#", TradeDate);
                CustomerSqlConn.op(sql, AppConfig.Base.StatSqlConn2);
                RedisDbconn.Instance.Set(TableName + TradeDate, "1");
                int sec = 3600 * 25;
                if(Kind == 2)
                {
                    sec = 3600 * 24 * 35;
                }
                RedisDbconn.Instance.SetExpire(TableName + TradeDate, sec);
            }
        }



        // 统计商户交易额到RDS
        public void StartMer()
        {
            Thread th = new Thread(StartMerDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StartMerDo()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("StatMerchantTradeSummaryQueue2");
                if(!string.IsNullOrEmpty(content))
                {
                    StatMerchantTradeSummary(content, 1);
                    StatMerchantTradeSummary(content, 2);


                    StatMerchantTradeSummaryList(content, 1);
                }
                else
                {
                    Thread.Sleep(10000);
                }
            }
        }
        public void StatMerchantTradeSummary(string content, int Kind)
        {
            try
            {
                JsonData selfDr = JsonMapper.ToObject(content);
                string TradeDate = selfDr["TradeDate"].ToString();
                decimal PayMoney = decimal.Parse(selfDr["PayMoney"].ToString());
                decimal MerchantActualAmount = decimal.Parse(selfDr["MerchantActualAmount"].ToString());
                int TradeCount = int.Parse(selfDr["TradeCount"].ToString());
                int MerchantId = int.Parse(selfDr["MerchantId"].ToString());
                int PayMode = int.Parse(selfDr["PayMode"].ToString());
                int IsAct = int.Parse(selfDr["IsAct"].ToString());

                if (Kind == 2)
                {
                    TradeDate = TradeDate.Substring(0, 6);
                }

                if (string.IsNullOrEmpty(RedisDbconn.Instance.Get<string>("MerchantTradeSummary2" + TradeDate)))
                {
                    CustomerSqlConn.op(AppConfig.Base.CreateMerchantTradeSummary.Replace("#DateTime#", TradeDate), AppConfig.Base.StatSqlConn2);
                    RedisDbconn.Instance.Set("MerchantTradeSummary2" + TradeDate, "1");
                    int sec = 3600 * 25;
                    if (Kind == 2)
                    {
                        sec = 3600 * 24 * 35;
                    }
                    RedisDbconn.Instance.SetExpire("MerchantTradeSummary2" + TradeDate, sec);
                    Thread.Sleep(2000);
                }

                string Id = "0";
                DataTable check = CustomerSqlConn.dtable("select Id from MerchantTradeSummary" + TradeDate + " where MerchantId=" + MerchantId + "", AppConfig.Base.StatSqlConn2);
                if (check.Rows.Count < 1)
                {
                    check = CustomerSqlConn.dtable("insert into MerchantTradeSummary" + TradeDate + " (MerchantId) values (" + MerchantId + ");select @@IDENTITY", AppConfig.Base.StatSqlConn2);
                    if (check.Rows.Count > 0)
                    {
                        Id = check.Rows[0][0].ToString();
                    }
                }
                else
                {
                    Id = check.Rows[0][0].ToString();
                }
                string setField = "";
                if (IsAct == 1)
                {
                    setField += "ActAmount=ActAmount+" + PayMoney + ","; // 活动交易额
                }
                else
                {
                    setField += "NonActAmount=NonActAmount+" + PayMoney + ","; // 非活动交易额
                }
                if (PayMode == 1)
                {
                    setField += "AliPayInFactAmount=AliPayInFactAmount+" + MerchantActualAmount + ","; // 支付宝实收金额
                }
                else if (PayMode == 2)
                {
                    setField += "WeChatInfactAmount=WeChatInfactAmount+" + MerchantActualAmount + ","; // 微信实收金额
                }
                setField += "OderCount=OderCount+" + TradeCount + ","; // 订单数
                setField += "InFactAmount=InFactAmount+" + MerchantActualAmount + ","; // 实收金额
                setField += "TradeAmount=TradeAmount+" + PayMoney + ","; // 交易金额
                CustomerSqlConn.op("update MerchantTradeSummary" + TradeDate + " set " + setField.TrimEnd(',') + " where Id=" + Id, AppConfig.Base.StatSqlConn2);
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "实时统计商户交易额日志RDS异常");
            }
        }

        public void StatMerchantTradeSummaryList(string content, int Kind)
        {
            try
            {
                JsonData selfDr = JsonMapper.ToObject(content);
                string TradeDate = selfDr["TradeDate"].ToString();
                decimal PayMoney = decimal.Parse(selfDr["PayMoney"].ToString());
                decimal MerchantActualAmount = decimal.Parse(selfDr["MerchantActualAmount"].ToString());
                int TradeCount = int.Parse(selfDr["TradeCount"].ToString());
                int MerchantId = int.Parse(selfDr["MerchantId"].ToString());
                int PayMode = int.Parse(selfDr["PayMode"].ToString());
                int IsAct = int.Parse(selfDr["IsAct"].ToString());

                string TradeMonth = TradeDate.Substring(0, 6);

                if (string.IsNullOrEmpty(RedisDbconn.Instance.Get<string>("MerchantTradeSummaryList:2:" + TradeMonth)))
                {
                    CustomerSqlConn.op(AppConfig.Base.CreateMerchantTradeSummaryList.Replace("#DateTime#", TradeMonth), AppConfig.Base.StatSqlConn2);
                    RedisDbconn.Instance.Set("MerchantTradeSummaryList:2:" + TradeMonth, "1");
                    int sec = 3600 * 25;
                    if (Kind == 2)
                    {
                        sec = 3600 * 24 * 35;
                    }
                    RedisDbconn.Instance.SetExpire("MerchantTradeSummaryList:2:" + TradeMonth, sec);
                    Thread.Sleep(2000);
                }

                string Id = "0";
                DataTable check = CustomerSqlConn.dtable("select Id from MerchantTradeSummaryList" + TradeMonth + " where MerchantId=" + MerchantId + " and TradeDate='" + TradeDate + "'", AppConfig.Base.StatSqlConn2);
                if (check.Rows.Count < 1)
                {
                    check = CustomerSqlConn.dtable("insert into MerchantTradeSummaryList" + TradeMonth + " (MerchantId,TradeDate) values (" + MerchantId + ",'" + TradeDate + "');select @@IDENTITY", AppConfig.Base.StatSqlConn2);
                    if (check.Rows.Count > 0)
                    {
                        Id = check.Rows[0][0].ToString();
                    }
                }
                else
                {
                    Id = check.Rows[0][0].ToString();
                }
                string setField = "";
                if (IsAct == 1)
                {
                    setField += "ActAmount=ActAmount+" + PayMoney + ","; // 活动交易额
                }
                else
                {
                    setField += "NonActAmount=NonActAmount+" + PayMoney + ","; // 非活动交易额
                }
                if (PayMode == 1)
                {
                    setField += "AliPayInFactAmount=AliPayInFactAmount+" + MerchantActualAmount + ","; // 支付宝实收金额
                }
                else if (PayMode == 2)
                {
                    setField += "WeChatInfactAmount=WeChatInfactAmount+" + MerchantActualAmount + ","; // 微信实收金额
                }
                setField += "OderCount=OderCount+" + TradeCount + ","; // 订单数
                setField += "InFactAmount=InFactAmount+" + MerchantActualAmount + ","; // 实收金额
                setField += "TradeAmount=TradeAmount+" + PayMoney + ","; // 交易金额
                CustomerSqlConn.op("update MerchantTradeSummaryList" + TradeMonth + " set " + setField.TrimEnd(',') + " where Id=" + Id, AppConfig.Base.StatSqlConn2);
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "实时统计商户交易额列表日志RDS异常");
            }
        }
    }
}