using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Library;
// using MongoDB.Bson;
// using MongoDB.Driver;
// using MongoDB.Driver.Linq;

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


        #region 发送短信验证码

        private string host = "https://gyytz.market.alicloudapi.com";
        private string path = "/sms/smsSend";
        private string method = "POST";
        private string appcode = "8e5704921ca3422f80f0deb935a7ddc6";

        public string Do(string mobile, string code)
        {
            string logString = "";
            String querys = "mobile=" + mobile + "&param=**code**%3A" + code + "%2C**minute**%3A5&smsSignId=8b278cf2bb2a4b3c818cc7a436307a12&templateId=908e94ccf08b4476ba6c876d13f084ad";
            logString += "\n" + querys;
            String bodys = "";
            String url = host + path;
            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;

            if (0 < querys.Length)
            {
                url = url + "?" + querys;
            }

            if (host.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = method;
            httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
            if (0 < bodys.Length)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }

            Stream st = httpResponse.GetResponseStream();
            StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
            string result = reader.ReadToEnd();
            logString += "\n" + result;
            LogHelper.Instance.WriteLog(logString, "阿里云短信验证码日志", true);
            return result;
        }

        public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }

        #endregion
    }
}