using DingTalk.Api;
using DingTalk.Api.Request;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XYY.Service.Standard.DingDing;

namespace XYY.Api.WarningNotice.WarningNoticeService
{
    public class DingTalkWarningNoticeService : BaseService
    {
        private readonly Dictionary<string, string> tokens;

        private IDingDingService _dingDingService;

        public DingTalkWarningNoticeService(IDingDingService dingDingService)
        {
            _dingDingService = dingDingService;
            tokens = new Dictionary<string, string>
            {
                {"定时任务失败", "ff52710d8e80cf44bc7981e557bfb9e123ea491ad9050e2304a634b1fcf0530d"},
                {"发送消息", "ff52710d8e80cf44bc7981e557bfb9e123ea491ad9050e2304a634b1fcf0530d"},
                {"邮政公开价更新", "eae7c7dcea1b5617dcf3d8deb1691aae92ce70310be0751550e89da6034da760"},
                {"定时任务", "ff52710d8e80cf44bc7981e557bfb9e123ea491ad9050e2304a634b1fcf0530d"},
            };
        }

        private string getObjcetToken(WarningNoticeTarget target)
        {
            if (tokens.TryGetValue(target.TargetName, out var token))
            {
                return token;
            }
            throw new Exception($"未找到相关机器人:{target.TargetName}");
        }

        public override bool NoticeText(TextMessageNoticeTarget target)
        {
            string token = getObjcetToken(target);
            string url = $"https://oapi.dingtalk.com/robot/send?access_token={token}";
            //return url;
            //string url = CreateMsgUrl(target);
            //string token = getObjcetToken(target);
            var client = new DefaultDingTalkClient(url);
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            request.Msgtype = "text";
            OapiRobotSendRequest.TextDomain text = new OapiRobotSendRequest.TextDomain();
            text.Content = target.Content;
            request.Text_ = text;
            OapiRobotSendRequest.AtDomain at = new OapiRobotSendRequest.AtDomain();
            at.IsAtAll = true;
            var response = client.Execute(request);
            return response.IsError;
        }

        public override bool NoticeLink(LinkMessageNoticeTarget target)
        {
            string url = CreateMsgUrl(target);
            var client = new DefaultDingTalkClient(url);
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            request.Msgtype = "link";
            OapiRobotSendRequest.LinkDomain link = new OapiRobotSendRequest.LinkDomain();
            link.MessageUrl = target.Link;
            link.Text = target.Text;
            link.Title = target.Title;
            request.Link_ = link;
            OapiRobotSendRequest.AtDomain at = new OapiRobotSendRequest.AtDomain();
            at.IsAtAll = target.ToAllUser;
            at.AtUserIds = target.UserIds;
            var response = client.Execute(request);
            return response.IsError;
        }

        public async override Task<bool> NoticeActionCard(ActionCardNoticeTarget target)
        {
            List<dynamic> buttonJsonList = new List<dynamic>();
            foreach (var btn in target.Buttons)
            {
                var btnItem = new
                {
                    title = btn.Text,
                    action_url = btn.Link,
                };
                buttonJsonList.Add(btnItem);
            }

            List<int> userIds = target.UserIds;
            List<string> ddUserIds = new List<string>();
            foreach (var uid in userIds)
            {
                var ddUserInfo = await _dingDingService.GetDingDingUserInfo(uid);
                if (ddUserInfo != null)
                {
                    ddUserIds.Add(ddUserInfo.UserId);
                }
            }


            string userId = string.Join(",", ddUserIds);
            dynamic actionCard2 = new
            {
                msgtype = "action_card",
                action_card = new
                {
                    title = target.Title + $"_{DateTime.Now.ToString("yyyyMMddHHmmss")}",
                    markdown = target.Text,
                    btn_orientation = target.ButtonOrient,
                    btn_json_list = buttonJsonList
                },
                to_all_user = false,
                userid_list = userId
            };

            string errMsg = await _dingDingService.SendMessage(userId, actionCard2);
            return !string.IsNullOrEmpty(errMsg);
        }

        private string CreateMsgUrl(WarningNoticeTarget target)
        {
            string token = getObjcetToken(target);
            string url = $"https://oapi.dingtalk.com/robot/send?access_token={token}";
            return url;
        }
    }
}
