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 ProfitShareService
    {
        public readonly static ProfitShareService Instance = new ProfitShareService();
        private ProfitShareService()
        { }

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

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

        public void StartDo(string content)
        {
            try
            {
                JsonData jsonObj = JsonMapper.ToObject(content);
                string SubMchid = jsonObj["SubMchid"].ToString(); //子商户号
                string TradeNo = jsonObj["TradeNo"].ToString(); //微信订单号
                string OrderNo = jsonObj["OrderNo"].ToString(); //商户订单号
                string result = WeChatFunction.Instance.QueryProfitShare(SubMchid, TradeNo, OrderNo);
                JsonData resultObj = JsonMapper.ToObject(result);
                if(result.Contains("\"state\":"))
                {
                    string state = resultObj["state"].ToString();
                    if(state == "FINISHED")
                    {
                        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("ProfitShareQueue", content);
                    }
                }
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "分账队列异常");
            }
        }
    }
}