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

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

        private void threadStart()
        {
            while (true)
            {
                try
                {
                    DoSomeThing();
                }
                catch (Exception ex)
                {
                    LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "重推机具数据异常");
                }
                Thread.Sleep(5000);
            }
        }

        //要执行的方法
        public void DoSomeThing()
        {
            string url = "";
            WebCMSEntities db = new WebCMSEntities();
            DateTime check = DateTime.Now.AddMinutes(-3);
            List<PushPosRecord> list = db.PushPosRecord.Where(m => m.CreateDate >= check && m.Status < 1).OrderBy(m => m.Id).Take(200).ToList();
            foreach(PushPosRecord sub in list)
            {
                string dataType = sub.DataType;
                if(dataType == "bind") url = "http://gateway.kexiaoshuang.com/v1/kxs/statServer/sp/binding";
                if(dataType == "un_bind") url = "http://gateway.kexiaoshuang.com/v1/kxs/statServer/sp/unbind";
                if(dataType == "trade") url = "http://gateway.kexiaoshuang.com/v1/kxs/statServer/sp/trade";
                if(dataType == "deposit") url = "http://gateway.kexiaoshuang.com/v1/kxs/statServer/sp/cash";
                if(dataType == "active") url = "http://gateway.kexiaoshuang.com/v1/kxs/statServer/sp/extActData";
                string res = PostWebRequest(url, sub.EncryptContent, new Dictionary<string, string>());
                if(res.Contains("\"status\""))
                {
                    JsonData backObj = JsonMapper.ToObject(res);
                    if(backObj["status"].ToString() == "1")
                    {
                        PushPosRecord edit = db.PushPosRecord.FirstOrDefault(m => m.Id == sub.Id);
                        if(edit != null)
                        {
                            edit.Status = 1;
                            edit.BackContent = res;
                        }
                    }
                    else
                    {
                        PushPosRecord edit = db.PushPosRecord.FirstOrDefault(m => m.Id == sub.Id);
                        if(edit != null)
                        {
                            edit.Status = 2;
                            edit.BackContent = res;
                        }
                    }
                }
                else
                {
                    PushPosRecord edit = db.PushPosRecord.FirstOrDefault(m => m.Id == sub.Id);
                    if(edit != null)
                    {
                        edit.Status = 3;
                        edit.BackContent = res;
                    }
                }
            }
            db.SaveChanges();
            db.Dispose();
        }

        public void SaveToDb(string content, string encryptContent, string dataType)
        {
            WebCMSEntities db = new WebCMSEntities();
            db.PushPosRecord.Add(new PushPosRecord()
            {
                CreateDate = DateTime.Now,
                Content = content,
                DataType = dataType,
                EncryptContent = encryptContent,
            });
            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";
                function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "POST请求异常");
            }
            return ret;
        }
        
    }
}