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

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

        public string Start()
        {
            bool op = true;
            WebCMSEntities db = new WebCMSEntities();
            string result = "";
            int total = 0;
            while (op)
            {
                TeamApply PopData = new TeamApply();
                try
                {
                    //获取apserver待同步的数据，执行入库
                    PopData = RedisDbconn.Instance.RPop<TeamApply>("Pop:TeamApply");
                    if (PopData != null)
                    {
                        TeamApply checkExist = db.TeamApply.FirstOrDefault(m => m.Id == PopData.Id);
                        if (checkExist != null)
                        {
                            checkExist = PopData;
                        }
                        else
                        {
                            db.TeamApply.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();
                    LogHelper.Instance.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(msg), "Pop:TeamApply:Error");
                    result = "有异常，请查看Pop:TeamApply:Error队列";
                }
            }
            db.Dispose();
            return result;
        }
    }
}