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
                {
                    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 && m.Status == 1).OrderByDescending(m => m.Id).ToList();
                    foreach (UnBindRecord Bind in Binds)
                    {
                        var tran = db.Database.BeginTransaction();
                        try
                        {
                            string PosSn = Bind.MerSnNo;
                            string MerNo = Bind.MerNo;
                            PxcModels.MachineForSnNo forSnNo = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == PosSn) ?? new PxcModels.MachineForSnNo();
                            PxcModels.MachineForMerNo forMerNo = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == MerNo) ?? new PxcModels.MachineForMerNo();
                            PxcModels.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == forSnNo.SnId) ?? new PxcModels.PosMachinesTwo();
                            if (pos.ActivationState == 0 && pos.BuyUserId > 0)
                            {
                                string BrandName = RelationClass.GetKqProductsInfo(pos.BrandId);
                                if (forMerNo != null)
                                {
                                    // 删除对应商户
                                    PxcModels.MachineForMerNo MerEdit = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == MerNo);
                                    if (MerEdit != null)
                                    {
                                        db.MachineForMerNo.Remove(MerEdit);
                                        db.SaveChanges();
                                    }
                                    PxcModels.PosMachinesTwo EditPos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == PosSn) ?? new PxcModels.PosMachinesTwo();
                                    PxcModels.PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == EditPos.BindMerchantId);
                                    if(merchant != null)
                                    {
                                        pos.BindMerchantId = 0;
                                        pos.BindingState = 0;
                                        pos.BindingTime = null;
                                        db.PosMerchantInfo.Remove(merchant);
                                        db.SaveChanges();
                                    }
                                }
                                db.MachineUnBind.Add(new PxcModels.MachineUnBind()
                                {
                                    CreateDate = DateTime.Now,
                                    MerchantId = pos.BindMerchantId,
                                    AuditDate = DateTime.Now,
                                    AuditDesc = BrandName + "推送解绑",
                                    AuditStatus = 1,
                                    SnNo = pos.PosSn,
                                    BrandId = pos.BrandId,
                                    UserId = pos.BuyUserId,
                                    ApplyNo = "U" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8),
                                });
                                pos.BindMerchantId = 0;
                                pos.BindingState = 0;
                                pos.BindingTime = DateTime.Parse("1900-01-01");
                                pos.UserId = pos.BuyUserId;
                                string IdBrand = pos.BuyUserId + "_" + pos.BrandId;
                                PxcModels.UserMachineData userData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
                                if (userData == null)
                                {
                                    userData = db.UserMachineData.Add(new PxcModels.UserMachineData()
                                    {
                                        IdBrand = IdBrand,
                                    }).Entity;
                                    db.SaveChanges();
                                }
                                userData.BindCount -= 1;
                                userData.UnBindCount += 1;
                                db.SaveChanges();

                                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();
                            function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n" + Bind.Id, "同步SP解绑数据到MAIN异常");
                        }
                        tran.Dispose();
                    }
                    spdb.Dispose();
                    db.Dispose();
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "同步SP解绑数据到MAIN异常");
                }
                Thread.Sleep(1000);
            }
        }
    }
}