using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Net.Http.Json;
using System.Text.Json;
using System.IO;
using TEAMModelOS.SDK.Extension;

namespace TEAMModelOS.SDK.DI
{
    public class DingDing
    {
        private const string url = "https://oapi.dingtalk.com/robot/send?access_token=";
        private readonly HttpClient _httpClient;

        public DingDing(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        // <summary>
        /// 發送需要加簽驗證的Bot訊息(msgtype為text)
        /// </summary>
        /// <param name="robotUrl">釘釘Robot發送Url</param>
        /// <param name="secret">加簽密鑰</param>
        /// <param name="msg">發送訊息</param>
        /// <returns></returns>
        public async Task SendBotMsg(string msg, GroupNames groupkey)
        {
            var content = new { msgtype = "text", text = new { content = msg } };
            var keys = groupkey.GetDescriptionText().Split(',');
            if (keys.Length == 1) await _httpClient.PostAsJsonAsync($"{url}{keys[0]}", content);
            else
            {
                var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                await _httpClient.PostAsJsonAsync($"{url}{keys[0]}&timestamp={timestamp}&sign={BotAddSign(keys[1], timestamp)}", content);
            }
        }

        // <summary>
        /// 發送需要加簽驗證的Bot訊息(msgtype為text)
        /// </summary>
        /// <param name="robotUrl">釘釘Robot發送Url</param>
        /// <param name="secret">加簽密鑰</param>
        /// <param name="msg">發送訊息</param>
        /// <returns></returns>
        public async Task SendBotMsg(string msg, string accesstoken, string secret = null)
        {
            var content = new { msgtype = "text", text = new { content = msg } };
            if (string.IsNullOrWhiteSpace(secret))
                await _httpClient.PostAsJsonAsync($"{url}{accesstoken}", content);
            else
            {
                var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                await _httpClient.PostAsJsonAsync($"{url}{accesstoken}&timestamp={timestamp}&sign={BotAddSign(secret, timestamp)}", content);
            }


        }

        #region private
        /// <summary>
        /// 釘釘Bot簽名生成方法
        /// </summary>
        /// <param name="zTime"></param>
        /// <returns></returns>
        private static string BotAddSign(string secret, long zTime)
        {
            //"SEC6a6822db6567f79854a474002407cd9ac36da4d194b5fb79e073c35ef61119ed";
            string stringToSign = zTime + "\n" + secret;
            var encoding = new System.Text.ASCIIEncoding();
            byte[] keyByte = encoding.GetBytes(secret);
            byte[] messageBytes = encoding.GetBytes(stringToSign);
            using (var hmacsha256 = new HMACSHA256(keyByte))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                return System.Web.HttpUtility.UrlEncode(Convert.ToBase64String(hashmessage), Encoding.UTF8);
            }
        }
        #endregion
    }

    public enum GroupNames
    {
        [Description("ce63217d9c734a92fd91c7c9ceaa9b25e109cce94615a7f75288dc43865a6e20,SEC6a6822db6567f79854a474002407cd9ac36da4d194b5fb79e073c35ef61119ed")]
        研發C組,
        [Description("2c5ced0725b592b1a96f1fb800d6d9a15727986ef75923a838a4d24e6b8c9147,SEC66ff954306c1fd98b5b160e23c253649f22205e69a16fb26e18d136f49875a9e")]
        客戶回饋群組,
        [Description("f8bf19c9363e3b288e018856014bcbf89708f19b3aae009e203edd68af25c9fe")]
        BB訂單群組,
        [Description("a27b099b15a054374da41b9f66f72e5fc6b378e98418859f7c0ef46408941808")]
        台北開發測試群組,
        [Description("82aba2fccfa8442c575db3ac0442fa5aea90cd7574bb9a71d5abf210ea72a3aa,SEC3f38eca87cd4fd10505d136f91071a2e8b14cd863bd6bbafb24c612fc751a59a")]
        成都开发測試群組,
        [Description("1a316ce4edc2db88231d40d80072b00f2751d7d9e2e5871c5dc061885b01c48d,SECff60201ac9b219943b9f8fc397fda1a617d0cbc140850f5ea9cb4f131479d39a")]
        醍摩豆服務運維群組
    }


}
