using System;
using System.Collections.Generic;
using System.Linq;
using MySystem.Models;
using Library;
using LitJson;

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

        public void Start(string PosSn, DateTime start, DateTime end)
        {
            SpModels.WebCMSEntities spdb = new SpModels.WebCMSEntities();
            WebCMSEntities db = new WebCMSEntities();
            IQueryable<SpModels.TradeRecord> trades = spdb.TradeRecord.Where(m => m.CreateDate >= start && m.CreateDate < end && m.TradeSnNo == PosSn);
            foreach (SpModels.TradeRecord trade in trades.ToList())
            {
                bool op = true;
                if (trade.SerEntryMode == "N")
                {
                    if (trade.TradeAmount == 9900 || trade.TradeAmount == 19900 || trade.TradeAmount == 29900)
                    {
                        op = false;
                        MachineForMerNo posFor = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == trade.MerNo) ?? new MachineForMerNo();
                        PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == posFor.SnId);
                        if (pos != null)
                        {
                            if (trade.SerEntryMode == "N" && trade.ProductType == "1")
                            {
                                pos.SeoKeyword = trade.TradeAmount.ToString("f2");
                                // pos.IsPurchase = 0;
                                db.SaveChanges();
                            }
                        }
                        SpModels.TradeRecord edit = spdb.TradeRecord.FirstOrDefault(m => m.Id == trade.Id);
                        if (edit != null)
                        {
                            edit.Status = 2;
                        }
                        spdb.SaveChanges();
                    }
                }
                if (trade.DiscountRateFlag == "True")
                {
                    op = false;
                    SpModels.TradeRecord edit = spdb.TradeRecord.FirstOrDefault(m => m.Id == trade.Id);
                    if (edit != null)
                    {
                        edit.Status = 2;
                    }
                    spdb.SaveChanges();
                }
                if(trade.ProductType == "7" && trade.TradeStatus != "00")
                {
                    op = false;
                    SpModels.TradeRecord edit = spdb.TradeRecord.FirstOrDefault(m => m.Id == trade.Id);
                    if (edit != null)
                    {
                        edit.Status = 2;
                    }
                    spdb.SaveChanges();
                }
                if (op)
                {
                    MachineForMerNo posFor = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == trade.MerNo) ?? new MachineForMerNo();
                    PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == posFor.SnId);
                    if (pos != null)
                    {
                        if (pos.BindMerchantId > 0)
                        {
                            Users user = db.Users.FirstOrDefault(m => m.Id == pos.UserId) ?? new Users();
                            int TopUserId = 0;
                            if (!string.IsNullOrEmpty(user.ParentNav))
                            {
                                TopUserId = int.Parse(user.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                            }
                            // TODO: 交易记录表，每月的Id单独存放，解决查询效率问题
                            bool check = db.TradeRecord.Any(m => m.Id >= 700000 && m.RecordNo == trade.TradeSerialNo);
                            if (!check)
                            {
                                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 == "DEBIT_BY_CARD")
                                    {
                                        BankCardType = 0;
                                    }
                                    else
                                    {
                                        BankCardType = 1;
                                    }
                                    if (trade.TradeType == "CLOUD_PAY") QrPayFlag = 1;
                                }
                                else if (pos.BrandId == 4 || pos.BrandId == 5 || 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 == 6)
                                {
                                    TradeAmount = TradeAmount / 100;
                                    if (trade.BankCardType == "01" || trade.BankCardType == "11")
                                    {
                                        BankCardType = 0;
                                    }
                                    else
                                    {
                                        BankCardType = 1;
                                    }
                                }
                                else if (pos.BrandId == 7)
                                {
                                    TradeAmount = TradeAmount / 100;
                                    if (trade.BankCardType == "OA" || trade.BankCardType == "CC" || trade.BankCardType == "SCC")
                                    {
                                        BankCardType = 1;
                                    }
                                    else
                                    {
                                        BankCardType = 0;
                                    }
                                }
                                int BrandId = int.Parse(trade.ProductType);
                                if (BrandId == 1 && trade.MerNo.StartsWith("M900"))
                                {
                                    BrandId = 3;
                                }
                                if (BrandId == 4 && trade.DeviceType == "200")
                                {
                                    BrandId = 5;
                                }
                                decimal SourceTradeAmount = TradeAmount;
                                if (pos.Sort == 0 && pos.BrandId == 7)
                                {
                                    decimal deposit = decimal.Parse(function.CheckNum(pos.SeoKeyword));
                                    if (deposit > 0)
                                    {
                                        TradeAmount -= deposit;
                                        pos.Sort = 1;
                                    }
                                }
                                if (TradeAmount > 0)
                                {
                                    ulong MerHelpFlag = 0;
                                    decimal DepositAmt = decimal.Parse(function.CheckNum(pos.SeoKeyword));
                                    if (DepositAmt > 0)
                                    {
                                        int Days = int.Parse(RedisDbconn.Instance.Get<string>("pobjrule:" + pos.BrandId + ":HelpPolicy:Days")); //天数
                                        if (pos.BindingTime != null)
                                        {
                                            if (pos.BindingTime.Value.AddDays(Days) > DateTime.Now)
                                            {
                                                MerHelpFlag = 1;
                                            }
                                        }
                                    }
                                    int CapFlag = 0;
                                    if(BankCardType == 0 && TradeAmount >= 1666.67M)
                                    {
                                        CapFlag = 1;
                                    }
                                    db.TradeRecord.Add(new TradeRecord()
                                    {
                                        ParentNav = user.ParentNav,
                                        CreateDate = trade.CreateDate,
                                        UpdateDate = trade.UpdateDate,
                                        RecordNo = trade.TradeSerialNo, //单号
                                        UserId = pos.UserId, //创客
                                        MerchantId = pos.BindMerchantId, //商户
                                        MerNo = trade.MerNo, //渠道商户编号
                                        MerHelpFlag = MerHelpFlag, //是否属于扶持周期内商户
                                        HelpMonthCount = 0, //扶持第几个月
                                        MerBuddyType = user.MerchantType, //商户创客类型
                                        SnNo = trade.TradeSnNo, //渠道SN号
                                        TradeSerialNo = trade.ChannelSerial, //交易流水号
                                        TradeAmount = TradeAmount, //交易金额
                                        BankCardType = BankCardType, //银行卡类型
                                        QrPayFlag = QrPayFlag, //云闪付标识
                                        CapFlag = CapFlag, //借记卡是否封顶
                                        VipFlag = VipFlag, //会员标记
                                        PayType = PayType, //支付方式
                                        BrandId = BrandId, //品牌
                                        Remark = trade.Remark, //备注
                                        TopUserId = TopUserId, //顶级创客
                                        MerUserId = pos.UserId, //商户直属创客
                                    });
                                }
                                decimal CheckMoney = 1000;
                                int CheckDays = 30;
                                if (pos.BrandId == 6)
                                {
                                    CheckMoney = 5000;
                                }
                                if (BankCardType == 1 || (BankCardType == 2 && pos.BrandId == 1) || (BankCardType == 2 && pos.BrandId == 3))
                                {
                                    pos.CreditTrade += SourceTradeAmount;
                                }
                                else if (BankCardType == 0)
                                {
                                    pos.DebitCardTrade += TradeAmount;
                                }
                                // if (pos.CreditTrade < CheckMoney)
                                // {
                                //     decimal deposit = decimal.Parse(function.CheckNum(pos.SeoKeyword));
                                //     if (deposit > 0 && pos.IsPurchase != 1)
                                //     {
                                //         pos.IsPurchase = 0;
                                //     }
                                // }
                                if (pos.CreditTrade >= CheckMoney && pos.ActivationState == 0 && pos.TransferTime < pos.BindingTime && pos.BindingTime > DateTime.Now.AddDays(-CheckDays))
                                {
                                    // decimal deposit = decimal.Parse(function.CheckNum(pos.SeoKeyword));
                                    // if (deposit == 0 && pos.IsPurchase != 1)
                                    // {
                                    //     pos.IsPurchase = 0;
                                    // }
                                    pos.ActivationState = 1;
                                    pos.ActivationTime = DateTime.Now;
                                    PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId);
                                    if (merchant != null)
                                    {
                                        merchant.ActiveStatus = 1;
                                        merchant.MerStandardDate = DateTime.Now;
                                        db.SaveChanges();
                                        RedisDbconn.Instance.Set("PosMerchantInfo:" + merchant.Id, merchant);
                                    }
                                    //发放大盟主奖励
                                    if(pos.LeaderUserId > 0)
                                    {
                                        RedisDbconn.Instance.AddList("LeaderPrizeQueue", pos.Id);
                                    }
                                }
                                db.SaveChanges();
                            }
                            SpModels.TradeRecord edit = spdb.TradeRecord.FirstOrDefault(m => m.Id == trade.Id);
                            if (edit != null)
                            {
                                edit.Status = 2;
                            }
                            spdb.SaveChanges();
                        }
                    }
                }
            }
            spdb.Dispose();
            db.Dispose();
        }
    }
}