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
                {
                    if (Utils.PushTimeCheck())
                    {
                        List<string> BrandIds = new List<string>();
                        BrandIds.Add("14");
                        BrandIds.Add("17");
                        List<string> SaveDataBindIds = Utils.Instance.SaveDataBindIds();
                        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 && !BrandIds.Contains(m.ProductType) && SaveDataBindIds.Contains(m.ProductType) && m.Status == 1).OrderByDescending(m => m.Id).Take(20).ToList();
                        foreach (var Bind in Binds)
                        {
                            var tran = db.Database.BeginTransaction();
                            try
                            {
                                if ((Bind.Field1 == "解绑" || Bind.Field1 == "UNBIND" || Bind.Field1 == "TRUE" || Bind.Field1 == "FORCED_UNBIND") && (Bind.ProductType == "1" || Bind.ProductType == "23" || Bind.ProductType == "27" || Bind.ProductType == "30" || Bind.ProductType == "34"))
                                {
                                    PosPushDataNewHelper.UnBind(new UnBindRecord()
                                    {
                                        MerSnNo = Bind.MerSnNo,
                                        MerNo = Bind.MerNo,
                                        ProductType = Bind.ProductType,
                                    });

                                    //wifi解绑逻辑
                                    if (Utils.Instance.IsWifi(int.Parse(Bind.ProductType)))
                                    {
                                        string fileName = function.MD5_16(Guid.NewGuid().ToString());
                                        string content = "{\"posSn\":\"" + Bind.MerSnNo + "\"}";
                                        RedisDbconn.Instance.AddList("kxs_unbindwifi_list", fileName + "#cut#" + content + "#cut#" + fileName);
                                    }
                                }
                                else if (Bind.Field1 == "CHANGE_BIND" && Bind.ProductType == "34")
                                {
                                    PosPushDataNewHelper.ChangeBind(new ChangeBindRecord()
                                    {
                                        MerNo = Bind.MerNo,
                                        MerSnNo = Bind.Field2,
                                        ProductType = Bind.ProductType,
                                        MerNewSnNo = Bind.MerSnNo,
                                    });
                                }
                                else
                                {
                                    if (Utils.Instance.IsWifi(int.Parse(Bind.ProductType)))
                                    {
                                        Bind.MerNo = Bind.MerSnNo;
                                        PosPushDataNewHelper.Bind0(Bind);
                                    }
                                }
                                BindRecord edit = spdb.BindRecord.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.SaveChanges();
                        spdb.Dispose();
                        db.SaveChanges();
                        db.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    Utils.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
                {
                    if (Utils.PushTimeCheck())
                    {
                        List<string> SaveDataBindIds = Utils.Instance.SaveDataBindIds();
                        WebCMSEntities spdb = new WebCMSEntities();
                        PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities();
                        DateTime start = DateTime.Now.AddDays(-365);
                        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" && SaveDataBindIds.Contains(m.ProductType) && m.Status == 1).OrderByDescending(m => m.Id).Take(20).ToList();
                        foreach (var Bind in Binds)
                        {
                            try
                            {
                                string KindName = Bind.Remark; //商品类型名称
                                string Name = Bind.Field3; //商品名称
                                decimal ActualAmount = decimal.Parse(function.CheckNum(Bind.SeoTitle)); //实付金额
                                if (ActualAmount >= 10000) ActualAmount = ActualAmount / 100;
                                // PosPushDataNewHelper.Trade(new TradeRecord()
                                // {
                                //     TradeSnNo = Bind.MerSnNo,
                                //     MerNo = Bind.MerNo,
                                //     TradeAmount = 0,
                                //     TradeSerialNo = function.MD5_16("sim:" + Bind.Id.ToString()),
                                //     CreateDate = Bind.CreateTime,
                                //     ProductType = Bind.ProductType,
                                //     Field1 = Bind.Field3,
                                //     Field2 = Bind.Field5,
                                //     ErrorMsg = ActualAmount.ToString(),
                                // });
                                // bool op = false;
                                // if(!Bind.MerSnNo.StartsWith("CS") && Bind.Field5 == "已激活" && Bind.Field3.Contains("双百套餐") && ActualAmount >= 100)
                                // {
                                //     op = true;
                                // }
                                // if(Bind.MerSnNo.StartsWith("CS") && Bind.Field5 == "已激活" && ActualAmount >= 100)
                                // {
                                //     op = true;
                                // }
                                if (Bind.Field5 == "已激活")
                                {
                                    PosPushDataNewHelper.Deposit(new ActivateRecord()
                                    {
                                        SeoKeyword = Bind.Field3,
                                        SeoTitle = ActualAmount.ToString(),
                                        ProductType = Bind.ProductType,
                                        SnNo = Bind.MerSnNo,
                                        MerNo = Bind.MerNo,
                                        Id = Bind.Id,
                                    });
                                }
                                BindRecord edit = spdb.BindRecord.FirstOrDefault(m => m.Id == Bind.Id);
                                if (edit != null)
                                {
                                    edit.Status = 2;
                                    spdb.SaveChanges();
                                }
                            }
                            catch (Exception ex)
                            {
                                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n" + Bind.Id, "同步SP广电卡绑定数据到MAIN异常");
                            }
                        }
                        spdb.SaveChanges();
                        spdb.Dispose();
                        db.SaveChanges();
                        db.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "同步SP广电卡绑定数据到MAIN异常");
                }
                Thread.Sleep(1000);
            }
        }
    }
}