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 ActRewardService
    {
        public readonly static ActRewardService Instance = new ActRewardService();
        private ActRewardService()
        { }

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

        public void dosomething()
        {
            while (true)
            {
                string data = RedisDbconn.Instance.RPop<string>("ActRewardQueue");
                if (!string.IsNullOrEmpty(data))
                {
                    try
                    {
                        JsonData jsonOj = JsonMapper.ToObject(data);
                        int PosId = int.Parse(function.CheckInt(jsonOj["PosId"].ToString()));
                        int UserId = int.Parse(function.CheckInt(jsonOj["UserId"].ToString()));
                        decimal RewardAmount = decimal.Parse(function.CheckInt(jsonOj["RewardAmount"].ToString()));
                        int ChangeType = int.Parse(function.CheckInt(jsonOj["ChangeType"].ToString()));
                        WebCMSEntities db = new WebCMSEntities();
                        PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == PosId) ?? new PosMachinesTwo();
                        PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId) ?? new PosMerchantInfo();
                        Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                        int BuyTopUserId = 0;
                        string ParentNav = user.ParentNav;
                        if (!string.IsNullOrEmpty(ParentNav))
                        {
                            string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                            if (ParentNavList.Length > 1)
                            {
                                BuyTopUserId = int.Parse(ParentNavList[1]);
                            }
                            else if (ParentNavList.Length == 1)
                            {
                                BuyTopUserId = int.Parse(ParentNavList[0]);
                            }
                        }
                        StatService.Instance.doActiveReward(db, merchant, pos, user.Id, user.ParentNav, BuyTopUserId, RewardAmount, ChangeType);
                        db.Dispose();
                    }
                    catch (Exception ex)
                    {                        
                        function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "设置激活奖励异常");
                    }
                }
                else
                {
                    Thread.Sleep(500);
                }
            }
        }
    }
}