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

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

        public string Start()
        {
            bool op = true;
            WebCMSEntities db = new WebCMSEntities();
            string result = "";
            // int total = 0;
            while (op)
            {
                ConsumerOrders PopData = new ConsumerOrders();
                try
                {
                    //获取apserver待同步的数据，执行入库
                    PopData = RedisDbconn.Instance.RPop<ConsumerOrders>("Pop:ConsumerOrders");
                    if (PopData != null)
                    {
                        ConsumerOrders checkExist = db.ConsumerOrders.FirstOrDefault(m => m.Id == PopData.Id);
                        if (checkExist != null)
                        {
                            checkExist = PopData;
                            db.SaveChanges();
                        }
                        else
                        {
                            ConsumerOrders item = db.ConsumerOrders.Add(PopData).Entity;
                            db.SaveChanges();
                            RedisDbconn.Instance.AddList("ConsumerOrders:Divi:" + PopData.MerchantId, item);
                            RedisDbconn.Instance.AddList("ConsumerOrders:Divi:List", item.Id.ToString());
                        }
                        // if (total >= 20)
                        // {
                        //     total = 0;
                        // }
                        if (string.IsNullOrEmpty(result)) result = "success";
                    }
                    else
                    {
                        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:ConsumerOrders:Error");
                    result = "有异常，请查看Pop:ConsumerOrders:Error队列";
                }
            }
            db.Dispose();
            return result;
        }
    }
}