using System;
using System.Collections.Generic;
using System.Linq;
using MySystem.PxcModels;
using Library;
using LitJson;

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

        public void Start(JobMqMsg jobInfo)
        {
            string content = "";
            try
            {
                string Msg = Profit();
                // jobInfo.Status = Msg == "success" ? 1: 0;
                // jobInfo.Msg = Msg == "success" ? "执行完成": Msg;
                // RabbitMQClient.Instance.SendMsg(Newtonsoft.Json.JsonConvert.SerializeObject(jobInfo), "ProfitBack");
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrEmpty(content))
                {
                    Dictionary<string, string> data = new Dictionary<string, string>();
                    data.Add("ErrTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    data.Add("ErrMsg", ex.ToString());
                    Utils.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(data), "profitback_err");
                }
                else
                {
                    Utils.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "profitback_service");
                }
            }
        }

        //验证并同步到账户
        private string Profit()
        {
            DateTime StatDate = DateTime.Now.AddMonths(-1);
            DateTime StartDate = DateTime.Parse(StatDate.ToString("yyyy-MM") + "-01 00:00:00");
            DateTime EndDate = StartDate.AddMonths(1);
            string TradeMonth = StatDate.ToString("yyyyMM");
            WebCMSEntities db = new WebCMSEntities();
            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    List<ProfitRewardRecord> list = db.ProfitRewardRecord.Where(m => m.TradeMonth == TradeMonth && m.CheckStatus == 0).ToList();
                    foreach (ProfitRewardRecord sub in list)
                    {
                        int UserId = sub.UserId; //创客
                        int MerchantId = sub.MerchantId; //商户
                        int BrandId = sub.BrandId; //品牌
                        int ProfitType = sub.ProfitType; //创客分润类型 直营-0，团队-1
                        decimal ProfitMoney = sub.TradeProfit; //交易分润
                        decimal ActualProfit = 0;
                        if (ProfitType == 0)
                        {
                            bool check = db.ProfitRecord.Any(m => m.UserId == sub.UserId && m.MerchantId == sub.MerchantId && m.BrandId == sub.BrandId && m.TradeDate >= StartDate && m.TradeDate <= EndDate);
                            if (check)
                            {
                                ActualProfit = db.ProfitRecord.Where(m => m.UserId == sub.UserId && m.MerchantId == sub.MerchantId && m.BrandId == sub.BrandId && m.TradeDate >= StartDate && m.TradeDate <= EndDate).Sum(m => m.ProfitAmount);
                            }
                        }
                        else if (ProfitType == 1)
                        {
                            string UserIdString = "," + sub.UserId + ",";
                            bool check = db.ProfitRecord.Any(m => m.ParentNav.Contains(UserIdString) && m.MerchantId == sub.MerchantId && m.BrandId == sub.BrandId && m.TradeDate >= StartDate && m.TradeDate <= EndDate);
                            if (check)
                            {
                                ActualProfit = db.ProfitRecord.Where(m => m.ParentNav.Contains(UserIdString) && m.MerchantId == sub.MerchantId && m.BrandId == sub.BrandId && m.TradeDate >= StartDate && m.TradeDate <= EndDate).Sum(m => m.ProfitAmount);
                            }
                        }
                        if (ActualProfit == ProfitMoney)
                        {
                            ProfitRewardRecord edit = db.ProfitRewardRecord.FirstOrDefault(m => m.Id == sub.Id);
                            if (edit != null)
                            {
                                edit.CheckStatus = 1;
                                db.SaveChanges();
                            }
                            UserAccount account = db.UserAccount.FirstOrDefault(m => m.UserId == sub.UserId);
                            if (account == null)
                            {
                                account = db.UserAccount.Add(new UserAccount()
                                {
                                    Id = sub.UserId,
                                    CreateDate = DateTime.Now,
                                    UserId = sub.UserId,
                                    UserProperty = 0,
                                    UserType = 2,
                                }).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; //变更后余额
                            db.SaveChanges();
                            UserAccountRecord accountRecord = db.UserAccountRecord.Add(new UserAccountRecord()
                            {
                                CreateDate = DateTime.Now,
                                UpdateDate = DateTime.Now,
                                UserId = sub.UserId, //创客
                                ChangeType = 1, //变动类型
                                ProductType = sub.BrandId, //产品类型
                                ChangeAmount = ProfitMoney, //变更金额
                                BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                                AfterTotalAmount = AfterTotalAmount, //变更后总金额
                                BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                                AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                                BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                                AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                                TransRecordNo = sub.RecordNo, //交易流水编号
                                Remark = "",
                            }).Entity;
                            db.SaveChanges();

                            RedisDbconn.Instance.HAddNumber("TmpTradeProfit", sub.UserId + "_" + BrandId + "_" + StatDate.ToString("yyyy年MM月") + "分润_" + StatDate.ToString("yyyyMM"), ProfitMoney);
                        }
                        else
                        {
                            ErrorMsg msg = new ErrorMsg()
                            {
                                Time = DateTime.Now,
                                ErrorContent = "同步交易分润失败，数据不一致",
                                Obj = Newtonsoft.Json.JsonConvert.SerializeObject(sub),
                            };
                            RedisDbconn.Instance.AddList("ProfitServiceWarning", msg);
                        }
                    }

                    //首页-快联盟产品-收益查看-交易分润
                    Dictionary<string, decimal> datalist = RedisDbconn.Instance.HGetAll<decimal>("TmpTradeProfit");
                    foreach (string key in datalist.Keys)
                    {
                        string[] fields = key.Split('_');
                        string UserId = fields[0];
                        string BrandId = fields[1];
                        string TradeM = fields[2];
                        string TradeMValue = fields[3];
                        RedisDbconn.Instance.AddList("TradeProfit:" + UserId + ":" + BrandId, new TradeProfitItem()
                        {
                            TradeProfit = datalist[key],
                            TradeMonth = TradeM,
                            TradeMonthValue = TradeMValue,
                            CreateDate = DateTime.Now,
                        });
                    }
                    RedisDbconn.Instance.Clear("TmpTradeProfit");
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    ErrorMsg msg = new ErrorMsg()
                    {
                        Time = DateTime.Now,
                        ErrorContent = ex.ToString(),
                    };
                    Utils.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(msg), "ProfitServiceError");
                }
            }
            db.Dispose();
            return "success";
        }
    }
}