using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using MySystem.Models;
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 < 3)
                {
                    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(600000);
            }
        }

        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)
        {
            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)
            {
                var userAccount = db.UserAccount.FirstOrDefault(m => m.Id == items.UserId) ?? new UserAccount();
                var record = info.FirstOrDefault(m => m.Id == items.Id);
                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 = 124,//过期机具货款扣费
                        Remark = "扣机具货款",

                    }).Entity;
                    record.Status = 1;
                    if (userAccount.ToChargeAmount >= record.ChargeAmount)
                    {
                        userAccount.ToChargeAmount -= record.ChargeAmount;//扣减预扣款
                    }
                    userAccount.BalanceAmount -= record.ChargeAmount;//扣减余额
                }
            }
            db.SaveChanges();
        }
    }
}