using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using System.IO;
using MySystem.MainModels;
using Library;
using LitJson;

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

        private void threadStart()
        {
            string data = "";
            try
            { 
                data = RedisDbconn.Instance.RPop<string>("PayCallBack");
                if (!string.IsNullOrEmpty(data))
                {
                    ScanQueue(data);
                }
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.ToString(), "支付回调队列异常");
            }
        }

        //要执行的方法
        private void ScanQueue(string data)
        {
            JsonData dateinfo = JsonMapper.ToObject(data);
            string OrderNo = dateinfo["out_trade_no"].ToString();
            string TradeNo = dateinfo["transaction_id"].ToString();
            decimal TotalFee = decimal.Parse(function.CheckNum(dateinfo["total_fee"].ToString()));
            int PayMode = int.Parse(function.CheckInt(dateinfo["pay_mode"].ToString()));
            OrderForNo orderForNo = OrderForNoDbconn.Instance.Get(OrderNo) ?? new OrderForNo();
            string OrderIds = orderForNo.OrderIds;
            if (!string.IsNullOrEmpty(OrderIds))
            {
                string[] orderIdList = OrderIds.Split(',');
                foreach (string orderIdStr in orderIdList)
                {
                    int orderid = int.Parse(orderIdStr);
                    Orders order = OrdersDbconn.Instance.Get(orderid);
                    if (order != null)
                    {
                        if (order.Status == 0)
                        {
                            order.Status = 1;
                            order.PayMode = PayMode;
                            order.TradeNo = TradeNo;
                            order.PayDate = DateTime.Now;

                            List<int> proids = OrderProductDbconn.Instance.GetList(orderid);
                            foreach (int proid in proids)
                            {
                                OrderProduct orderPro = OrderProductDbconn.Instance.Get(proid) ?? new OrderProduct();
                                Products product = ProductsDbconn.Instance.Get(orderPro.ProductId);
                                if (product != null)
                                {
                                    product.MonthSale += orderPro.ProductCount;
                                    RedisDbconn.Instance.Set("Products:" + product.Id, product);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}