using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using MySystem.Models.Main;
using Library;
using System.Threading;
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;
using LitJson;

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

        #region 检查订单是否在队列里
        public void Start()
        {
            Thread th = new Thread(StartDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StartDo()
        {
            while (true)
            {
                string orderidstring = RedisDbconn.Instance.RPop<string>("ConsumerProfitCheck");
                if (!string.IsNullOrEmpty(orderidstring))
                {
                    DoSomeThing(orderidstring);
                    Thread.Sleep(2000);
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
        }

        public void DoSomeThing(string orderidstring)
        { 
            try
            {
                int orderId = int.Parse(function.CheckInt(orderidstring));
                WebCMSEntities db = new WebCMSEntities();
                ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == orderId);
                if(order != null)
                {
                    var list = RedisDbconn.Instance.GetList<ConsumerOrders>("ConsumerOrdersHd:Divi:" + order.PayMode + ":" + order.MerchantId);
                    if(!list.Any(m => m.Id == orderId) && !db.ConsumerProfit.Any(m => m.OrderId == orderId))
                    {
                        RedisDbconn.Instance.AddList("ConsumerOrdersHd:Divi:" + order.PayMode + ":List", order.Id.ToString());
                    }
                }
                db.Dispose();
            }
            catch(Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "检查订单是否在队列里异常");
            }
        }
        #endregion
    }
}