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

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

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

        public void ready()
        {
            while (true)
            {
                string data = RedisDbconn.Instance.RPop<string>("OperatePrizeQueue");
                if (!string.IsNullOrEmpty(data))
                {
                    try
                    {
                        dosomething(data);
                    }
                    catch (Exception ex)
                    {
                        Utils.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "运营中心奖励异常");
                    }
                    Thread.Sleep(100);
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
        }

        public void dosomething(string data)
        {
            int PosId = int.Parse(function.CheckInt(data));
            WebCMSEntities db = new WebCMSEntities();
            OpModels.WebCMSEntities spdb = new OpModels.WebCMSEntities();
            PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == PosId);
            if (pos != null)
            {
                bool IsGet = true;
                if(Utils.Instance.IsWifi(pos.BrandId))
                {
                    int Count = db.UserAccountRecord.Count(m => m.QueryCount == PosId && m.ChangeType == 121);
                    int Count1 = db.WifiTradeRecord.Count(m => m.SnNo == pos.PosSn);
                    IsGet = Count >= Count1;
                }
                else
                {
                    IsGet = db.UserAccountRecord.Any(m => m.QueryCount == PosId && m.ChangeType == 121);
                }
                if(!IsGet)
                {
                    int OpId = 0;
                    int UserId = pos.BuyUserId;
                    while(UserId > 0)
                    {
                        Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                        OpModels.SysAdmin sys = spdb.SysAdmin.FirstOrDefault(m => m.UserId == user.Id) ?? new OpModels.SysAdmin();
                        if(user.UserType >= 1 && sys.ExpireDate > DateTime.Now)
                        {
                            OpId = user.Id;
                            UserId = 0;
                        }
                        else
                        {
                            UserId = user.ParentUserId;
                        }
                    }
                    if(OpId > 0)
                    {
                        decimal ChangeAmount = 5;
                        if(pos.BrandId == 14)
                        {
                            ChangeAmount = 19 * 0.05M;
                        }
                        if(Utils.Instance.IsWifi(pos.BrandId))
                        {
                            int tradeCount = db.WifiTradeRecord.Count(m => m.SnNo == pos.PosSn);
                            if (tradeCount > 0)
                            {
                                ChangeAmount = db.WifiTradeRecord.Where(m => m.SnNo == pos.PosSn).OrderByDescending(m => m.Id).FirstOrDefault().TradeAmount * 0.005M;
                                ChangeAmount = PublicFunction.NumberFormat(ChangeAmount);
                            }
                            else
                            {
                                ChangeAmount = 0;
                            }
                        }
                        if(ChangeAmount > 0)
                        {
                            UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == OpId);
                            if (account == null)
                            {
                                account = db.UserAccount.Add(new UserAccount()
                                {
                                    Id = OpId,
                                    UserId = OpId,
                                }).Entity;
                                db.SaveChanges();
                            }
                            decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                            decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                            decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                            account.BalanceAmount += ChangeAmount;
                            account.TotalAmount += ChangeAmount;
                            decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                            decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                            decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                            UserAccountRecord userAccountRecord = db.UserAccountRecord.Add(new UserAccountRecord()
                            {
                                CreateDate = DateTime.Now,
                                UpdateDate = DateTime.Now,
                                UserId = OpId, //创客
                                ProductType = pos.BrandId, //品牌
                                ChangeType = 121, //变动类型
                                ChangeAmount = ChangeAmount, //变更金额
                                BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                                AfterTotalAmount = AfterTotalAmount, //变更后总金额
                                BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                                AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                                BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                                AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                                QueryCount = PosId,
                                Kind = 3,
                            }).Entity;
                            db.SaveChanges();

                            //发送APP推送消息
                            Utils.Instance.PrizePush(OpId, ChangeAmount);
                        }
                    }
                }
            }
            db.Dispose();
            spdb.Dispose();
        }
    }
}