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

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


        public void Start()
        {
            Thread th = new Thread(dosomething);
            th.IsBackground = true;
            th.Start();
        }
        
        private void dosomething()
        { 
            bool op = true;
            while (op)
            {
                string content = RedisDbconn.Instance.RPop<string>("AlipayCallBack2");
                if (!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        sloveAlipayCallBack(content);
                    }
                    catch(Exception ex)
                    {
                        function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "直联支付宝支付回调异常");
                    }
                }
                else
                {
                    Thread.Sleep(2000);
                }
            }
        }

        public void sloveAlipayCallBack(string content)
        { 
            JsonData jsonObj = JsonMapper.ToObject(content);
            string OrderNo = jsonObj["out_trade_no"].ToString();
            string TradeNo = jsonObj["transaction_id"].ToString();
            decimal TotalFee = decimal.Parse(function.CheckNum(jsonObj["total_fee"].ToString()));
            WebCMSEntities db = new WebCMSEntities();
            MerchantDepositOrder order = db.MerchantDepositOrder.FirstOrDefault(m => m.OrderNo == OrderNo && m.Status == 0);
            if(order != null)
            {
                order.Status = 1;
                order.UpdateDate = DateTime.Now;
                MerchantInfo mer = db.MerchantInfo.FirstOrDefault(m => m.Id == order.MerchantId);
                if(mer != null)
                {
                    mer.IsAct = 1;
                }
                db.SaveChanges();
            }
            db.Dispose();
        }

    }
}