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

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

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

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

                            UnBindRecord edit = spdb.UnBindRecord.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);
            }
        }
    }
}