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

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

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