using System;
using System.Collections.Generic;
using System.Linq;
using MySystem.SpModels;
using Library;
using LitJson;
using System.Threading;

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

        public void Start()
        {
            Thread th = new Thread(StartDo);
            th.IsBackground = true;
            th.Start();
        }

        public void StartDo()
        {
            while (true)
            {
                try
                {
                    if (Utils.PushTimeCheck())
                    {
                        List<string> SaveDataBindIds = Utils.Instance.SaveDataBindIds();
                        WebCMSEntities spdb = new WebCMSEntities();
                        PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities();
                        DateTime start = DateTime.Now.AddDays(-30);
                        List<ChangeBindRecord> Binds = spdb.ChangeBindRecord.Where(m => m.ReBindTime >= start && SaveDataBindIds.Contains(m.ProductType) && m.Status == 1).OrderByDescending(m => m.Id).ToList();
                        foreach (ChangeBindRecord Bind in Binds)
                        {
                            var tran = db.Database.BeginTransaction();
                            try
                            {
                                PosPushDataNewHelper.ChangeBind(Bind);

                                ChangeBindRecord edit = spdb.ChangeBindRecord.FirstOrDefault(m => m.Id == Bind.Id);
                                if (edit != null)
                                {
                                    edit.Status = 2;
                                    spdb.SaveChanges();
                                }

                                tran.Commit();
                            }
                            catch (Exception ex)
                            {
                                tran.Rollback();
                                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n" + Bind.Id, "同步SP换绑数据到MAIN异常");
                            }
                            tran.Dispose();
                        }
                        spdb.Dispose();
                        db.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "同步SP换绑数据到MAIN异常");
                }
                Thread.Sleep(1000);
            }
        }
    }
}