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

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

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

        public void doSomething()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("SycnHelpProfitQueue2");
                if (!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        function.WriteLog(DateTime.Now.ToString() + "\r\n\r\n", "同步助利宝分润数据");
                        string[] data = content.Split(new string[] { "#cut#" }, StringSplitOptions.None);
                        string date = data[0];
                        int OpType = int.Parse(data[1]);
                        string SysUserName = data[2];
                        if (OpType == 0)
                        {
                            DoHelpProfit(date, SysUserName);
                        }
                        else if (OpType == 1)
                        {
                            DoHelpProfit2(date, SysUserName);
                        }
                        function.WriteLog(DateTime.Now.ToString() + "\r\n\r\n", "同步助利宝分润数据");
                    }
                    catch (Exception ex)
                    {
                        function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "同步助利宝分润数据异常");
                    }
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
        }


        #region 助力宝分润展示

        public void DoHelpProfit(string month, string sysUserName)
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            OtherMySqlConn.dtable("update HelpProfitReward set Status=1 where Status=0 and TradeMonth='" + month + "'");
        }

        #endregion

        #region 助力宝分润到账

        public void DoHelpProfit2(string month, string sysUserName)
        {
            WebCMSEntities db = new WebCMSEntities();
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            
            DataTable dt = OtherMySqlConn.dtable("select UserId,RewardType,sum(CreditRewardAmount),sum(CreditTradeAmt) from HelpProfitReward where Status=1 and TradeMonth='" + month + "' GROUP BY UserId,RewardType");
            function.WriteLog("数量:" + dt.Rows.Count, "同步助利宝分润");
            int index = 0;
            foreach (DataRow dr in dt.Rows)
            {
                index += 1;
                int UserId = int.Parse(dr["UserId"].ToString());
                int RewardType = int.Parse(dr["RewardType"].ToString());
                decimal ProfitMoney = decimal.Parse(dr[2].ToString());
                decimal TradeAmt = decimal.Parse(dr[3].ToString());
                var tran = db.Database.BeginTransaction();
                bool op = false;
                try
                {
                    Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                    UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == UserId);
                    if (account == null)
                    {
                        account = db.UserAccount.Add(new UserAccount()
                        {
                            Id = UserId,
                            UserId = UserId,
                        }).Entity;
                        db.SaveChanges();
                    }
                    decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                    decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                    decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                    account.BalanceAmount += ProfitMoney;
                    account.TotalAmount += ProfitMoney;
                    decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                    decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                    decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                    UserAccountRecord add = db.UserAccountRecord.Add(new UserAccountRecord()
                    {
                        CreateDate = DateTime.Now,
                        UpdateDate = DateTime.Now,
                        UserId = UserId, //创客
                        ProductType = 101,
                        ChangeType = RewardType, //变动类型
                        ChangeAmount = ProfitMoney, //变更金额
                        BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                        AfterTotalAmount = AfterTotalAmount, //变更后总金额
                        BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                        AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                        BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                        AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                        Remark = RewardType == 1 ? "直拓商户分润" : "推荐交易分润",
                    }).Entity;
                    db.SaveChanges();
                    tran.Commit();
                    op = true;
                    PublicFunction.SplitUserAccountRecord(add);
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + UserId + "," + ProfitMoney + "\n" + ex.ToString(), "同步助利宝分润异常");
                    tran.Rollback();
                }
                function.WriteLog(index.ToString(), "同步助利宝分润");
            }
            OtherMySqlConn.dtable("update HelpProfitReward set Status=2 where Status=1 and TradeMonth='" + month + "'");
            db.Dispose();
        }

        #endregion
    }
}