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

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

        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");
                        BrandIds.Add("23");
                        BrandIds.Add("24");
                        BrandIds.Add("25");
                        BrandIds.Add("26");
                        List<string> SaveDataBindIds = Utils.Instance.SaveDataBindIds();
                        WebCMSEntities spdb = new WebCMSEntities();
                        PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities();
                        DateTime root = DateTime.Parse("2025-01-01 00:00:00");
                        DateTime start = DateTime.Now.AddDays(-30);
                        DateTime end = DateTime.Now.AddMinutes(-3);
                        int StartId = 139478000;
                        // if(StartId == 0) StartId = 133391021;
                        IQueryable<TradeRecord> trades = spdb.TradeRecord.Where(m => m.Id > StartId && !BrandIds.Contains(m.ProductType) && SaveDataBindIds.Contains(m.ProductType) && m.CreateDate >= start && m.CreateDate >= root && m.Sort == 0).OrderBy(m => m.CreateDate).Take(20);
                        foreach (TradeRecord trade in trades.ToList())
                        {
                            // StartId = trade.Id;
                            string TradeSnNo = trade.TradeSnNo;

                            bool op = true;
                            if (trade.SerEntryMode == "N" && trade.ProductType == "1") //金控押金获取
                            {
                                if (trade.TradeAmount == 9900 || trade.TradeAmount == 19900 || trade.TradeAmount == 29900)
                                {
                                    op = false;
                                }
                            }
                            else if (trade.SerEntryMode == "1" && trade.ProductType == "27") //金控押金获取
                            {
                                if (trade.TradeAmount == 9900 || trade.TradeAmount == 19900 || trade.TradeAmount == 29900)
                                {
                                    op = false;
                                }
                            }
                            else if ((trade.ProductType == "4" || trade.ProductType == "8" || trade.ProductType == "9") && (trade.Field2 == "5200" || trade.Field2 == "5800")) //乐刷海科费率0.52,0.58的不入库
                            {
                                op = false;
                            }
                            else if (trade.SerEntryMode == "1" && trade.ProductType == "10") //联动押金获取
                            {
                                if (trade.TradeAmount == 99 || trade.TradeAmount == 199 || trade.TradeAmount == 299)
                                {
                                    op = false;
                                }
                            }
                            else if (trade.SerEntryMode == "40" && trade.ProductType == "12") //盒易付押金获取
                            {
                                if (trade.TradeAmount == 99 || trade.TradeAmount == 199 || trade.TradeAmount == 299)
                                {
                                    op = false;
                                }
                            }
                            else if (trade.TradeType == "40" && trade.ProductType == "15") //联客宝押金获取
                            {
                                if (trade.TradeAmount == 99 || trade.TradeAmount == 199 || trade.TradeAmount == 299)
                                {
                                    op = false;
                                }
                            }
                            else if (trade.SerEntryMode == "DEPOSIT" && trade.ProductType == "30") //拉卡拉押金获取
                            {
                                if (trade.TradeAmount == 9900 || trade.TradeAmount == 19900 || trade.TradeAmount == 29900)
                                {
                                    op = false;
                                }
                            }
                            if (trade.DiscountRateFlag == "True")
                            {
                                op = false;
                            }
                            if (trade.ProductType == "7" && trade.TradeStatus != "00")
                            {
                                op = false;
                            }
                            if (op)
                            {
                                string check = RedisDbconn.Instance.Get<string>("helpprofit:" + trade.TradeSerialNo);
                                if (string.IsNullOrEmpty(check))
                                {
                                    RedisDbconn.Instance.Set("helpprofit:" + trade.TradeSerialNo, trade.TradeSerialNo);
                                    RedisDbconn.Instance.SetExpire("helpprofit:" + trade.TradeSerialNo, 10);
                                    PxcModels.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == TradeSnNo);
                                    if (pos != null)
                                    {
                                        PxcModels.KqProducts brand = db.KqProducts.FirstOrDefault(m => m.Id == pos.BrandId) ?? new PxcModels.KqProducts();
                                        if (pos.BindMerchantId > 0)
                                        {
                                            PxcModels.Users user = db.Users.FirstOrDefault(m => m.Id == pos.UserId) ?? new PxcModels.Users();
                                            int TopUserId = 0;
                                            if (!string.IsNullOrEmpty(user.ParentNav))
                                            {
                                                TopUserId = int.Parse(user.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                                            }
                                            decimal TradeAmount = trade.TradeAmount;
                                            int BankCardType = -1;
                                            int QrPayFlag = 0;
                                            int VipFlag = 0;
                                            int PayType = 0;
                                            if (pos.BrandId == 1 || pos.BrandId == 3)
                                            {
                                                TradeAmount = TradeAmount / 100;
                                                BankCardType = int.Parse(trade.BankCardType);
                                                if (trade.TradeType == "02") QrPayFlag = 1;
                                                else if (trade.TradeType == "NQ") PayType = 1;
                                                if (trade.SettleMethod == "E") VipFlag = 1;
                                            }
                                            else if (pos.BrandId == 2)
                                            {
                                                if (trade.TradeType == "CREDIT_BY_CARD")
                                                {
                                                    BankCardType = 1;
                                                }
                                                else
                                                {
                                                    BankCardType = 0;
                                                }
                                                if (trade.TradeType == "CLOUD_PAY") QrPayFlag = 1;
                                            }
                                            else if (pos.BrandId == 4 || pos.BrandId == 5)
                                            {
                                                TradeAmount = TradeAmount / 100;
                                                if (trade.BankCardType == "100")
                                                {
                                                    BankCardType = 1;
                                                }
                                                else if (trade.BankCardType == "200")
                                                {
                                                    BankCardType = 0;
                                                }
                                                if (trade.TradeType == "200") QrPayFlag = 1;
                                                if (trade.Field1 == "1") VipFlag = 1;
                                            }
                                            else if (pos.BrandId == 6 || pos.BrandId == 22)
                                            {
                                                TradeAmount = TradeAmount / 100;
                                                if (trade.BankCardType == "02" || trade.BankCardType == "12")
                                                {
                                                    BankCardType = 1;
                                                }
                                                else
                                                {
                                                    BankCardType = 0;
                                                }
                                            }
                                            else if (pos.BrandId == 7)
                                            {
                                                TradeAmount = TradeAmount / 100;
                                                if (trade.BankCardType == "OA" || trade.BankCardType == "CC" || trade.BankCardType == "SCC")
                                                {
                                                    BankCardType = 1;
                                                }
                                                else
                                                {
                                                    BankCardType = 0;
                                                }
                                            }
                                            else if (pos.BrandId == 8 || pos.BrandId == 9)
                                            {
                                                TradeAmount = TradeAmount / 100;
                                                if (trade.BankCardType == "100")
                                                {
                                                    BankCardType = 1;
                                                }
                                                else if (trade.BankCardType == "200")
                                                {
                                                    BankCardType = 0;
                                                }
                                                if (trade.TradeType == "200") QrPayFlag = 1;
                                                if (trade.Field1 == "1") VipFlag = 1;
                                            }
                                            else if (pos.BrandId == 10 || pos.BrandId == 11)
                                            {
                                                if (trade.BankCardType == "01")
                                                {
                                                    BankCardType = 1;
                                                }
                                                else if (trade.BankCardType == "00")
                                                {
                                                    BankCardType = 0;
                                                }
                                                if (trade.TradeType == "F010") QrPayFlag = 1;
                                            }
                                            else if (pos.BrandId == 12 || pos.BrandId == 13) //盒易付
                                            {
                                                if (trade.BankCardType == "C")
                                                {
                                                    BankCardType = 1;
                                                }
                                                else if (trade.BankCardType == "D")
                                                {
                                                    BankCardType = 0;
                                                }
                                                if (trade.Field3 == "1") QrPayFlag = 1;
                                            }
                                            else if (pos.BrandId == 15 || pos.BrandId == 16) //联客宝
                                            {
                                                TradeAmount = TradeAmount / 100;
                                                // 支付类型
                                                // 01-内卡借记卡
                                                // 02-内卡贷记卡
                                                // 03-银联二维码
                                                // 11-外卡借记卡
                                                // 12-外卡贷记卡
                                                // 30-微信
                                                // 31-支付宝
                                                // M3-扫码（银联二维码、微信、支付宝）
                                                if (trade.BankCardType == "02")
                                                {
                                                    BankCardType = 1;
                                                }
                                                else
                                                {
                                                    BankCardType = 0;
                                                }
                                            }
                                            else if (pos.BrandId == 30 || pos.BrandId == 31) //拉卡拉
                                            {
                                                TradeAmount = TradeAmount / 100;
                                                if (trade.BankCardType == "01" || trade.BankCardType == "61")
                                                {
                                                    BankCardType = 1;
                                                }
                                                else
                                                {
                                                    BankCardType = 0;
                                                }
                                            }
                                            int BrandId = pos.BrandId;
                                            decimal SourceTradeAmount = TradeAmount;
                                            decimal CheckMoney = brand.ActTradeAmount > 0 ? brand.ActTradeAmount : 1000;
                                            //判断激活条件并激活
                                            if (TradeAmount > 0)
                                            {
                                                ulong MerHelpFlag = 0;
                                                int CapFlag = 0;
                                                if (BankCardType == 0 && TradeAmount >= 1666.67M)
                                                {
                                                    CapFlag = 1;
                                                }
                                                string HelpProfitFlag = "";
                                                bool checkHelpProfit = db.HelpProfitMerchantForUser.Any(m => m.MerchantId == pos.BindMerchantId);
                                                if (checkHelpProfit)
                                                {
                                                    HelpProfitFlag = "HelpProfit";
                                                }
                                                int ActStatus = pos.ActivationState;
                                                int Version = 0;
                                                if (MerHelpFlag == 2) Version = 1;
                                                if (MerHelpFlag == 3) Version = 2;
                                                //盒易付和来客吧电签，稳定期自动转到稳定期A
                                                if ((pos.BrandId == 12 || pos.BrandId == 13) && MerHelpFlag == 0 && Version == 0)
                                                {
                                                    Version = 1;
                                                }
                                                if (Utils.Instance.IsWifi(pos.BrandId))
                                                {
                                                    MerHelpFlag = 1;
                                                    Version = 0;
                                                }
                                                decimal SettleFee = trade.SettleFee * 100;
                                                PxcModels.TradeRecord add = db.TradeRecord.Add(new PxcModels.TradeRecord()
                                                {
                                                    ParentNav = user.ParentNav,
                                                    CreateDate = trade.CreateDate,
                                                    UpdateDate = trade.UpdateDate,
                                                    RecordNo = trade.TradeSerialNo, //单号
                                                    UserId = pos.UserId, //创客
                                                    MerchantId = pos.BindMerchantId, //商户
                                                    MerNo = trade.MerNo, //渠道商户编号
                                                    MerHelpFlag = MerHelpFlag >= 2 ? 1 : MerHelpFlag, //1扶持周,0稳定期,2盈利期
                                                    HelpMonthCount = 0, //扶持第几个月
                                                    MerBuddyType = user.MerchantType, //商户创客类型
                                                    SnNo = TradeSnNo, //渠道SN号
                                                    TradeSerialNo = trade.ChannelSerial, //交易流水号
                                                    TradeAmount = TradeAmount, //交易金额
                                                    BankCardType = BankCardType, //银行卡类型
                                                    QrPayFlag = QrPayFlag, //云闪付标识
                                                    CapFlag = CapFlag, //借记卡是否封顶
                                                    VipFlag = VipFlag, //会员标记
                                                    PayType = PayType, //支付方式
                                                    BrandId = BrandId, //品牌
                                                    Remark = trade.TradeType == "2" && trade.ProductType == "12" ? "吱码SN:" + trade.TradeSnNo : trade.Remark, //备注
                                                    TopUserId = TopUserId, //顶级创客
                                                    MerUserId = pos.UserId, //商户直属创客M
                                                    SeoTitle = HelpProfitFlag,
                                                    Version = Version,
                                                    ActStatus = ActStatus,
                                                    CreateMan = trade.AgentNo,
                                                    UpdateMan = trade.BankCardType,
                                                    SeoKeyword = trade.SerEntryMode,
                                                    SeoDescription = trade.TradeType,
                                                    Sort = (int)SettleFee,
                                                    TradeDate = pos.BindingTime,
                                                }).Entity;
                                                db.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }
                            // function.WritePage("/SycnSp/", "TradeRecordIdForHelp.txt", StartId.ToString());
                            TradeRecord edit = spdb.TradeRecord.FirstOrDefault(m => m.Id == trade.Id);
                            if (edit != null)
                            {
                                edit.Sort = 1;
                            }
                            spdb.SaveChanges();
                        }
                        spdb.Dispose();
                        db.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "同步SP交易数据到助利宝异常");
                }
                Thread.Sleep(500);
            }
        }
    }
}