using System;
using System.Collections.Generic;
using System.Linq;
using MySystem.PxcModels;
using Library;
using LitJson;

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

        public void Start(JobMqMsg jobInfo)
        {
            string content = "";
            try
            {
                string OrderString = jobInfo.OrderString;
                if (OrderString.StartsWith("Sp:") && OrderString.EndsWith(":Sycn"))
                {
                    string TableName = OrderString.Split(':')[1];
                    string Msg = "";
                    bool op = true;
                    while (op)
                    {
                        string data = RedisDbconn.Instance.RPop<string>(TableName);
                        if(!string.IsNullOrEmpty(data))
                        {
                            Dictionary<string, string> dic = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
                            if (TableName.StartsWith("kq_"))
                            {
                                ProfitHelper.Instance.StartListenMerchantDo(dic, true);
                            }
                            else
                            { 
                                ProfitHelper.Instance.StartListenMerchantDo(dic);
                            }
                        }
                        else
                        {
                            op = false;
                        }
                    }
                    jobInfo.Status = Msg == "success" ? 1 : 0;
                    jobInfo.Msg = Msg == "success" ? "执行完成" : Msg;
                    RabbitMQClient.Instance.SendMsg(Newtonsoft.Json.JsonConvert.SerializeObject(jobInfo), "SycnTableDataBack");
                }
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrEmpty(content))
                {
                    Dictionary<string, string> data = new Dictionary<string, string>();
                    data.Add("ErrTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    data.Add("ErrMsg", ex.ToString());
                    function.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(data), "public_err");
                }
                else
                {
                    function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "public_service");
                }
            }
        }
    }
}