using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYY.TaskTrack.Standard.TaskModel;
using XYY.TaskTrack.Standard;
using XYY.Data.Model.Standard.Tracking;
using XYY.Service.Standard.First.DB;
using XYY.Service.Standard.DingDing;
using XYY.Api.WarningNotice.WarningNoticeService;
using AgileHttp;

namespace XYY.Service.Standard.First.JobSubscribe
{

    public interface IWebHook
    {
        void SendMarkdown(string msg);

        string PostFile(string file);

        void SendFile(string mid);
    }

    public class QYWXWebHook : IWebHook
    {
        public string Url;

        public QYWXWebHook(string url)
        {
            Url = url;
        }

        public string PostFile(string file)
        {
            throw new NotImplementedException();
        }

        public void SendFile(string mid)
        {
            throw new NotImplementedException();
        }

        public void SendMarkdown(string msg)
        {
            HttpClient client = new HttpClient(Url);
            Dictionary<string, string> header = new Dictionary<string, string>();
            header.Add("Content-Type", "application/json");
            client.Config(new RequestOptions { Headers = header });
            var responseInfo = client.Post(msg);
        }
    }

    /// <summary>
    /// 细刻轨迹推送消费服务
    /// </summary>
    public class XiKeTrackingSendJobSubscribe : IBaseConsumer<List<XikeTraceMessage>>
    {
        ITrackingLogDB trackingLogDB;
        IWebHook webHook;
        public XiKeTrackingSendJobSubscribe(ITrackingLogDB trackingLogDB, IWebHook webHook)
        {
            this.trackingLogDB = trackingLogDB;
            this.webHook = webHook;
        }

        public Task Consume(List<XikeTraceMessage> message)
        {
            XiKeApi xiKeApi = new XiKeApi();
            var result = xiKeApi.SendMessage(message);
            //写入日志
            trackingLogDB.ManyUpdate(result);
            //包含失败时，警报！
            if (result.Any(x => !x.IsSuccess))
            {
                List<string> ddmsgList = result.Where(x => !x.IsSuccess).Take(3).Select(x =>
                   "\n>" + x.Key + "\n" + x.ErrorMessage).ToList();
                string ddmsg = string.Join("", ddmsgList);
                var msg = new
                {
                    msgtype = "markdown",
                    markdown = new
                    {
                        content = $"轨迹推送失败<font color=\"warning\">{ddmsgList.Count}条</font>其中前3条如下{ddmsg}"
                    }
                };
                string strmsg = Newtonsoft.Json.JsonConvert.SerializeObject(msg);
                webHook.SendMarkdown(strmsg);
            }
            return Task.CompletedTask;
        }
    }

}
