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

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

        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(-5);
                    int StartId = int.Parse(function.CheckInt(function.ReadInstance("/SycnSp/BindRecordId.txt")));
                    var Binds = spdb.BindRecord.Select(m => new { m.Id, m.CreateTime, m.Status, m.MerNo, m.MerSnNo, m.ProductType, m.Field1 }).Where(m => m.Id >= StartId && m.CreateTime >= start && m.Status == 1).OrderByDescending(m => m.Id).ToList();
                    foreach (var Bind in Binds)
                    {
                        var tran = db.Database.BeginTransaction();
                        try
                        {
                            if(Bind.Field1 == "解绑" && Bind.ProductType == "1")
                            {
                                // string PosSn = Bind.MerSnNo;
                                // string MerNo = Bind.MerNo;
                                // PxcModels.MachineForSnNo forSnNo = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == PosSn);
                                // PxcModels.MachineForMerNo forMerNo = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == MerNo);
                                // PxcModels.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == forSnNo.SnId);
                                // if (pos.ActivationState == 0 && pos.BuyUserId > 0 && pos.BindingState == 0)
                                // {
                                //     if (forMerNo != null)
                                //     {
                                //         db.MachineForMerNo.Remove(forMerNo);
                                //         db.SaveChanges();
                                //     }
                                //     db.MachineUnBind.Add(new PxcModels.MachineUnBind()
                                //     {
                                //         CreateDate = DateTime.Now,
                                //         MerchantId = pos.BindMerchantId,
                                //         AuditDate = DateTime.Now,
                                //         AuditDesc = "金控推送解绑",
                                //         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();

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

                                // 删除对应商户
                                PxcModels.MachineForMerNo forMerNo = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == Bind.MerNo);
                                if (forMerNo != null)
                                {
                                    db.MachineForMerNo.Remove(forMerNo);
                                    db.SaveChanges();
                                }
                                PxcModels.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == Bind.MerSnNo) ?? new PxcModels.PosMachinesTwo();
                                PxcModels.PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId);
                                if(merchant != null)
                                {
                                    //备份解绑的商户信息
                                    CustomerSqlConn.op("insert into PosMerchantInfoBak select * from PosMerchantInfo where Id=" + pos.BindMerchantId, MysqlConn.SqlConnStr);
                                    db.SaveChanges();
                                    pos.BindMerchantId = 0;
                                    pos.BindingState = 0;
                                    pos.BindingTime = null;
                                    db.PosMerchantInfo.Remove(merchant);
                                    db.SaveChanges();
                                }

                                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();

                                BindRecord edit = spdb.BindRecord.FirstOrDefault(m => m.Id == Bind.Id);
                                if (edit != null)
                                {
                                    edit.Status = 2;
                                    spdb.SaveChanges();
                                }
                            }
                            else
                            {
                                PxcModels.MachineForSnNo posFor = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == Bind.MerSnNo) ?? new PxcModels.MachineForSnNo();
                                PxcModels.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == posFor.SnId);
                                if (pos != null)
                                {
                                    pos.BindingState = 1;
                                    pos.BindingTime = Bind.CreateTime;
                                    pos.Status = 0;
                                    PxcModels.MachineForMerNo merFor = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == Bind.MerNo);
                                    if (merFor == null)
                                    {
                                        merFor = db.MachineForMerNo.Add(new PxcModels.MachineForMerNo()
                                        {
                                            MerNo = Bind.MerNo,
                                            SnId = pos.Id,
                                        }).Entity;
                                    }
                                    else
                                    {
                                        merFor.SnId = pos.Id;
                                    }
                                    db.SaveChanges();

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

                                    string IdBrand = pos.UserId + "_" + pos.BrandId;
                                    PxcModels.UserMachineData MachineData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
                                    if (MachineData == null)
                                    {
                                        MachineData = db.UserMachineData.Add(new PxcModels.UserMachineData()
                                        {
                                            IdBrand = IdBrand,
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    MachineData.BindCount += 1;
                                    MachineData.UnBindCount -= 1;
                                    db.SaveChanges();
                                }
                            }
                            tran.Commit();
                        }
                        catch (Exception ex)
                        {
                            tran.Rollback();
                            function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n" + Bind.Id, "同步SP绑定数据到MAIN异常");
                        }
                        tran.Dispose();
                    }
                    spdb.SaveChanges();
                    spdb.Dispose();
                    db.SaveChanges();
                    db.Dispose();
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "同步SP绑定数据到MAIN异常");
                }
                Thread.Sleep(1000);
            }
        }
    }
}