using PushPlatform.Common.Util;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PushPlatform.Common.SmsService;
using PushInfo.Core.Models.Tables;
using PushPlatform.Common.Enumerate;
using PushInfo.Core.Models.QueryResults;
using WebSocketSharp;
using System.Net.Mail;
using PushPlatform.Common.Model;
using System.Net;

namespace PushInfo.Core.BLL
{
    public class SmsBLL
    {
        private static ProjectPushBLL proBll = new ProjectPushBLL();
        private static string smsProjectId = ConfigurationManager.AppSettings["smsProjectId"]; //默认推送项目Id

        private static string sMSMessageSigna = ConfigurationManager.AppSettings["SMSMessageSigna"];  //短信推送模板

        private static string socKetServerUrl = ConfigurationManager.AppSettings["SocKetServerUrl"];  //socket服务器地址
        private static string socKetDefPushId = ConfigurationManager.AppSettings["socKetDefPushId"];

        private static object _Locker = new object();
        #region 推送App
        public APIResult<string> PushSingle(AppPushConfig appCfgModel, string clientid, int type, string title, string body, string transmissionContent)
        {
            APIResult<string> result = new APIResult<string>();
            result.Result = 1;
            try
            {
                //using (SMSServiceClient sms = new SMSServiceClient())
                //{
                //    r = sms.PushMessageToSingle(Guid.Parse(pushProjectId), new string[] { }, clientid, type, title, body, transmissionContent);
                //}
                GeTuiPushMessage.APPID = appCfgModel.AppID;
                GeTuiPushMessage.APPKEY = appCfgModel.AppKey;
                GeTuiPushMessage.MASTERSECRET = appCfgModel.MasterSecret;
                lock (_Locker)
                {
                    return GeTuiPushMessage.PushMessageToSingle(new List<string>(), clientid, type, title, body, transmissionContent);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                result.Result = 0;
                result.code = 1;
                result.Msg = "抛出异常，请查询日志！";
                return result;
            }
        }
        #endregion

        #region 推送短信
        public APIResult<string> PushMessage(string smsProjectId,string mobile, string body,string smsMessageSigna, int smsType)
        {
            APIResult<string> result = new APIResult<string>();
            result.Result = 1;
            try
            {
                var smsresult = "";
                if(smsType == (int)SmsType.博士通)  //607新版短信
                {
                    using (PushPlatform.Common.NewSmsService.SmsServiceClient sms = new PushPlatform.Common.NewSmsService.SmsServiceClient())
                    {
                        var r = sms.SendMsg(smsProjectId, mobile, string.Format(smsMessageSigna, body));
                        smsresult = r;
                        if (r.Substring(0, 1) == "0")
                        {
                            smsresult = "100";
                        }
                    }
                }
                else if(smsType == (int)SmsType.阿里云)
                {
                    using (PushPlatform.Common.NewSmsService.SmsServiceClient sms = new PushPlatform.Common.NewSmsService.SmsServiceClient())
                    {
                        var r = sms.AliSendCode(smsProjectId, smsMessageSigna, "SMS_213772733", mobile, "");
                        smsresult = r;
                        if (r=="OK")
                        {
                            smsresult = "100";
                        }
                    }
                }
                else
                {
                    using (SMSServiceClient sms = new SMSServiceClient())
                    {
                        smsresult = sms.SendMessage(Guid.Parse(smsProjectId), mobile, string.Format(smsMessageSigna, body), null).ToString();
                    }
                }

                if (!smsresult.Equals("100"))
                {
                    result.Result = 0;
                    result.Msg = smsresult;
                }
            }
            catch (Exception e)
            {
                LogHelper.Error(e);
                result.Result = 0;
                result.code = 1;
                result.Msg = "抛出异常，请查询日志！";
                return result;
            }
            return result;
        }
        #endregion

        #region 推送项目异常给项目管理人员
        public static void PushErrorInfo(string projectId,string errorMsg)
        {
            try
            {
                Project_Info proModel = proBll.GetProjectById(projectId);
                if(proModel == null)
                {
                    return;
                }
                string smsresult = string.Empty;
                using (SMSServiceClient sms = new SMSServiceClient())
                {
                    smsresult = sms.SendMessage(Guid.Parse(smsProjectId), proModel.InternalPrincipalMobile, string.Format(sMSMessageSigna, errorMsg), null).ToString();
                }
            }
            catch (Exception e)
            {
                LogHelper.Error(e);
            }
        }
        #endregion

        #region socket推送
        public void PushSocket(Map_Project_Push mapProPush, DataMessage Data)
        {
            string dataStr = JsonHelper.ToJson(mapProPush);
            string sendInfo = Data.userId+"|"+ dataStr;

            using (var ws = new WebSocket("ws://"+ socKetServerUrl+ "?user="+socKetDefPushId))
            {
                ws.OnMessage += (sender, e) =>
                  LogHelper.Info("Laputa says: " + e.Data);
                ws.Connect();
                ws.Send(sendInfo);
            }
        }
        #endregion

        #region 发送邮件
        /// <summary>
        /// 发送邮件    
        /// </summary>
        /// <param name="recipients">收件人邮箱</param>
        /// <param name="subject">主题</param>
        /// <param name="content">正文</param>
        /// <param name="emailConfig">发送服务配置</param>
        public APIResult<string> SendEmail(string recipients, string subject, string content, MailConfig emailConfig)
        {
            APIResult<string> returnResult = new APIResult<string>();
            returnResult.Result = 1;
            try
            {
                MailMessage mailObj = new MailMessage();
                mailObj.From = new MailAddress(emailConfig.Email); //发送人邮箱地址

                if (recipients.Contains(","))
                {
                    string[] recipients_arr = recipients.Split(',');
                    if (recipients_arr != null && recipients_arr.Length > 0)
                    {
                        foreach (string r in recipients_arr)
                        {
                            mailObj.To.Add(r);   //收件人邮箱地址
                        }
                    }
                }
                else
                {
                    mailObj.To.Add(recipients);   //收件人邮箱地址
                }

                mailObj.Subject = subject;    //主题
                mailObj.Body = content;    //正文
                mailObj.IsBodyHtml = true;
                mailObj.BodyEncoding = System.Text.Encoding.UTF8;
                SmtpClient smtp = new SmtpClient();
                smtp.Host = emailConfig.Smtp;         //smtp服务器名称
                smtp.UseDefaultCredentials = true;
                smtp.Credentials = new NetworkCredential(emailConfig.Email, emailConfig.Pwd);  //发送人的登录名和密码
                smtp.Send(mailObj);
                returnResult.Msg = "1";
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                returnResult.Result = 0;
                returnResult.code = 1;
                returnResult.Msg = "抛出异常，请查询日志！";
            }
            return returnResult;
        }
        #endregion
    }
}
