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

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

        string reqUrl = "https://lcx.93a.cn:18080/mikl/wechat/payResult";

        public void Start()//启动
        {
            Thread thread = new Thread(listen);
            thread.IsBackground = true;
            thread.Start();
        }

        public void listen()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("OrderPushQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        doSomething(content);
                        Thread.Sleep(10);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "商户订单信息推送异常");
                    }
                }
                else
                {
                    Thread.Sleep(1000);
                }
            }
        }

        public void doSomething(string content)
        {
            JsonData jsonObj = JsonMapper.ToObject(content);
            SortedList<string, string> data = new SortedList<string, string>();
            data.Add("order_no", jsonObj["order_no"].ToString()); //订单号
            data.Add("order_status", jsonObj["order_status"].ToString()); //订单状态
            data.Add("order_time", jsonObj["order_time"].ToString()); //变动时间
            post(data);
        }

        private string post(SortedList<string, string> data)
        {
            string req = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            function.WriteLog("请求地址：" + reqUrl, "商户订单信息推送日志");
            function.WriteLog("请求参数：" + req, "商户订单信息推送日志");
            string result = function.PostWebRequest(reqUrl, req, "application/json");
            function.WriteLog("响应数据：" + result, "商户订单信息推送日志");
            return result;
        }
    }
}