using System;
using System.Linq;
using System.Threading;
using MySystem.Models;
using LitJson;


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

        public void Start()//启动
        {
            Thread thread = new Thread(StartDo);
            thread.IsBackground = true;
            thread.Start();
        }

        public void StartDo()
        {
            while (true)
            {
                string data = RedisDbconn.Instance.RPop<string>("SycnUserMachineCountQueue");
                if (!string.IsNullOrEmpty(data))
                {
                    JsonData json = JsonMapper.ToObject(data);
                    int UserId = int.Parse(json["UserId"].ToString());
                    int BrandId = int.Parse(json["BrandId"].ToString());
                    WebCMSEntities dbnew = new WebCMSEntities();
                    string IdBrand = UserId + "_" + BrandId;
                    UserMachineData machineData = dbnew.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
                    if (machineData == null)
                    {
                        machineData = dbnew.UserMachineData.Add(new UserMachineData()
                        {
                            IdBrand = IdBrand
                        }).Entity;
                        dbnew.SaveChanges();
                    }
                    machineData.BindCount = dbnew.PosMachinesTwo.Count(m => m.Status > -1 && m.BuyUserId == UserId && m.BrandId == BrandId && m.BindingState == 1);
                    machineData.UnBindCount = dbnew.PosMachinesTwo.Count(m => m.Status > -1 && m.BuyUserId == UserId && m.BrandId == BrandId && m.BindingState == 0);
                    machineData.TotalMachineCount = machineData.BindCount + machineData.UnBindCount;
                    dbnew.SaveChanges();
                    dbnew.Dispose();
                }
                else
                {
                    Thread.Sleep(10000);
                }
            }
        }
    }
}