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

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

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