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

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

        public void Start()
        {
            Thread th = new Thread(dosomething);
            th.IsBackground = true;
            th.Start();
        }
        
        private void dosomething()
        {
            while (true)
            {
                try
                {
                    string content = RedisDbconn.Instance.RPop<string>("ReservePayQueue");
                    if (!string.IsNullOrEmpty(content))
                    {
                        sloveAlipayCallBack(content);
                    }
                    else
                    {
                        Thread.Sleep(2000);
                    }
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "商城订单余额支付异常");
                    Thread.Sleep(2000);
                }
            }
        }

        public void sloveAlipayCallBack(string content)
        {
            int OrderId = int.Parse(function.CheckInt(content));
            WebCMSEntities db = new WebCMSEntities();
            Orders order = db.Orders.FirstOrDefault(m => m.Id == OrderId && m.PayMode == 4 && m.PayStatus == 0);
            if (order != null)
            {
                decimal TotalPrice = order.TotalPrice;
                UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == order.UserId);
                if (account != null)
                {
                    if(account.LeaderReserve >= TotalPrice)
                    {
                        AlipayPayBack2Service.Instance.DoOrderV2(db, OrderId);
                    }
                }
            }
            db.Dispose();
        }
    }
}