using Quartz;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using XYY.Tool.QuotaReduction;

namespace XYY.Tool.TimingTask.jobs
{
    public class QuotaReductionJob : IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            int count = 0; bool isSucess = false;string msg = string.Empty;
            DateTime startTime =Convert.ToDateTime(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd")); 
            DateTime endTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
            do{
                try
                {
                    RestSharp.RestClient client = new RestSharp.RestClient(JobConfig.QuotaReductionJobApi+ $"?startTime={startTime}&endTime={endTime}");
                    RestSharp.RestRequest request = new RestSharp.RestRequest(RestSharp.Method.POST);
                    request.AddHeader("Authorization", "token 57AEDE5487260443D6BF2182D31286B1");
                    var response = client.Execute(request);
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        isSucess = true;
                    }
                    else
                    {
                        count++;
                    }
                }
                catch (Exception ex)
                {
                    count++;
                }
                //重复赋值，取最后一次错误
                msg = $"授信数据还原:" + JobConfig.QuotaReductionJobApi + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "    "
                    + $"{((count == 0 || count == 1) ? "首次请求" : "请求次数:" + count)},请求结果为{isSucess}";
                Console.WriteLine(msg);
                //睡眠再继续
                if (count <= JobConfig.QuotaReductionJobTryTime && !isSucess) { Thread.Sleep(JobConfig.QuotaReductionJobTryTimeInterval); }
            }
            while (count <= JobConfig.QuotaReductionJobTryTime&& !isSucess) ;
            //失败请求，发送钉钉消息
            if (!isSucess) { dingApiRequest.sendDingMessageToChat("QuotaReductionJob", msg); }
            return null;
        }
    }
}
