using System;
using System.Collections.Generic;
using System.Linq;
using MySystem.Models;
using Library;
using LitJson;
using System.Text.RegularExpressions;
using System.Threading;

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

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

        public void StartListen()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("AlipayShareQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    StartDo(content);
                }
                else
                {
                    Thread.Sleep(2000);
                }
            }
        }

        public void StartDo(string content)
        {
            try
            {
                JsonData jsonObj = JsonMapper.ToObject(content);
                string TradeNo = jsonObj["TradeNo"].ToString(); //支付宝订单号
                string OrderNo = jsonObj["OrderNo"].ToString(); //商户订单号
                string AuthToken = jsonObj["AuthToken"].ToString();
                string result = AlipayFunction.Instance.QuerySettle(OrderNo, TradeNo, AuthToken);
                JsonData resultObj = JsonMapper.ToObject(result);
                if(result.Contains("\"alipay_trade_order_settle_query_response\""))
                {
                    string code = resultObj["alipay_trade_order_settle_query_response"]["code"].ToString();
                    if(code == "10000")
                    {
                        WebCMSEntities db = new WebCMSEntities();
                        ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.OrderNo == OrderNo && m.Status == 2);
                        if (order != null)
                        {
                            RedisDbconn.Instance.AddList("ConsumerOrders:Divi:" + order.PayMode + ":List", order.Id.ToString());
                            // RedisDbconn.Instance.AddRightList("ConsumerOrders:Divi:" + order.PayMode + ":" + order.MerchantId, order);
                        }
                        db.Dispose();
                    }
                    else
                    {
                        RedisDbconn.Instance.AddList("AlipayShareQueue", content);
                    }
                }
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "支付宝查询分账异常");
            }
        }
    }
}