using Newtonsoft.Json;
using Quartz;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XYY.Tool.QuotaReduction;
using XYY.Tool.TimingTask.Model;

namespace XYY.Tool.TimingTask.jobs
{
    public class Lading51TrackJob : IJob
    {
        public class Lading51TrackResult
        {
            public string LadingBillNumber { get; set; }
            public string errorMessage { get; set; }
        }
        public Task Execute(IJobExecutionContext context)
        {
            string msg = string.Empty;
            var client = new RestClient(JobConfig.Lading51TrackApi);
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Authorization", "token 57AEDE5487260443D6BF2182D31286B1");
            request.AddHeader("Content-Type", "application/json");
            List<string> bodys = new List<string>() { };
            request.AddJsonBody(bodys);
            IRestResponse response = client.Execute(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var result = JsonConvert.DeserializeObject<ApiJsonModel>(response.Content);
                if (result.success == true)
                {
                    var apiData = JsonConvert.DeserializeObject<List<Lading51TrackResult>>(result.data.ToString());
                    if (apiData.Count > 0)
                    {
                        msg = "51提单轨迹任务失败数据：" + string.Join(";\r\n", apiData.Select(x => x.LadingBillNumber + ":" + x.errorMessage));
                    }
                    else
                    {
                        msg = "51提单轨迹任务执行成功";
                    }
                }
            }
            else
            {
                msg += "51提单轨迹任务接口调用失败！" + response.ErrorMessage ?? response.Content;
            }
            if (msg.Contains("失败")) { dingApiRequest.sendDingMessageToChat("Lading51TrackApi", msg); }
            return null;
        }
    }
}
