using System;
using System.Linq;
using System.Data;
using System.Threading;
using Library;
using LitJson;
using MySystem.Models.Push;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;

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

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

        private void threadStart()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("KxsPosDataQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        DoSomeThing(content);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + content + "\n" + ex, "推送机具数据异常");
                    }
                }
                else
                {
                    Thread.Sleep(5000);
                }
            }
        }

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

        private void threadStartSaveToDb()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("KxsPosDataSaveToDbQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        DoSomeThing2(content);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + content + "\n" + ex, "保存推送结果");
                    }
                }
                else
                {
                    Thread.Sleep(5000);
                }
            }
        }

        //要执行的方法
        public void DoSomeThing(string content)
        {
            string url = "";
            Utils.WriteLog(DateTime.Now.ToString() + "\n" + content, "统一推送日志");
            content = content.Replace("null", "\"\"");
            JsonData jsonObj = JsonMapper.ToObject(content);
            string dataType = jsonObj["data_type"].ToString();
            string dataContent = jsonObj["data_content"].ToJson();
            if(dataType == "bind") url = AppConfig.Base.JavaPushHost + "v1/kxs/statServer/sp/binding";
            if(dataType == "un_bind") url = AppConfig.Base.JavaPushHost + "v1/kxs/statServer/sp/unbind";
            if(dataType == "trade") url = AppConfig.Base.JavaPushHost + "v1/kxs/statServer/sp/trade";
            if(dataType == "deposit") url = AppConfig.Base.JavaPushHost + "v1/kxs/statServer/sp/cash";
            if(dataType == "active") url = AppConfig.Base.JavaPushHost + "v1/kxs/statServer/sp/extActData";
            if(dataType == "qr_bind") url = AppConfig.Base.JavaPushHost + "v1/kxs/statServer/sp/saveHaoDaQrCodeMchInfo";
            if(dataType == "lkb_trade") url = AppConfig.Base.JavaPushHost + "v1/kxs/statServer/sp/lkbTrade";
            Utils.WriteLog("url:" + url, "统一推送日志");
            string encryptContent = AesEncrypt(dataContent);
            encryptContent = Convert.ToBase64String(Encoding.UTF8.GetBytes(encryptContent));
            Utils.WriteLog("encryptContent:" + encryptContent, "统一推送日志");
            string res = PostWebRequest(url, encryptContent, new Dictionary<string, string>());
            Utils.WriteLog("res:" + res + "\n\n\n", "统一推送日志");
            RedisDbconn.Instance.AddList("KxsPosDataSaveToDbQueue", dataContent + "#cut#" + encryptContent + "#cut#" + dataType + "#cut#" + res);
        }

        public void DoSomeThing2(string content)
        {
            string[] data = content.Split(new string[]{ "#cut#" }, StringSplitOptions.None);
            string dataContent = data[0];
            string encryptContent = data[1];
            string dataType = data[2];
            string res = data[3];
            if(!res.Contains("\"status\""))
            {
                SaveToDb(dataContent, encryptContent, dataType, res);
                return;
            }
            JsonData backObj = JsonMapper.ToObject(res);
            if(backObj["status"].ToString() != "1")
            {
                SaveToDb(dataContent, encryptContent, dataType, res);
                return;
            }
            SaveToDb(dataContent, encryptContent, dataType, res, 1);
        }

        public void SaveToDb(string content, string encryptContent, string dataType, string backContent, int status = 0)
        {
            WebCMSEntities db = new WebCMSEntities();
            db.PushPosRecord.Add(new PushPosRecord()
            {
                CreateDate = DateTime.Now,
                Content = content,
                DataType = dataType,
                EncryptContent = encryptContent,
                BackContent = backContent,
                Status = status,
            });
            db.SaveChanges();
            db.Dispose();
        }

        public string AesEncrypt(string str)
        {
            if (string.IsNullOrEmpty(str)) return null;
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
            string key = "CBTU1dD4Kd5pyiGWTsI10jRQ3SvKusSV";
            string iv = "DYgjCEIMVrj2W9xN";

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                IV = Encoding.UTF8.GetBytes(iv),
                Mode = System.Security.Cryptography.CipherMode.CBC,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };
            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        public string PostWebRequest(string postUrl, string paramData, Dictionary<string, string> headers)
        {
            string ret = string.Empty;
            try
            {
                byte[] postData = System.Text.Encoding.UTF8.GetBytes(paramData);
                // 设置提交的相关参数 
                HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
                System.Text.Encoding myEncoding = System.Text.Encoding.UTF8;
                request.Method = "POST";
                request.KeepAlive = false;
                request.AllowAutoRedirect = true;
                request.ContentType = "application/json";
                foreach (string key in headers.Keys)
                {
                    request.Headers.Add(key, headers[key]);
                }
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR  3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";

                request.ContentLength = postData.Length;

                // 提交请求数据 
                Stream outputStream = request.GetRequestStream();
                outputStream.Write(postData, 0, postData.Length);
                outputStream.Close();
                HttpWebResponse response;
                Stream responseStream;
                StreamReader reader;
                string srcString;
                response = request.GetResponse() as HttpWebResponse;
                responseStream = response.GetResponseStream();
                reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
                srcString = reader.ReadToEnd();
                ret = srcString;   //返回值赋值
                reader.Close();
            }
            catch (WebException ex)
            {
                HttpWebResponse response = (HttpWebResponse)ex.Response;
                Stream myResponseStream = response.GetResponseStream();
                //获取响应内容
                StreamReader myStreamReader = new StreamReader(myResponseStream);
                ret = myStreamReader.ReadToEnd();
                myResponseStream.Close();
            }
            catch (Exception ex)
            {
                ret = "fail";
                Utils.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "POST请求异常");
            }
            return ret;
        }
        
    }
}