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

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

        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), "StandardBack");
            }
            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), "standardback_err");
                }
                else
                {
                    Utils.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "standardback_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<MerchantRebateDetail> list = db.MerchantRebateDetail.Where(m => m.TradeMonth == TradeMonth && m.SyncStatus == 0).ToList();
                    foreach (MerchantRebateDetail sub in list)
                    {
                        MachineForMerNo machinefor = RedisDbconn.Instance.Get<MachineForMerNo>("MachineForMerNo:" + sub.SnNo) ?? new MachineForMerNo();
                        PosMachines machine = RedisDbconn.Instance.Get<PosMachines>("PosMachines:" + machinefor.SnId) ?? new PosMachines();
                        Users user = db.Users.FirstOrDefault(m => m.Id == machine.UserId) ?? new Users();
                        int TopUserId = 0;
                        if (!string.IsNullOrEmpty(user.ParentNav))
                        {
                            TopUserId = int.Parse(user.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                        }                        
                        MerchantRebateDetail edit = db.MerchantRebateDetail.FirstOrDefault(m => m.Id == sub.Id);
                        if (edit != null)
                        {
                            edit.SyncStatus = 1;
                            db.SaveChanges();
                        }
                        UserAccount account = db.UserAccount.FirstOrDefault(m => m.UserId == user.Id);
                        if (account == null)
                        {
                            account = db.UserAccount.Add(new UserAccount()
                            {
                                Id = user.Id,
                                CreateDate = DateTime.Now,
                                UserId = user.Id,
                                UserProperty = 0,
                                UserType = 2,
                            }).Entity;
                            db.SaveChanges();
                        }
                        decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                        decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                        decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                        account.BalanceAmount += sub.CreditRewardAmount;
                        account.TotalAmount += sub.CreditRewardAmount;
                        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 = user.Id, //创客
                            ChangeType = 40, //变动类型
                            ProductType = sub.BrandId, //产品类型
                            ChangeAmount = sub.CreditRewardAmount, //变更金额
                            BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                            AfterTotalAmount = AfterTotalAmount, //变更后总金额
                            BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                            AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                            BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                            AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                        }).Entity;
                        db.SaveChanges();
                    }
                    
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    ErrorMsg msg = new ErrorMsg()
                    {
                        Time = DateTime.Now,
                        ErrorContent = ex.ToString(),
                    };
                    Utils.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(msg), "StandardServiceError");
                }
            }
            db.Dispose();
            return "success";
        }
    }
}