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

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

        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(-100);
                    DateTime end = DateTime.Now.AddMinutes(-2);
                    int StartId = int.Parse(function.CheckInt(function.ReadInstance("/SycnSp/MerchantsId.txt")));
                    var Mers = spdb.Merchants.Where(m => m.Id >= StartId && m.CreateTime >= start && m.CreateTime <= end && m.Status == 1 && m.ProductType != "14" && SaveDataBindIds.Contains(m.ProductType)).OrderByDescending(m => m.Id).Take(20).ToList();
                    // var Mers = spdb.Merchants.Where(m => m.Id == 765841).ToList();
                    foreach (var Mer in Mers)
                    {
                        var tran = db.Database.BeginTransaction();
                        try
                        {
                            if (Mer.Field2 != "解绑" && Mer.Field2 != "UNBIND" && Mer.Field2 != "CHANGE_BIND" && Mer.Field2 != "TRUE")
                            {
                                string rnd = "";
                                if (!Utils.Instance.IsWifi(int.Parse(Mer.ProductType)) && !Utils.Instance.IsHaoDa(int.Parse(Mer.ProductType)) && Mer.ProductType != "14")
                                {
                                    rnd = GetRandom(spdb, Mer.SnNo, Mer.MerNo);
                                }
                                if (Utils.Instance.IsWifi(int.Parse(Mer.ProductType)))
                                {
                                    Mer.MerNo = Mer.SnNo;
                                    PosPushDataNewHelper.Bind(Mer);
                                    if (function.CheckNull(Mer.AgentName).StartsWith("YCJG"))
                                    {
                                        PosPushDataNewHelper.Deposit(new ActivateRecord()
                                        {
                                            SeoTitle = "0.00",
                                            ProductType = Mer.ProductType,
                                            SnNo = Mer.SnNo,
                                            MerNo = Mer.SnNo,
                                            Id = Mer.Id,
                                        });
                                    }
                                }
                                else if (Mer.ProductType == "12" || Mer.ProductType == "30" || Mer.ProductType == "34")
                                {
                                    MerchantRecord merInfo = new MerchantRecord();
                                    if (Mer.ProductType == "12" || Mer.ProductType == "34") merInfo = spdb.MerchantRecord.FirstOrDefault(m => m.MerNo == Mer.MerNo);
                                    if (Mer.ProductType == "30")
                                    {
                                        merInfo = spdb.MerchantRecord.FirstOrDefault(m => m.Field3 == Mer.MerNo);
                                        if (merInfo == null) merInfo = spdb.MerchantRecord.FirstOrDefault(m => m.MerNo == Mer.MerNo);
                                    }
                                    if (merInfo != null)
                                    {
                                        Mer.MerNo = merInfo.MerNo;
                                        Mer.MerIdcardNo = merInfo.LegalIdCard;
                                        Mer.MerName = merInfo.MerName;
                                        if (Mer.ProductType == "30")
                                        {
                                            Mer.MerMobile = merInfo.Field2;
                                        }
                                        if (Mer.ProductType == "34")
                                        {
                                            Mer.MerMobile = merInfo.MerNewSnNo;
                                        }
                                        PosPushDataNewHelper.Bind(Mer, rnd);
                                    }
                                }
                                else if (!Utils.Instance.IsHaoDa(int.Parse(Mer.ProductType)))
                                {
                                    PosPushDataNewHelper.Bind(Mer, rnd);
                                }
                            }
                            Merchants edit = spdb.Merchants.FirstOrDefault(m => m.Id == Mer.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" + Mer.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 string GetRandom(WebCMSEntities spdb, string sn, string merno)
        {
            var list = spdb.BindRecord.Select(m => new { m.MerSnNo, m.MerNo, m.CreateTime }).Where(m => m.MerSnNo == sn && m.MerNo == merno).ToList().Select(m => m.CreateTime).Distinct().ToList();
            if(list.Count > 1)
            {
                return function.get_Random(5);
            }
            return "";
        }

        public void WifiSendPrize(PxcModels.WebCMSEntities db, PxcModels.PosMachinesTwo pos, PxcModels.PosMerchantInfo add)
        {
            PxcModels.WifiTradeRecord trade = db.WifiTradeRecord.FirstOrDefault(m => m.SnNo == pos.PosSn && m.Status == 0);
            if (trade != null)
            {
                trade.Status = 1;
                db.SaveChanges();
                decimal Prize = trade.TradeAmount * 0.15M;
                StatService.Instance.doActiveReward(db, add, pos, pos.BuyUserId, "", 1, Prize);
                if (pos.CardType < 100)
                {
                    RedisDbconn.Instance.AddList("OpenRewardQueue", pos.Id.ToString());
                }
                if (pos.LeaderUserId > 0 && db.Leaders.Any(m => m.Id == pos.LeaderUserId && m.ExpiredDate > DateTime.Now) && pos.CardType < 100)
                {
                    RedisDbconn.Instance.AddList("LeaderPrizeQueue", pos.Id);
                }
                if (pos.CardType < 100)
                {
                    RedisDbconn.Instance.AddList("OperatePrizeQueue", pos.Id);
                }
            }
        }






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

        public void StartSimDo()
        {
            while (true)
            {
                try
                {
                    List<string> SaveDataBindIds = Utils.Instance.SaveDataBindIds();
                    WebCMSEntities spdb = new WebCMSEntities();
                    PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities();
                    DateTime start = DateTime.Now.AddDays(-365);
                    DateTime end = DateTime.Now.AddMinutes(-2);
                    int StartId = 400000;
                    var Mers = spdb.Merchants.Where(m => m.Id >= StartId && m.CreateTime >= start && m.CreateTime <= end && m.Status == 1 && m.ProductType == "14" && SaveDataBindIds.Contains(m.ProductType)).OrderByDescending(m => m.Id).Take(20).ToList();
                    foreach (var Mer in Mers)
                    {
                        var tran = db.Database.BeginTransaction();
                        try
                        {
                            if (Mer.Field2 != "解绑" && Mer.Field2 != "UNBIND")
                            {
                                if (!Utils.Instance.IsHaoDa(int.Parse(Mer.ProductType)))
                                {
                                    PosPushDataNewHelper.Bind(Mer);
                                }
                            }
                            Merchants edit = spdb.Merchants.FirstOrDefault(m => m.Id == Mer.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" + Mer.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);
            }
        }
    }
}