using System;
using System.Collections.Generic;
using System.Threading;
using System.Linq;
using System.Data;
using MySystem;
using MySystem.PxcModels;
using Library;
using LitJson;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Net;

public class PosChannelHelper
{
    public readonly static PosChannelHelper Instance = new PosChannelHelper();
    private PosChannelHelper()
    {
    }

    public void Start()
    {
        Thread th = new Thread(DoWorks);
        th.IsBackground = true;
        th.Start();
    }

    private void DoWorks()
    {
        while (true)
        {
            try
            {
                WebCMSEntities db = new WebCMSEntities();
                DoSomething(db);
                db.Dispose();
                Thread.Sleep(600000);
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "补下单机具券奖励异常");
            }
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "补下单机具券奖励日志");
        }
    }

    public void DoSomething(WebCMSEntities db)
    {
        List<PosChannelSet> mains = db.PosChannelSet.Where(m => m.Status == 0).ToList();
        foreach(PosChannelSet main in mains)
        {
            int PassCount = 0;
            string PosSnList = "";
            List<PosChannelSetRecord> list = db.PosChannelSetRecord.Where(m => m.RecordId == main.Id).ToList();
            foreach(PosChannelSetRecord sub in list)
            {
                string jsonString = QueryTermAcqInfo(sub.PosSn);
                JsonData jsonData = JsonMapper.ToObject(jsonString);
                if(jsonData["resultCode"].ToString() == "1")
                {
                    string acqInstId = jsonData["data"]["acqInstId"].ToString();
                    if(sub.ChannelNo == acqInstId)
                    {
                        PosChannelSetRecord edit = db.PosChannelSetRecord.FirstOrDefault(m => m.Id == sub.Id);
                        if(edit != null)
                        {
                            edit.Status = 1;
                            db.SaveChanges();
                            PosSnList += edit.PosSn + ",";
                            PassCount += 1;
                        }
                    }
                }
            }
            if(PassCount >= list.Count)
            {
                PosChannelSet edit = db.PosChannelSet.FirstOrDefault(m => m.Id == main.Id);
                if(edit != null)
                {
                    edit.Status = 1;
                    db.SaveChanges();
                    Users user = db.Users.FirstOrDefault(m => m.Id == edit.UserId) ?? new Users();
                    string ChannelName = "";
                    if(edit.ChannelNo == "48130000") ChannelName = "环讯";
                    if(edit.ChannelNo == "48310000") ChannelName = "易生";
                    if(edit.ChannelNo == "48330000") ChannelName = "海科";
                    if(edit.ChannelNo == "48470000") ChannelName = "中付";
                    RedisDbconn.Instance.AddList("MsgPersonalQueue", Newtonsoft.Json.JsonConvert.SerializeObject(new MsgPersonal()
                    {
                        UserId = edit.UserId, //创客
                        Title = "机具通道变更通知", //标题
                        Content = "<div class='f16' style='padding:12px 16px;'>尊敬的" + user.RealName + "盟主您好:<br />您名下的机具SN:<br />" + PosSnList.TrimEnd(',').Replace(",", "<br />") + "，通道已更改为" + ChannelName + "，请知悉!</div>", //内容
                        CreateDate = DateTime.Now,
                    }));
                }
            }
        }
    }






    
        #region 盒易付

        //测试环境
        // string BoxRequestUrl = "https://openapi-test.iboxpay.com/api";
        // string BoxAppId = "8840021411446784";
        // string BoxAppSecret = "xgwGnmYGjVy0GOWOWkQtRk8Hk8ur5tCV";
        // string BoxPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjMQxp24mjxDTr13uPW0y+tiO1yXFGw7P/pPQ0oZKK7F6KstEaus7pLEywBZ5XRXE5jgkhR2TS7Ne7djJfbpn5yFc6pPlz3ZsOfBVeB88NEwhx6xzCGX2eqSSkO33n8w2G0xc2ss5HpYBarT00NBZWhrwOXpdRPYLOYHKVU3Rl+FA9xDw/wYfoWvrr+JSfHRGn/ENMmQFEdckAbPauKaQMrZD2kz+PRrhq56eWnCuVQPcaz/jroVT8qQEgkg2IsNy+DwfLOIqm8IySEpxnQ5wN/KvsQJc2wXDQNf9F5kvWwjoqSSP0qJS+oPRXET+zJb+WTk2y5M6AYoC9NodwsC4NwIDAQAB";
        // string BrhCode = "039001";
        
        //生产环境
        string BoxRequestUrl = "https://openapi.iboxpay.com/api";
        string BoxAppId = "AP5879017839106039808";
        string BoxAppSecret = "DGtftIyl6R3nzwPr5YuV5fnmkfwufXRj";
        string BoxPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjmjoQirIYZBD9Qon2HkF4j/NAINXtJ7Lzq/WXxTF7t7mg7LNARt0+ZZaeWx8caq2fv5zdsGyyoInL23cBtDI5KmFfK69iA0ygQMK0WbiKqsUB1OpPbT3+9zLuadIJAznjA223lY6CIjTpdLZhaRjImNVqc60bdkx6YsQcA+xW+3r1JH4PPHb7yBEbkKIX8OhyX7U4p0TkbDkAobbjHr5YB9gmYLoSFJMOPfTtSExkv7/Y7IVR9poZAHcr3teFoAiXW3RzxelRtnXxIkl/6AUOKoL5fhr/UTUN+Q18uzNljYWr6SwnTI3EmtzgykaewWtZvV85Xdhe/BjiQ5Xor7YbwIDAQAB";
        string BrhCode = "039034";

        public string BoxServiceFee(string SnList, string ServiceFee)
        {
            function.WriteLog(DateTime.Now.ToString(), "设置盒易付机具服务费");
            function.WriteLog(SnList, "设置盒易付机具服务费");
            Dictionary<string, object> reqdic = new Dictionary<string, object>();
            Dictionary<string, string> headdic = new Dictionary<string, string>();
            string batchNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);

            string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            headdic.Add("appid", BoxAppId);//开发者id
            headdic.Add("appsecret", BoxAppSecret);//开发者密码
            headdic.Add("X-Up-AppId", BoxAppId);
            headdic.Add("X-Timestamp", timestamp);
            headdic.Add("X-Sign-Type", "SHA-256");
            
            reqdic.Add("snList", SnList.Split(',').ToList());//终端列表
            if(ServiceFee != "0")
            {
                ServiceFee += "00";
            }
            reqdic.Add("depositGear", ServiceFee);//押金档位
            reqdic.Add("modelId", "MHN10916");//费率，固定0.6
            reqdic.Add("brhCode", BrhCode);//机构号
            reqdic.Add("batchNo", batchNo);//批次号
            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);

            headdic.Add("X-Sign", SHA256Sign(timestamp + BoxAppSecret + req));
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            function.WriteLog("请求头\n" + head, "设置盒易付机具服务费");
            function.WriteLog("请求参数\n" + req, "设置盒易付机具服务费");
            function.WriteLog("请求地址：" + BoxRequestUrl + "/inst/register/terms", "设置盒易付机具服务费");
            string result = PostWebRequest(BoxRequestUrl + "/inst/register/terms", req, headdic);
            function.WriteLog("返回\n" + result + "\n\n", "设置盒易付机具服务费");
            return result;
        }

        public string BoxFee(string MerNo, string Fee)
        {
            function.WriteLog(DateTime.Now.ToString(), "设置盒易付机具费率");
            function.WriteLog(MerNo, "设置盒易付机具费率");
            Dictionary<string, object> reqdic = new Dictionary<string, object>();
            Dictionary<string, string> headdic = new Dictionary<string, string>();
            string batchNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);

            string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            headdic.Add("appid", BoxAppId);//开发者id
            headdic.Add("appsecret", BoxAppSecret);//开发者密码
            headdic.Add("X-Up-AppId", BoxAppId);
            headdic.Add("X-Timestamp", timestamp);
            headdic.Add("X-Sign-Type", "SHA-256");

            reqdic.Add("mchtNo", MerNo);//终端列表
            reqdic.Add("brhCode", BrhCode);//机构号
            reqdic.Add("tNDiscId", Fee == "0.6" ? "MHN10916" : "MHN10917");//费率模型
            reqdic.Add("effectiveFlag", "1");//立即生效
            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);

            headdic.Add("X-Sign", SHA256Sign(timestamp + BoxAppSecret + req));
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            function.WriteLog("请求头\n" + head, "设置盒易付机具费率");
            function.WriteLog("请求参数\n" + req, "设置盒易付机具费率");
            function.WriteLog("请求地址：" + BoxRequestUrl + "/inst/mcht/update_disc", "设置盒易付机具费率");
            string result = PostWebRequest(BoxRequestUrl + "/inst/mcht/update_disc", req, headdic);
            function.WriteLog("返回\n" + result + "\n\n", "设置盒易付机具费率");
            return result;
        }

        //查询终端收单机构
        public string QueryTermAcqInfo(string SnNo)
        {
            function.WriteLog(DateTime.Now.ToString(), "查询终端收单机构");
            function.WriteLog(SnNo, "查询终端收单机构");
            Dictionary<string, object> reqdic = new Dictionary<string, object>();
            Dictionary<string, string> headdic = new Dictionary<string, string>();

            string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            headdic.Add("appid", BoxAppId);//开发者id
            headdic.Add("appsecret", BoxAppSecret);//开发者密码
            headdic.Add("X-Up-AppId", BoxAppId);
            headdic.Add("X-Timestamp", timestamp);
            headdic.Add("X-Sign-Type", "SHA-256");
            
            reqdic.Add("tusn", SnNo); //机具号
            string req = Newtonsoft.Json.JsonConvert.SerializeObject(reqdic);

            headdic.Add("X-Sign", SHA256Sign(timestamp + BoxAppSecret + req));
            string head = Newtonsoft.Json.JsonConvert.SerializeObject(headdic);
            function.WriteLog("请求头\n" + head, "查询终端收单机构");
            function.WriteLog("请求参数\n" + req, "查询终端收单机构");
            function.WriteLog("请求地址：" + BoxRequestUrl + "/inst/term/queryTermAcqInfo", "查询终端收单机构");
            string result = PostWebRequest(BoxRequestUrl + "/inst/term/queryTermAcqInfo", req, headdic);
            function.WriteLog("返回\n" + result + "\n\n", "查询终端收单机构");
            return result;
        }

        public string SHA256Sign(string toSignStr)
        {
            byte[] toSignByte = Encoding.UTF8.GetBytes(toSignStr);
            SHA256 sha256 = SHA256.Create();
            byte[] signByte = sha256.ComputeHash(toSignByte);
            string sign = Convert.ToBase64String(signByte);
            return sign;
        }

        public bool VerifySign(string toSignStr, string signStr)
        {
            byte[] toSignByte = Encoding.Default.GetBytes(toSignStr);
            byte[] signByte = Convert.FromBase64String(signStr);
            var toKey = Convert.FromBase64String(BoxPublicKey);
            var rsaroot = RSA.Create();
            rsaroot.ImportSubjectPublicKeyInfo(toKey, out _);
            var publicKeyParameters = rsaroot.ExportParameters(false);
            using (var rsa = RSA.Create())
            {
                rsa.ImportParameters(publicKeyParameters);
                var sha256 = SHA256.Create();
                var hash = sha256.ComputeHash(toSignByte);
                return rsa.VerifyHash(hash, signByte, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
            }
        }

        public string SignData(string toSignStr)
        {
            byte[] toSignByte = Encoding.UTF8.GetBytes(toSignStr);
            var toKey = Convert.FromBase64String(BoxPublicKey);
            var rsaroot = RSA.Create();
            rsaroot.ImportSubjectPublicKeyInfo(toKey, out _);
            var publicKeyParameters = rsaroot.ExportParameters(false);
            using (var rsa = RSA.Create())
            {
                rsa.ImportParameters(publicKeyParameters);
                var sha256 = SHA256.Create();
                var hash = sha256.ComputeHash(toSignByte);
                byte[] endByte = rsa.SignData(toSignByte, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
                return Convert.ToBase64String(endByte);
            }
        }

        public string PostWebRequest(string postUrl, string paramData, Dictionary<string, string> headers)
        {
            string ret = string.Empty;
            try
            {
                function.WriteLog(DateTime.Now.ToString(), "请求开店宝API日志");
                function.WriteLog(postUrl, "请求开店宝API日志");
                function.WriteLog(paramData, "请求开店宝API日志");
                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();
                function.WriteLog(srcString, "请求开店宝API日志");
            }
            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(), "请求开店宝API异常");
            }
            return ret;
        }

        #endregion

}