using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using MrWu.Debug;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Server.Core
{
    /// <summary>
    /// 微信机器人管理
    /// </summary>
    public class WeChatRobotManager : SingleInstance<WeChatRobotManager>
    {
        public enum RobotType
        {
            /// <summary>
            /// Bug提交
            /// </summary>
            BugReport,
            
            /// <summary>
            /// 统计
            /// </summary>
            StatisticsReport,
            
            /// <summary>
            /// SQL自动化
            /// </summary>
            SqlAutoReport,
            
            /// <summary>
            /// 俱乐部信息文件推送
            /// </summary>
            ClubFileAutoReport,
            
            /// <summary>
            /// 奔溃推送
            /// </summary>
            CrashReport,
            
            /// <summary>
            /// 监控报警
            /// </summary>
            MonitorAlarm,
        }
        
        public class MsgData
        {
            public string msgtype;

            public MsgContent text;
        }
        
        public class MsgContent
        {
            public string content;
        }

        private static readonly Dictionary<RobotType, string> WebHookKey = new Dictionary<RobotType, string>()
        {
            {
                RobotType.ClubFileAutoReport,
                "4fb2a61f-d99b-4a5f-b712-7e5df35e4f03"
            },
            {
                RobotType.SqlAutoReport,
                "fd74fe28-82a0-4a51-98e7-32b623fe324d"
            },
            {
                RobotType.StatisticsReport,
                "a871b76a-bd2e-45d3-9cb2-5b13a57f9435"
            },
            {
                RobotType.BugReport,
                "8e94e385-6a2b-4785-8d2b-c8d2d9f7d21a"
            },
            {
                RobotType.CrashReport,
                "d260c0b1-cca1-4c5c-85bd-0b0a8f7ed148"
            },
            {
                RobotType.MonitorAlarm,
                "6ad8b86b-2f2d-4f7d-a5d0-539cf54b80fb"
            }
            // {
            //     RobotType.MonitorAlarm,
            //     "ce0249cb-b548-4c48-be82-c404fb1ad104"
            // }
        };
        
        private string GetUploadUrl(RobotType robotType) => $"https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key={WebHookKey[robotType]}&type=file";
        private string GetMessageUrl(RobotType robotType) => $"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={WebHookKey[robotType]}";

        public Task<string> SendMsg(string msg, RobotType robotType)
        {
            string content = JsonConvert.SerializeObject(new MsgData
            {
                msgtype = "text",
                text = new MsgContent()
                {
                    content = msg
                }
            });

            return Task.Run(() => HttpHelper.Post(GetMessageUrl(robotType), Encoding.UTF8.GetBytes(content)));
        }

        public void SendFile(string filePath, RobotType robotType)
        {
            UploadFile(filePath, robotType);
        }
        
        public void SendFileAsync(string filePath, RobotType robotType)
        {
            Task.Run(() =>
            {
                UploadFile(filePath, robotType);
            });
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        private void UploadFile(string filePath, RobotType robotType)
        {
            try
            {
                string retContent = HttpHelper.PostFile(GetUploadUrl(robotType), filePath);
                Debug.Log($"上传结束: {retContent}");
                var retObj = JsonConvert.DeserializeObject(retContent) as JObject;
                if (retObj != null && retObj.TryGetValue("errcode", out var errcodeObj) )
                {
                    if (errcodeObj.Value<int>() == 0 && retObj["media_id"] != null)
                    {
                        string mediaId = retObj["media_id"].Value<string>();
                        var messageData = new
                        {
                            msgtype = "file",
                            file = new { media_id = mediaId }
                        };
                        
                        HttpHelper.Post(GetMessageUrl(robotType), Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messageData)));
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Debug.Log("[WeChatRobotManager]上传失败");
            }
        }
    }
}