using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using MySystem.PxcModels;
using Library;

namespace MySystem
{
    /// <summary>
    /// 过期机具执行扣费
    /// </summary>
    public class TimeOutPosChargeService
    {
        public readonly static TimeOutPosChargeService Instance = new TimeOutPosChargeService();
        private TimeOutPosChargeService()
        { }

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

        public void doSomething()
        {
            while (true)
            {
                if (DateTime.Now.Hour < 9)
                {
                    try
                    {
                        string check = function.ReadInstance("/TimeOutPosCharge/check" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
                        if (string.IsNullOrEmpty(check))
                        {
                            function.WritePage("/TimeOutPosCharge/", "check" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt", DateTime.Now.ToString("HH:mm:ss"));
                            WebCMSEntities db = new WebCMSEntities();
                            var date = DateTime.Now.AddDays(-60).ToString("yyyy-MM-dd 00:00:00");//过期限制时间
                            var time = DateTime.Parse(date);//过期限制时间

                            DataTable dt = CustomerSqlConn.dtable("SELECT BuyUserId FROM PosMachinesTwo WHERE `Status`>-1 AND BuyUserId>0 AND BindingState=0 AND ActivationState=0 AND ScanQrTrade=0 AND RecycEndDate <'" + date + "' GROUP BY BuyUserId", MysqlConn.SqlConnStr);//扣费创客
                            var query = db.PosMachinesTwo.Where(m => m.Status > -1 && m.BuyUserId > 0 && m.BindingState == 0 && m.ActivationState == 0 && m.ScanQrTrade == 0 && m.RecycEndDate < time).ToList();//循环过期超过15天机具
                            var brandInfo = db.KqProducts.ToList();
                            foreach (DataRow item in dt.Rows)
                            {
                                int BuyUserId = int.Parse(item["BuyUserId"].ToString());
                                var userAccount = db.UserAccount.FirstOrDefault(m => m.Id == BuyUserId);
                                if (userAccount == null)
                                {
                                    userAccount = db.UserAccount.Add(new UserAccount()
                                    {
                                        Id = BuyUserId,
                                        UserId = BuyUserId,
                                    }).Entity;
                                    db.SaveChanges();
                                }
                                var posInfo = query.Where(m => m.BuyUserId == BuyUserId);
                                var amount = 0;
                                foreach (var pos in posInfo)
                                {
                                    var poss = db.PosMachinesTwo.FirstOrDefault(m => m.Id == pos.Id) ?? new PosMachinesTwo();
                                    poss.ScanQrTrade = 999;
                                    var Brand = brandInfo.FirstOrDefault(m => m.Id == pos.BrandId);
                                    if (Brand.Name.Contains("电签"))
                                    {
                                        amount = 200;
                                    }
                                    if (Brand.Name.Contains("大POS"))
                                    {
                                        amount = 300;
                                    }
                                    userAccount.ToChargeAmount += amount;//增加预扣款
                                    var toChargeBackRecord = db.ToChargeBackRecord.Add(new ToChargeBackRecord
                                    {
                                        CreateDate = DateTime.Now,
                                        UserId = BuyUserId,
                                        ChargeAmount = amount,
                                        ChargeType = 124,//过期机具货款扣费
                                        Remark = pos.PosSn,

                                    }).Entity;
                                }
                            }
                            db.SaveChanges();

                            DoChargeAmount(db);
                        }
                    }
                    catch (Exception ex)
                    {
                        function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "过期机具执行扣费异常");
                    }
                }
                Thread.Sleep(1000);
            }
        }



        public void StartDoChargeAmount()
        {
            Thread th = new Thread(StartDoChargeAmountReady);
            th.IsBackground = true;
            th.Start();
        }

        public void StartDoChargeAmountReady()
        {
            while (true)
            {
                WebCMSEntities db = new WebCMSEntities();
                DoChargeAmount(db);
                db.Dispose();
                Thread.Sleep(60000);
            }
        }

        public void ListenChargeAmount()
        {
            Thread th = new Thread(ListenChargeAmountReady);
            th.IsBackground = true;
            th.Start();
        }

        public void ListenChargeAmountReady()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("DoChargeAmountQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    WebCMSEntities db = new WebCMSEntities();
                    DoChargeAmount(db, int.Parse(function.CheckInt(content)));
                    db.Dispose();
                }
            }
        }

        public void DoChargeAmount(WebCMSEntities db, int UserId = 0)
        {
            MySystem.OpModels.WebCMSEntities opdb = new MySystem.OpModels.WebCMSEntities();
            IQueryable<ToChargeBackRecord> list = db.ToChargeBackRecord.Where(m => m.Status == 0);//过期机具扣费记录
            if (UserId > 0)
            {
                list = list.Where(m => m.UserId == UserId);
            }
            var info = list.ToList();
            foreach (var items in info)
            {
                function.WriteLog(DateTime.Now.ToString(), "扣款监听日志");
                function.WriteLog(items.UserId.ToString(), "扣款监听日志");
                var userAccount = db.UserAccount.FirstOrDefault(m => m.Id == items.UserId) ?? new UserAccount();
                var record = info.FirstOrDefault(m => m.Id == items.Id);
                var check = false; //扣款成功标记

                function.WriteLog("BalanceAmount:" + userAccount.BalanceAmount + ";ChargeAmount:" + record.ChargeAmount + ";", "扣款监听日志");
                function.WriteLog("in", "扣款监听日志");
                var ChangeType = 0;
                var Remark = "";
                if (record.ChargeType == 124)//过期机具货款扣费
                {
                    ChangeType = 124;
                    Remark = "扣机具货款";
                }
                if (record.ChargeType == 1)//普通预扣款
                {
                    ChangeType = 202;
                    // Remark = "普通扣款";
                    Remark = items.Remark;
                }
                if (record.ChargeType == 2)//分期预扣款
                {
                    ChangeType = 201;
                    // Remark = "分期扣款";
                    Remark = items.Remark;
                }
                if (record.Kind < 2) //主库
                {
                    if (record.Kind == 0) //创客预扣款
                    {
                        if (userAccount.BalanceAmount >= record.ChargeAmount)
                        {
                            var userAccountRecord = db.UserAccountRecord.Add(new UserAccountRecord
                            {
                                CreateDate = DateTime.Now,
                                UserId = items.UserId,
                                BeforeBalanceAmount = userAccount.BalanceAmount,
                                AfterBalanceAmount = userAccount.BalanceAmount - record.ChargeAmount,
                                ChangeAmount = record.ChargeAmount,
                                ChangeType = ChangeType,
                                Remark = Remark,
                            }).Entity;

                            function.WriteLog("ToChargeAmount:" + userAccount.ToChargeAmount + ";ChargeAmount:" + record.ChargeAmount + ";", "扣款监听日志");
                            if (userAccount.ToChargeAmount >= record.ChargeAmount)
                            {
                                function.WriteLog("ok", "扣款监听日志");
                                userAccount.ToChargeAmount -= record.ChargeAmount;//分期扣款
                            }
                            userAccount.BalanceAmount -= record.ChargeAmount;//扣减余额
                            check = true;
                        }
                    }
                    if (record.Kind == 1) //盟主预扣款
                    {
                        if (userAccount.LeaderBalanceAmount >= record.ChargeAmount)
                        {
                            //11：盟主储蓄金增减单(兑换机具券 机具券兑换 系统增加(盟主储蓄金) 系统扣减(盟主储蓄金) 储备金购买)
                            // 示例：+/-金额
                            //  盟主储蓄金：剩余盟主储蓄金
                            // 12：可提现余额增减单(系统增加(可提现余额) 系统扣减(可提现余额))
                            // 示例：+/-金额
                            //  可提现余额：剩余可提现余额
                            // 13：盟主储蓄金减少可提现余额增加(推荐大/小盟主 商城购机 购机奖励)
                            // 示例：-金额
                            //  盟主储蓄金：剩余盟主储蓄金
                            //  可提现余额：+金额
                            var leaderReserveRecord = db.LeaderReserveRecord.Add(new LeaderReserveRecord()
                            {
                                CreateDate = DateTime.Now, //创建时间
                                Sort = 12,
                                UserId = items.UserId, //创客
                                Remark = "盟主预扣款",
                                SeoDescription = items.SeoDescription,
                                ChangeType = 2,//变动类型(1 增加 2 减少)
                                BeforeAmt = userAccount.LeaderBalanceAmount,
                                AfterAmt = userAccount.LeaderBalanceAmount - record.ChargeAmount,
                                ChangeAmt = record.ChargeAmount,
                                TradeDate = DateTime.Now.ToString("yyyyMMdd"),
                                TradeMonth = DateTime.Now.ToString("yyyyMM"),
                            }).Entity;

                            function.WriteLog("LeaderToChargeAmount:" + userAccount.LeaderToChargeAmount + ";ChargeAmount:" + record.ChargeAmount + ";", "扣款监听日志");
                            if (userAccount.LeaderToChargeAmount >= record.ChargeAmount)
                            {
                                function.WriteLog("ok", "扣款监听日志");
                                userAccount.LeaderToChargeAmount -= record.ChargeAmount;//扣减盟主预扣款
                            }
                            userAccount.LeaderBalanceAmount -= record.ChargeAmount;//扣减盟主可提现余额
                            check = true;
                        }
                    }
                }
                else //运营中心
                {
                    var opUserAccount = opdb.UserAccount.FirstOrDefault(m => m.Id == items.UserId) ?? new MySystem.OpModels.UserAccount();
                    if (record.Kind == 2) //运营中心预扣款
                    {
                        if (opUserAccount.ValidForGetAmount >= record.ChargeAmount)
                        {
                            var amoutRecord = opdb.AmountRecord.Add(new MySystem.OpModels.AmountRecord
                            {
                                CreateDate = DateTime.Now,
                                UserId = items.UserId,
                                SeoDescription = "运营中心预扣款",
                                UseAmount = record.ChargeAmount,
                                OperateType = 2,
                                BeforeAmount = opUserAccount.ValidAmount + opUserAccount.TotalAmt + opUserAccount.ValidForGetAmount,
                                AfterAmount = opUserAccount.ValidAmount + opUserAccount.TotalAmt + opUserAccount.ValidForGetAmount - record.ChargeAmount,
                            }).Entity;

                            function.WriteLog("OperateToChargeAmount:" + userAccount.OperateToChargeAmount + ";ChargeAmount:" + record.ChargeAmount + ";", "扣款监听日志");
                            if (userAccount.OperateToChargeAmount >= record.ChargeAmount)
                            {
                                function.WriteLog("ok", "扣款监听日志");
                                userAccount.OperateToChargeAmount -= record.ChargeAmount;//扣减运营中心预扣款
                            }
                            opUserAccount.ValidForGetAmount -= record.ChargeAmount;//扣减运营中心可提现余额
                            amoutRecord.AfterValidForGetAmount = opUserAccount.ValidForGetAmount;
                            amoutRecord.AfterTotalAmt = opUserAccount.TotalAmt;
                            amoutRecord.AfterValidAmount = opUserAccount.ValidAmount;
                            check = true;
                        }
                    }
                }
                if (check)
                {
                    record.Status = 1;
                    record.UpdateDate = DateTime.Now;
                    if (record.ChargeType == 2)
                    {
                        var toChargeBackRecordSub = db.ToChargeBackRecordSub.FirstOrDefault(m => m.Id == record.Sort) ?? new ToChargeBackRecordSub();
                        var toChargeByStage = db.ToChargeByStage.FirstOrDefault(m => m.Id == toChargeBackRecordSub.ParentId && m.TimeNumber > m.QueryCount) ?? new ToChargeByStage();
                        toChargeBackRecordSub.Status = 1;
                        toChargeByStage.QueryCount += 1;
                        toChargeByStage.ChargeAmount += toChargeBackRecordSub.ChargeAmount;
                        if (toChargeByStage.TimeNumber == toChargeByStage.QueryCount)
                        {
                            toChargeByStage.Status = 1;
                        }
                    }
                }
                function.WriteLog("\n\n", "扣款监听日志");
            }
            db.SaveChanges();
            opdb.SaveChanges();
        }
    }
}