using System;
using System.Collections.Generic;
using System.Linq;
using MySystem.Models.Main;
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>("ProfitShareHdQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    StartDo(content);
                }
                else
                {
                    Thread.Sleep(2000);
                }
            }
        }

        public void StartDo(string content)
        {
            try
            {
                JsonData jsonObj = JsonMapper.ToObject(content);
                string ApplyNo = jsonObj["ApplyNo"].ToString(); //微信订单号
                string MchtNo = jsonObj["MchtNo"].ToString(); //商户订单号
                string OrderNo = jsonObj["OrderNo"].ToString(); //商户订单号
                JsonData result = JsonMapper.ToObject(HaoDaHelper.Instance.OrderDivideAccountsQuery(ApplyNo, MchtNo));
                string state = result["data"]["status"].ToString();
                if (result["data"]["status"].ToString() == "0")
                {
                    WebCMSEntities db = new WebCMSEntities();
                    ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.OrderNo == OrderNo && m.Status == 2);
                    if (order != null)
                    {
                        RedisDbconn.Instance.AddList("ConsumerOrdersHd:Divi:" + order.PayMode + ":List", order.Id.ToString());
                    }
                    db.Dispose();
                }
                else
                {
                    RedisDbconn.Instance.AddList("ProfitShareHdQueue", content);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "分账队列异常");
            }
        }
    }
}