using System;
using System.Collections.Generic;
using System.Net;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.AppMessagePush;
using Siger.Middlelayer.Common.AppMessagePush.Model;
using Siger.Middlelayer.Common.AppSMSSend;
using Siger.Middlelayer.Common.AppSMSSend.Model;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Repository.Entities;

namespace Siger.ApiTPM.Utilities
{
    public class MessagePushHelper: IDisposable
    {
        private readonly int _signId;
        private readonly bool _sendMessage = false;
        private static JPushClient _jpushClient;
        private static JSMSClient _jsmsClient;

        public MessagePushHelper(string appkey, string appsecret, int signid, int issendSMS)
        {
            _jpushClient = new JPushClient(appkey, appsecret);
            _jsmsClient = new JSMSClient(appkey, appsecret);
            _signId = signid;
            _sendMessage = issendSMS == 1;
        }

        public PushMessageResult PushMessage(siger_app_project_message message, bool isOnline, string toUserKey, string mobile, int templateId, Dictionary<string, string> paras)
        {
            if (isOnline)
            {
                if (string.IsNullOrWhiteSpace(toUserKey))
                {
                    return PushMessageResult.UserAppKeyIsEmpty;
                }

                if (PushOnLineMessage(toUserKey, message.title, message.content, message))
                {
                    return PushMessageResult.SendSuccessful;
                }

                return PushMessageResult.PushMessageFailed;
            }
            else
            {
                if (!_sendMessage)
                {
                    return PushMessageResult.SendSMSFailed;
                }
                if (string.IsNullOrWhiteSpace(mobile))
                {
                    return PushMessageResult.UserMobileIsEmpty;
                }

                if (SendSMSMessage(mobile, templateId, paras))
                {
                    return PushMessageResult.SendSuccessful;
                }
                return PushMessageResult.SendSMSFailed;
            }
        }

        public bool PushOnLineMessage(string appKey, string title, string content, siger_app_project_message message)
        {
            return ExecutePush(appKey, title, content, message);
        }

        public bool SendSMSMessage(string mobile, int templateId, Dictionary<string, string> paras)
        {
            if (paras == null)
            {
                Logger.WriteLineWarn("paras is null.");
                return false;
            }
            if (templateId <= 0)
            {
                Logger.WriteLineWarn("get sms massage template failed.");
                return false;
            }

            return ExecuteSendSMS(mobile, templateId, paras);
        }

        private bool ExecutePush(string registerId, string title, string content, siger_app_project_message message)
        {
            var audience =
                new Dictionary<string, List<string>> {{"registration_id", new List<string> {registerId}}};
            PushPayload pushPayload = new PushPayload()
            {
                Platform = new List<string> { "android","ios" },
                Audience = audience,
                Notification = new Notification
                {
                    Alert = title,
                    Android = new Android
                    {
                        Alert = content,
                        Title = title,
                        BuilderId = 1,
                        Extras  = new Dictionary<string, object>
                        {
                            { "msgid", message.id },
                            { "msgtype", message.type }
                        }
                    },
                    IOS = new IOS
                    {
                        Alert = new Dictionary<string, string>
                        {
                            { "title", title },
                            { "body", content }
                        },
                        Sound = "sound.caf",
                        Badge = "+1",
                        Extras = new Dictionary<string, object>
                        {
                            { "msgid", message.id },
                            { "msgtype", message.type }
                        }
                    }
                },
                //Message = new Message
                //{
                //    Title = title,
                //    Content = content
                //},
                Options = new Options
                {
                    IsApnsProduction = true, //指定 APNS 通知发送环境
                    SendNo = UnixTimeHelper.GetNow(),
                    TimeToLive = 86400 //保存离线时间的秒数默认为一天
                }
            };
            try
            {
                var response = _jpushClient.SendPush(pushPayload);
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    return true;
                }
                Logger.WriteLineError($"ExecutePush to {registerId} failed, message:" + response.Content);
            }
            catch (Exception e)
            {
               Logger.WriteLineError($"ExecutePush to {registerId} failed, error:" + e);
            }

            return false;
        }

        private bool ExecuteSendSMS(string mobile, int templateId, Dictionary<string, string> paras)
        {
            try
            {
                var template = new TemplateMessage
                {
                    SignId = _signId,
                    Mobile = mobile,
                    TemplateId = templateId,
                    Type = 2, // 通知类
                    TemplateParameters = paras
                };
                var response = _jsmsClient.SendTemplateMessage(template);
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    return true;
                }
                Logger.WriteLineError($"ExecutePush to {mobile} failed, message:" + response.Content);
            }
            catch (Exception e)
            {
                Logger.WriteLineError($"ExecutePush to {mobile} failed, error:" + e);
            }

            return false;
        }

        public void Dispose()
        {
            _jpushClient = null;
            _jsmsClient = null;
        }
    }
}
