using Library;
using MySystem.PxcModels;
using System;
using System.Linq;

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

        public string Start()
        {
            bool op = true;
            WebCMSEntities db = new WebCMSEntities();
            string result = "";
            int total = 0;
            while (op)
            {
                Consumers PopData = new Consumers();
                try
                {
                    //获取apserver待同步的数据，执行入库
                    PopData = RedisDbconn.Instance.RPop<Consumers>("Pop:Consumers");
                    if (PopData != null)
                    {
                        Consumers checkExist = db.Consumers.FirstOrDefault(m => m.Id == PopData.Id);
                        if (checkExist != null)
                        {
                            checkExist = PopData;
                        }
                        else
                        {
                            db.Consumers.Add(PopData);
                        }
                        total += 1;
                        if (total >= 20)
                        {
                            total = 0;
                            db.SaveChanges();
                        }
                        if (string.IsNullOrEmpty(result)) result = "success";
                    }
                    else
                    {
                        if (total > 0)
                        {
                            db.SaveChanges();
                        }
                        op = false;
                    }
                }
                catch (Exception ex)
                {
                    ErrorMsg msg = new ErrorMsg();
                    msg.Obj = PopData;
                    msg.Time = DateTime.Now;
                    msg.ErrorContent = ex.ToString();
                    Utils.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(msg), "Pop:Consumers:Error");
                    result = "有异常，请查看Pop:Consumers:Error队列";
                }
            }
            db.Dispose();
            return result;
        }
    }
}