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

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

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

        public void dosomething()
        {
            while (true)
            {
                try
                {
                    if(DateTime.Now.Hour > 3 && DateTime.Now.Hour < 20 && DateTime.Now >= DateTime.Parse("2023-09-20 11:00:00"))
                    {
                        string chk = function.ReadInstance("/PrePosWithhold/" + DateTime.Now.ToString("yyyyMMdd") + ".txt");
                        if(string.IsNullOrEmpty(chk))
                        {
                            function.WritePage("/PrePosWithhold/", "" + DateTime.Now.ToString("yyyyMMdd") + ".txt", DateTime.Now.ToString());
                            PrePosWithhold();
                        }
                    }
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "预发机提醒异常");
                }
                Thread.Sleep(300000);
            }
        }

        //预发机30天未完成申请时向预发创客增加一条预扣款
        private void PrePosWithhold()
        {
            WebCMSEntities db = new WebCMSEntities();
            DateTime end = DateTime.Parse(DateTime.Now.AddDays(-29).ToString("yyyy-MM-dd") + " 00:00:00");
            int Id = 0;
            bool op = true;
            while(op)
            {
                var PrePosList = db.PreSendStockDetail.Where(m => m.Id > Id && m.ApplyFlag == 0 && m.CreateDate < end && m.Status >= 0 && m.Status <= 1 && m.WithholdFlag == 0).OrderBy(m => m.Id).Take(20).ToList();
                if(PrePosList.Count > 0)
                {
                    foreach(var Pos in PrePosList)
                    {
                        PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == Pos.SnId && m.BuyUserId == 0 && m.PreUserId > 0);
                        if(pos != null)
                        {
                            KqProducts brand = db.KqProducts.FirstOrDefault(m => m.Id == Pos.BrandId) ?? new KqProducts();
                            decimal ChargeAmount = brand.Kind == 2 ? 300 : 200;
                            db.ToChargeBackRecord.Add(new ToChargeBackRecord
                            {
                                CreateDate = DateTime.Now,
                                SeoTitle = "系统",
                                SeoDescription = "预发机超时未申请扣款",
                                Remark = "预发机超时未申请扣款",
                                ChargeType = 1,
                                ChargeAmount = ChargeAmount,
                                UserId = Pos.ToUserId,
                                Field1 = Pos.SnNo,
                            });
                            pos.WithholdFlag = 1;
                            PreSendStockDetail pre = db.PreSendStockDetail.FirstOrDefault(m => m.Id == Pos.Id);
                            if(pre != null)
                            {
                                pre.WithholdFlag = 1;
                            }
                            //增加账户预扣总额
                            Utils.Instance.ToChargeAmount(Pos.ToUserId, ChargeAmount);
                        }
                        Id = Pos.Id;
                    }
                    db.SaveChanges();
                }
                else
                {
                    op = false;
                }
            }
            db.Dispose();
        }






        // 含有【预】字标签的机具完成申请时
        // ·若预扣款已扣，则返还创客余额
        // ·若预扣款未扣，则删除该条预扣款
        public void StartPre()
        {
            Thread th = new Thread(StartPreDo);
            th.IsBackground = true;
            th.Start();
        }

        public void StartPreDo()
        {
            while (true)
            {
                try
                {
                    string content = RedisDbconn.Instance.RPop<string>("PreWithholdQueue");
                    if(!string.IsNullOrEmpty(content))
                    {
                        function.WriteLog("content:" + content, "预发扣款机具申请");
                        JsonData jsonObj = JsonMapper.ToObject(content);
                        int UserId = int.Parse(function.CheckInt(jsonObj["UserId"].ToString()));
                        string SnNo = jsonObj["SnNo"].ToString();
                        WebCMSEntities db = new WebCMSEntities();
                        decimal ChargeAmount = 0;
                        bool doBack = true; //是否减少账户预扣总额
                        ToChargeBackRecord back = db.ToChargeBackRecord.FirstOrDefault(m => m.UserId == UserId && m.Field1 == SnNo && m.Remark == "预发机超时未申请扣款");
                        if(back != null)
                        {
                            function.WriteLog("预扣款数据:" + Newtonsoft.Json.JsonConvert.SerializeObject(back), "预发扣款机具申请");
                            ChargeAmount = back.ChargeAmount;
                            function.WriteLog("预扣款是否已扣:" + back.Status, "预发扣款机具申请");
                            if(back.Status == 1)
                            {
                                Utils.Instance.OpAccount(back.UserId, ChargeAmount, 134, false);
                                doBack = false;
                            }
                            db.ToChargeBackRecord.Remove(back);
                            db.SaveChanges();
                        }
                        db.Dispose();

                        //减少账户预扣总额
                        function.WriteLog("是否减少账户预扣总额:" + doBack, "预发扣款机具申请");
                        if(doBack)
                        {
                            Utils.Instance.ToChargeAmount(UserId, -ChargeAmount);
                            function.WriteLog("减少账户预扣总额:" + ChargeAmount, "预发扣款机具申请");
                        }

                        Thread.Sleep(500);
                    }
                    else
                    {
                        Thread.Sleep(30000);
                    }
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "预发扣款机具申请异常");
                    Thread.Sleep(300000);
                }
            }
        }
    }
}