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.Remark, m.Field1, m.Field2, m.Field3, m.Field5, m.SeoTitle }).Where(m => m.Id >= StartId && m.CreateTime >= start && m.ProductType != "14" && 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")
                            {
                                // 删除对应商户，激活机具除外
                                PxcModels.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == Bind.MerSnNo) ?? new PxcModels.PosMachinesTwo();
                                if(pos.ActivationState == 0)
                                {
                                    PxcModels.MachineForMerNo forMerNo = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == Bind.MerNo);
                                    if (forMerNo != null)
                                    {
                                        db.MachineForMerNo.Remove(forMerNo);
                                        db.SaveChanges();
                                    }
                                    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();

                                    if(pos.BuyUserId == 0 && pos.PreUserId > 0)
                                    {
                                        // RedisDbconn.Instance.Set("CheckUserBindPrePos:" + pos.PreUserId, "您的名下有已绑定的预发机 sn：" + pos.PosSn + " 尚未申请，绑定30分钟内申请即可免费自动补录，请前往客小爽产品中点击机具申请继续完成申请");

                                        RedisDbconn.Instance.AddList("CheckUserBindPrePos:" + pos.PreUserId, pos.PosSn);
                                        int ExpireTime = 60 * 25;
                                        RedisDbconn.Instance.SetExpire("CheckUserBindPrePos:" + pos.PreUserId, ExpireTime);
                                    }
                                }
                            }
                            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);
            }
        }


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

        public void StartSimDo()
        {
            while (true)
            {
                try
                {
                    WebCMSEntities spdb = new WebCMSEntities();
                    PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities();
                    DateTime start = DateTime.Now.AddDays(-60);
                    int StartId = int.Parse(function.CheckInt(function.ReadInstance("/SycnSp/BindRecordId.txt")));
                    var Binds = spdb.BindRecord.Where(m => m.Id >= StartId && m.CreateTime >= start && m.ProductType == "14" && m.Status == 1).OrderByDescending(m => m.Id).ToList();
                    foreach (var Bind in Binds)
                    {
                        try
                        {
                            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)
                            {
                                string KindName = Bind.Remark; //商品类型名称
                                string Name = Bind.Field3; //商品名称
                                pos.BindingState = 1;
                                pos.BindingTime = Bind.CreateTime;
                                pos.Status = 0;
                                pos.IsFirst = 1;
                                if(Name == "激活后补卡")
                                {
                                    PxcModels.MachineForMerNo forMerNo = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == Bind.MerNo);
                                    if(forMerNo != null)
                                    {
                                        PxcModels.PosMachinesTwo oldpos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == forMerNo.SnId);
                                        if(oldpos != null)
                                        {
                                            oldpos.IsFirst = 0;
                                            pos.BindingState = oldpos.BindingState;
                                            pos.BindingTime = oldpos.BindingTime;
                                            pos.ActivationState = oldpos.ActivationState;
                                            pos.ActivationTime = oldpos.ActivationTime;
                                        }
                                    }
                                }

                                decimal ActualAmount = decimal.Parse(function.CheckNum(Bind.SeoTitle)); //实付金额
                                string ActStatus = Bind.Field5; //激活状态名称
                                if (KindName == "基础套餐" && Name == "双百套餐" && ActStatus == "已激活" && ActualAmount >= 100)
                                {
                                    pos.Detail = "0";
                                }
                                else
                                {
                                    pos.Detail = "1";
                                }

                                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;
                                }

                                PxcModels.PosMerchantInfo add = db.PosMerchantInfo.FirstOrDefault(m => m.KqMerNo == Bind.MerNo && m.KqSnNo == Bind.MerSnNo);
                                if (add == null)
                                {
                                    add = db.PosMerchantInfo.Add(new PxcModels.PosMerchantInfo()
                                    {
                                        CreateDate = Bind.CreateTime,
                                        KqMerNo = Bind.MerNo,
                                        KqSnNo = Bind.MerSnNo,
                                        MerchantNo = Bind.MerNo.Length > 16 ? Bind.MerNo.Substring(0, 16) : Bind.MerNo,
                                    }).Entity;
                                    db.SaveChanges();
                                }
                                PxcModels.SimposMerchantInfo sim = db.SimposMerchantInfo.FirstOrDefault(m => m.KqMerNo == Bind.MerNo && m.KqSnNo == Bind.MerSnNo);
                                if (sim == null)
                                {
                                    string json = Bind.SeoDescription;
                                    string ProductName = ""; //商品名称
                                    string ActivityName = ""; //促销活动名称
                                    string ProductTypeName = ""; //商品类型名称
                                    string ActStatusName = ""; //激活状态名称
                                    string ActAmount = ""; //实付金额
                                    string EmployeeNo = ""; //员工工号
                                    string EmployeeName = ""; //员工姓名
                                    if(!string.IsNullOrEmpty(json))
                                    {
                                        JsonData jsonObj = JsonMapper.ToObject(json);
                                        ProductName = jsonObj["ProductName"].ToString();
                                        ActivityName = jsonObj["ActiveName"].ToString();
                                        ProductTypeName = jsonObj["ProductType"].ToString();
                                        ActAmount = jsonObj["ActualAmount"].ToString();
                                        ActStatusName = jsonObj["ActStatus"].ToString();
                                        EmployeeNo = jsonObj["WorkNo"].ToString();
                                        EmployeeName = jsonObj["AccountName"].ToString();
                                    }
                                    sim = db.SimposMerchantInfo.Add(new PxcModels.SimposMerchantInfo()
                                    {
                                        Id = add.Id,
                                        CreateDate = Bind.CreateTime,
                                        KqMerNo = Bind.MerNo,
                                        KqSnNo = Bind.MerSnNo,
                                        MerchantNo = Bind.MerNo.Length > 16 ? Bind.MerNo.Substring(0, 16) : Bind.MerNo,
                                        ProductName = ProductName,
                                        ActivityName = ActivityName,
                                        ProductTypeName = ProductTypeName,
                                        ActStatusName = ActStatusName,
                                        ActAmount = decimal.Parse(ActAmount),
                                        EmployeeNo = EmployeeNo,
                                        EmployeeName = EmployeeName,
                                    }).Entity;
                                    db.SaveChanges();
                                }
                                pos.BindMerchantId = add.Id;
                                pos.LastMerchantId = add.Id;
                                if(pos.CardType < 2)
                                {
                                    pos.IsPurchase = 1;
                                }

                                sim.UpdateDate = Bind.UpdateTime;
                                sim.TopUserId = 1;
                                sim.BrandId = pos.BrandId;
                                sim.SnStoreId = pos.StoreId;
                                if(ActStatus == "已激活")
                                {
                                    sim.MerStandardDate = DateTime.Now;
                                    sim.ActiveStatus = 1;
                                }
                                sim.UserId = pos.UserId;
                                sim.MgrName = Bind.MerName;
                                sim.MerStatus = 1;
                                sim.KqSnNo = pos.PosSn;
                                sim.MerRealName = Bind.MerName;
                                sim.MerchantMobile = Bind.MerNewSnNo;
                                sim.MerchantName = Bind.MerName;
                                sim.Type = pos.CardType + 1;
                                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;

                                if(Bind.Field5 == "已激活")
                                {
                                    bool PrizeFlag = pos.CardType > 0;
                                    SycnSpTradeService.Instance.ActPos(db, pos, 0, 30, PrizeFlag, Bind.SeoKeyword);
                                }
                                db.SaveChanges();
                            }
                        }
                        catch (Exception ex)
                        {
                            function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n" + Bind.Id, "同步SP绑定数据到MAIN异常");
                        }
                    }
                    spdb.SaveChanges();
                    spdb.Dispose();
                    db.SaveChanges();
                    db.Dispose();
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "同步SP绑定数据到MAIN异常");
                }
                Thread.Sleep(1000);
            }
        }
    }
}