using Library;
using MySystem.Models;
using System;
using System.Linq;

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

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