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

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

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

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

        private void DoTradeProfit(int BrandId, string date, string SysUserName, int OpType = 0)
        {
            int OpTypeDo = OpType + 1;
            WebCMSEntities db = new WebCMSEntities();
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            DataTable dt = OtherMySqlConn.dtable("select UserId,ProfitType,sum(CreditTradeProfit+DebitNonTradeCapProfit+DebitTradeCapProfit+QrCreditTradeProfit) from ProfitRewardRecord where CheckStatus=" + OpType + " and BrandId=" + BrandId + " and TradeMonth='" + date + "' group by UserId,ProfitType");
            function.WriteLog("分润:" + BrandId + ":" + dt.Rows.Count, "同步分润数据");
            int index = 0;
            foreach (DataRow dr in dt.Rows)
            {
                index += 1;
                int UserId = int.Parse(dr["UserId"].ToString());
                ulong ProfitType = ulong.Parse(dr["ProfitType"].ToString());
                OtherMySqlConn.op("update ProfitRewardRecord set CheckStatus=" + OpTypeDo + " where BrandId=" + BrandId + " and TradeMonth='" + date + "' and UserId=" + UserId + " and ProfitType=" + ProfitType);
                decimal ProfitMoney = decimal.Parse(dr[2].ToString());
                var tran = db.Database.BeginTransaction();
                try
                {
                    Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                    if (OpType == 0)
                    {
                        ProfitRecord profit = db.ProfitRecord.FirstOrDefault(m => m.UserId == UserId && m.BrandId == BrandId && m.SeoTitle == date);
                        if (profit == null)
                        {
                            profit = db.ProfitRecord.Add(new ProfitRecord()
                            {
                                CreateDate = DateTime.Now,
                                CreateMan = SysUserName,
                                SeoTitle = date,
                                ParentNav = user.ParentNav,
                                BrandId = BrandId,
                                UserId = UserId,
                            }).Entity;
                            db.SaveChanges();
                        }
                        profit.ProfitAmount += ProfitMoney;
                        string IdBrand = UserId + "_" + BrandId;
                        UserMachineData MachineData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
                        if (MachineData == null)
                        {
                            MachineData = db.UserMachineData.Add(new UserMachineData()
                            {
                                IdBrand = IdBrand,
                            }).Entity;
                            db.SaveChanges();
                        }
                        MachineData.TradeProfit += ProfitMoney;
                        db.SaveChanges();
                    }
                    else if (OpType == 1)
                    {
                        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 = BrandId,
                            ChangeType = 1, //变动类型
                            ChangeAmount = ProfitMoney, //变更金额
                            BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                            AfterTotalAmount = AfterTotalAmount, //变更后总金额
                            BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                            AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                            BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                            AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                            Remark = ProfitType == 1 ? "直拓商户分润" : "品牌推广服务费",
                        }).Entity;
                        db.SaveChanges();
                        PublicFunction.SplitUserAccountRecord(add);
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + UserId + "," + ProfitType + "," + ProfitMoney + "\n" + ex.ToString(), "同步到余额异常");
                    tran.Rollback();
                }
                function.WriteLog(index.ToString(), "同步分润数据");
            }
            db.Dispose();
        }
        private void DoTradeProfit2(int BrandId, string date, string SysUserName, int OpType = 0)
        {
            WebCMSEntities db = new WebCMSEntities();
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            DataTable dt = OtherMySqlConn.dtable("select UserId,ProfitAmount from ProfitRecord where BrandId=" + BrandId + " and SeoTitle='" + date + "' and UserId>0 order by Id");
            function.WriteLog("分润:" + BrandId + ":" + dt.Rows.Count, "同步分润数据");
            int index = 0;
            foreach (DataRow dr in dt.Rows)
            {
                index += 1;
                int UserId = int.Parse(dr["UserId"].ToString());
                decimal ProfitAmount = decimal.Parse(dr["ProfitAmount"].ToString());
                var tran = db.Database.BeginTransaction();
                try
                {
                    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 += ProfitAmount;
                    account.TotalAmount += ProfitAmount;
                    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 = BrandId,
                        ChangeType = 1, //变动类型
                        ChangeAmount = ProfitAmount, //变更金额
                        BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                        AfterTotalAmount = AfterTotalAmount, //变更后总金额
                        BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                        AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                        BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                        AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                    }).Entity;
                    db.SaveChanges();
                    tran.Commit();
                    PublicFunction.SplitUserAccountRecord(add);
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + UserId + "," + ProfitAmount + "\n" + ex.ToString(), "同步到余额异常");
                    tran.Rollback();
                }
                function.WriteLog(index.ToString(), "同步分润数据");
            }
            db.Dispose();
        }


        //分润补贴
        private void DoSubsidyProfit(int BrandId, string date, int OpType = 0)
        { 
            int OpTypeDo = OpType + 1;
            WebCMSEntities db = new WebCMSEntities();
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            DataTable dt = OtherMySqlConn.dtable("select SubsidyUserId,sum(SubsidyProfitRate) from ProfitSubsidyDetail where Status=" + OpType + " and BrandId=" + BrandId + " and TradeMonth='" + date + "' GROUP BY SubsidyUserId");
            function.WriteLog("补贴:" + BrandId + ":" + dt.Rows.Count, "同步分润数据");
            int index = 0;
            foreach (DataRow dr in dt.Rows)
            {
                index += 1;
                int UserId = int.Parse(dr["SubsidyUserId"].ToString());
                decimal ProfitMoney = decimal.Parse(dr[1].ToString());
                OtherMySqlConn.op("update ProfitSubsidyDetail set Status=" + OpTypeDo + " where BrandId=" + BrandId + " and TradeMonth='" + date + "' and SubsidyUserId=" + UserId + "");
                var tran = db.Database.BeginTransaction();
                try
                {
                    Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                    if (OpType == 0)
                    {
                        string IdBrand = UserId + "_" + BrandId;
                        UserMachineData MachineData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
                        if (MachineData == null)
                        {
                            MachineData = db.UserMachineData.Add(new UserMachineData()
                            {
                                IdBrand = IdBrand,
                            }).Entity;
                            db.SaveChanges();
                        }
                        MachineData.OtherProfit += ProfitMoney;
                        db.SaveChanges();
                    }
                    else if (OpType == 1)
                    {
                        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 = BrandId,
                            ChangeType = 111, //变动类型
                            ChangeAmount = ProfitMoney, //变更金额
                            BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                            AfterTotalAmount = AfterTotalAmount, //变更后总金额
                            BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                            AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                            BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                            AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                            Remark = "直拓商户补贴",
                        }).Entity;
                        db.SaveChanges();
                        PublicFunction.SplitUserAccountRecord(add);
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + UserId + "," + ProfitMoney + "\n" + ex.ToString(), "同步到补贴异常");
                    tran.Rollback();
                }
                function.WriteLog(index.ToString(), "同步分润数据");
            }
            db.Dispose();
        }
    }
}