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

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

        public void Start(JobMqMsg jobInfo)
        {
            string content = "";
            try
            {
                string Msg = CheckData();
                // jobInfo.Status = Msg == "success" ? 1: 0;
                // jobInfo.Msg = Msg == "success" ? "执行完成": Msg;
                // RabbitMQClient.Instance.SendMsg(Newtonsoft.Json.JsonConvert.SerializeObject(jobInfo), "DiviBack");
            }
            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());
                    function.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(data), "diviback_err");
                }
                else
                {
                    function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "diviback_service");
                }
            }
        }

        //检查机具扣费情况
        private string CheckData()
        {
            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<UserAccountRecord> list = db.UserAccountRecord.Where(m => m.CreateDate >= StartDate && m.CreateDate < EndDate && m.Status == -1).ToList();
                    foreach (UserAccountRecord sub in list)
                    {
                        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 += sub.ChangeAmount;
                        account.TotalAmount += sub.ChangeAmount;
                        decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                        decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                        decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                        UserAccountRecord edit = db.UserAccountRecord.FirstOrDefault(m => m.Id == sub.Id);
                        if (edit != null)
                        {
                            edit.Status = 0;
                            edit.BeforeTotalAmount += BeforeTotalAmount; //变更前总金额
                            edit.AfterTotalAmount += AfterTotalAmount; //变更后总金额
                            edit.BeforeFreezeAmount += BeforeFreezeAmount; //变更前冻结金额
                            edit.AfterFreezeAmount += AfterFreezeAmount; //变更后冻结金额
                            edit.BeforeBalanceAmount += BeforeBalanceAmount; //变更前余额
                            edit.AfterBalanceAmount += AfterBalanceAmount; //变更后余额
                        }
                        db.SaveChanges();

                        //首页-快联盟产品-收益查看-分红奖励
                        List<TradeProfitItem> DiviList = RedisDbconn.Instance.GetList<TradeProfitItem>("TradeProfit:Divi:" + sub.UserId + ":" + sub.ProductType, 1, 1000000);
                        TradeProfitItem Check = DiviList.FirstOrDefault(m => m.TradeMonthValue == TradeMonth);
                        if (Check == null)
                        {
                            DiviList.Add(new TradeProfitItem()
                            {
                                TradeProfit = sub.ChangeAmount,
                                TradeMonth = sub.CreateDate.Value.ToString("yyyy年MM月"),
                                TradeMonthValue = sub.CreateDate.Value.ToString("yyyyMM"),
                                CreateDate = DateTime.Now,
                            });
                        }
                        else
                        {
                            Check.TradeProfit += sub.ChangeAmount;
                        }
                        RedisDbconn.Instance.Clear("TradeProfit:Divi:" + sub.UserId + ":" + sub.ProductType);
                        RedisDbconn.Instance.AddList("TradeProfit:Divi:" + sub.UserId + ":" + sub.ProductType, DiviList.ToArray());

                    }
                    
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    ErrorMsg msg = new ErrorMsg()
                    {
                        Time = DateTime.Now,
                        ErrorContent = ex.ToString(),
                    };
                    function.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(msg), "DiviServiceError");
                }
            }
            db.Dispose();
            return "success";
        }
    }
}