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

namespace XYY.Tool.TimingTask.jobs
{
    public class GenerateFirstBillsJob:IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            int count = 0; bool isSucess = false; string msg = string.Empty;
            do
            {
                try
                {
                    RestSharp.RestClient client = new RestSharp.RestClient(JobConfig.GenerateFirstBillsJobApi);
                    RestSharp.RestRequest request = new RestSharp.RestRequest(RestSharp.Method.POST);
                    request.AddHeader("Authorization", "token 57AEDE5487260443D6BF2182D31286B1");
                    var response = client.Execute(request);
                    var responseResult = JsonConvert.DeserializeObject<ApiJsonModel>(response.Content);
                    if (responseResult.success)
                    {
                        isSucess = responseResult.success;
                    }
                    else
                    {
                        count++;
                    }
                    //重复赋值，取最后一次错误
                    msg = $"头程账单:" + JobConfig.GenerateFirstBillsJobApi + $"\r\n执行结果:{isSucess}\r\n" ;
                    if (!string.IsNullOrEmpty(responseResult.data.ToString())) 
                    {
                        var info = JsonConvert.DeserializeObject<List<Tuple<int, DateTime, DateTime, string>>>(responseResult.data.ToString());
                        foreach (var item in info)
                        {
                            msg += $"客户Id:{item.Item1},起:{item.Item2},止:{item.Item3},原因:{item.Item4}\r\n";
                        }
                    }
                }
                catch (Exception ex)
                {
                    count++;
                }
                Console.WriteLine(msg);
                //睡眠再继续
                if (count <= JobConfig.GenerateFirstBillsJobTryTime && !isSucess) { Thread.Sleep(JobConfig.GenerateFirstBillsJobTryTimeInterval); }
            }
            while (count <= JobConfig.GenerateFirstBillsJobTryTime && !isSucess);
            //失败请求，发送钉钉消息
            if (!isSucess) { dingApiRequest.sendDingMessageToChat("GenerateFirstBillsJob", msg); }
            return null;
        }
    }
}
