using Newtonsoft.Json;
using RMYY_CallCenter_Api.Model;
using RMYY_CallCenter_Api.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace RMYY_CallCenter_Api.Controllers
{
    public class PushMessageController : BaseController
    {


        //定义常量, appId、appKey、masterSecret 采用本文档 "第二步 获取访问凭证 "中获得的应用配置
        private static String APPID = ConfigHelper.GetValue("APPID");
        private static String APPKEY = ConfigHelper.GetValue("APPKEY");
        private static String MASTERSECRET = ConfigHelper.GetValue("MASTERSECRET");
        private Bll .T_Sys_UserAccount userBLL = new Bll.T_Sys_UserAccount();
        public class AppClientListDto
        {
            /// <summary>
            /// 应用分类（1android 2ios）
            /// </summary>
            public int apptype { get; set; }
            /// <summary>
            /// app端ClientId值
            /// </summary>
            public string clientid { get; set; }
            /// <summary>
            /// 用户code
            /// </summary>
            public string usercode { get; set; }
        }
       
        public ActionResult PutAppClientIdAsync(string clientid, int apptype = 1)
        {
           
            LogHelper.Debug("clientid"+ clientid);
            var list = new List<AppClientListDto>();
            string usercode = "";
            if (User != null)
            {
                usercode = User.F_UserCode;
            }
            //获取redis缓存
            var clientidStr = RedisHelper.StringGet("clientidlist");

            if (clientidStr != null)
                list = clientidStr.ToString().ToList<AppClientListDto>();
            if (!string.IsNullOrEmpty(clientid))
            {
                var count = 0;

                #region 去重 - 保证只有一个坐席账号，且只往一个登录账号的手机上推送
                var lists = list.Where(x => x.usercode == usercode).ToList();
                if (lists != null) count = lists.Count();
                if (count > 0)
                {
                    foreach (var item in lists)
                    {
                        list.Remove(item);
                    }
                }
                var cilid = list.Where(x => x.clientid == clientid).ToList();
                if (cilid != null)
                {
                    if (cilid.Count > 0)
                    {
                        foreach (var item in cilid)
                        {

                            list.Remove(item);
                        }
                    }
                }
                //存入redis缓存
                list.Add(new AppClientListDto
                {
                    apptype = apptype,
                    clientid = clientid,
                    usercode = usercode
                });

                RedisHelper.StringSet("clientidlist", list.ToJson());
                #endregion
                return Success("保存ClientId成功");
            }
            return Success("没有获取到该设备clientid");

        }
        private static InternalMessagesController msg = new InternalMessagesController();
        public ActionResult Clild(string usercode)
        {
            var userModel = new Bll.T_Sys_UserAccount().GetModel(usercode);

            if (userModel != null)
            {
                usercode = userModel.F_UserCode;
            }
            var clientidStr = RedisHelper.StringGet("clientidlist");
            var list = new List<AppClientListDto>();
            if (clientidStr != null)
                list = clientidStr.ToString().ToList<AppClientListDto>();
            var lists = list.Where(x => x.usercode == usercode).ToList();
            string clientid = "";
            if (lists != null)
            {
                foreach (var item in lists)
                {
                    clientid = item.clientid;
                }
            }
            var obj = new
            {
                state = "success",
                message = "成功",
                pushResult = clientid
            };
            return Content(obj.ToJson()); ;
        }
        [AllowAnonymous ]
        public ActionResult Push(string Title, string content, string usercode)
        {
            return Success(PushApp(Title, content, usercode));
        }

        public static string PushApp(string Title, string content, string usercode)
        {
            string pushResult = "";
            var clientidStr = RedisHelper.StringGet("clientidlist");
            var list = new List<AppClientListDto>();
            if (clientidStr != null)
                list = clientidStr.ToString().ToList<AppClientListDto>();
            var lists = list.Where(x => x.usercode == usercode).ToList();
            string clientid = "";
            if (lists != null)
            {
                foreach (var item in lists)
                {
                    clientid = item.clientid;
                }
            }
            if (!string.IsNullOrEmpty(clientid))
            {
                try
                {
                    var t = PushAppSend(Title, content, clientid);
                    pushResult = t;
                }
                catch (Exception e)
                {
                    LogHelper.Error("PushApp" + e.Message);
                    pushResult = e.Message;
                }
            }

            return pushResult; ;
        }

       
        private static string appSendToken = "";
        /// <summary>
        /// 获取token
        /// </summary>
        /// <returns></returns>
        public static string GetAppSendToken()
        {
            string token = "";
            if (!string.IsNullOrWhiteSpace(appSendToken))
            {
                return appSendToken;
            }
            
            //签名 ： appkey+timestamp+mastersecret   SHA256加密
            string timestamp = GenerateTimeStamp();//时间戳
            string sign = APPKEY + timestamp + MASTERSECRET;
            sign = sha256(sign); //sha256加密

            var postdata = new
            {
                sign = sign,
                timestamp = timestamp,
                appkey = APPKEY
            };
            string data = JsonConvert.SerializeObject(postdata);

            WebClient wc = new WebClient();
            string url = $@"https://restapi.getui.com/v2/{APPID}/auth";
            wc.Encoding = Encoding.UTF8;
            wc.Headers.Add("Content-Type", "application/json");
            // wc2.Headers.Add("token", "STZN202204020911111");
            try
            {
                string result = wc.UploadString(url, data);
                //{"msg":"success","code":0,"data":{"expire_time":"1652341431131","token":"ef9b1b20798956299552a28ef549e859f2856eae17a2021c81f85e5e8244a40b"}}
                // string result = "{\"msg\":\"success\",\"code\":0,\"data\":{\"expire_time\":\"1652341431131\",\"token\":\"ef9b1b20798956299552a28ef549e859f2856eae17a2021c81f85e5e8244a40b\"}}";
                var detail = result.ToObject<AppResultModel>();
                appSendToken = detail.data.token;
                token = appSendToken;
            }
            catch (Exception ex)
            {
                throw;
            }

            return token;

        }
      
        /// <summary>
        /// 推送
        /// </summary>
        public static string PushAppSend(string title, string content, string cid)
        {
            string token = GetAppSendToken();
            string guid = Guid.NewGuid().ToString();
            #region 示例说明

            //https://restapi.getui.com/v2/kylXOUvnEd8Al3yT39ELR1/push/single/cid

            #endregion

            APPSendModel postDate = new APPSendModel();
            postDate.request_id = guid;
            postDate.settings.ttl = -1;
            postDate.audience.cid.Add(cid);//cid 就是手机的唯一ID，我现在要给这个手机推消息
            postDate.push_message.notification.title = title;
            postDate.push_message.notification.body = content;
            postDate.push_message.notification.click_type = "url";
            postDate.push_message.notification.url = "https//:xxx";
            string data = JsonConvert.SerializeObject(postDate);
            WebClient wc = new WebClient();
            string url = $@"https://restapi.getui.com/v2/{APPID}/push/single/cid";
            wc.Encoding = Encoding.UTF8;
            wc.Headers.Add("Content-Type", "application/json");
            wc.Headers.Add("token", token);


            try
            {
                string result = wc.UploadString(url, data);
                var detail = result.ToObject<AppResultModel>();
                return detail.ToJson();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }
        /// <summary>
        /// app发送model
        /// </summary>
        public class APPSendModel
        {
            public APPSendModel()
            {
                settings = new settings();
                audience = new audience();
                push_message = new push_message();
            }

            /// <summary>
            /// 	请求唯一标识号，10-32位之间；如果request_id重复，会导致消息丢失
            /// </summary>
            public string request_id { get; set; }

            /// <summary>
            /// 推送条件设置，详细解释见下方settings说明
            /// </summary>
            public settings settings { get; set; }

            /// <summary>
            /// 个推推送消息参数，详细内容见push_message
            /// </summary>
            public audience audience { get; set; }

            /// <summary>
            /// 个推推送消息参数
            /// </summary>
            public push_message push_message { get; set; }

        }
        /// <summary>
        /// 推送条件设置
        /// </summary>
        public class settings
        {
            /// <summary>
            /// 	消息离线时间设置，单位毫秒，-1表示不设离线，-1 ～ 3 * 24 * 3600 * 1000(3天)之间
            /// </summary>
            public int? ttl { get; set; }
        }

        /// <summary>
        /// 推送目标用户
        /// </summary>
        public class audience
        {
            /// <summary>
            /// 构造
            /// </summary>
            public audience()
            {
                cid = new List<string>();
            }

            /// <summary>
            /// 别名数组，只能填一个别名；绑定别名请参考
            /// </summary>
            public List<string> cid { get; set; }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        public class push_message
        {
            /// <summary>
            /// 构造
            /// </summary>
            public push_message()
            {
                notification = new notification();
            }
            /// <summary>
            /// 通知
            /// </summary>
            public notification notification { get; set; }
        }

        /// <summary>
        /// 通知
        /// </summary>
        public class notification
        {
            /// <summary>
            /// 通知标题
            /// </summary>
            public string title { get; set; }

            /// <summary>
            /// 通知内容
            /// </summary>
            public string body { get; set; }

            /// <summary>
            /// 写死 url就好
            /// </summary>
            public string click_type { get; set; }

            /// <summary>
            /// "https//:xxx
            /// </summary>
            public string url { get; set; }
        }


        /// <summary>
        /// APP 发送 model
        /// </summary>
        public class AppResultModel
        {

            /// <summary>
            /// 
            /// </summary>
            public string msg { get; set; }

            /// <summary>
            /// 10001 就是过期    0 是成功
            /// </summary>
            public int? code { get; set; }

            /// <summary>
            /// 
            /// </summary>
            public AppResultModelDetail data { get; set; }
        }
        /// <summary>
        /// 
        /// </summary>
        public class AppResultModelDetail
        {
            /// <summary>
            /// 
            /// </summary>
            public string expire_time { get; set; }

            /// <summary>
            /// 
            /// </summary>
            public string token { get; set; }
        }


        #region 私有成员
        /// <summary>
        /// 获取时间撮
        /// </summary>
        /// <returns></returns>
        private static string GenerateTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        /// <summary>
        /// 加密算法
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private static string sha256(string data)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            byte[] hash = SHA256Managed.Create().ComputeHash(bytes);

            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                builder.Append(hash[i].ToString("X2"));
            }

            return builder.ToString();
        }
        #endregion




    }
}