using Furion;
using Furion.DependencyInjection;
using Furion.FriendlyException;
using Furion.RemoteRequest.Extensions;
using Furion.TaskScheduler;
using Nirvana.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Waste.Domain;

namespace Waste.Application
{
    /// <summary>
    /// 定时任务
    /// </summary>
    public class JobWorkder : ISpareTimeWorker
    {
        /// <summary>
        /// 每隔 5s 执行
        /// </summary>
        /// <param name="timer"></param>
        /// <param name="count"></param>
        [SpareTime(5000, "推送测量结果", StartNow = true, ExecuteType = SpareTimeExecuteTypes.Serial)]
        public void DoSomethingAsync(SpareTimer timer, long count)
        {
            bool IsTask = App.Configuration["IsTask"].ToBool();
            if (!IsTask)
            {
                return;
            }
            Scoped.Create(async (_, scope) =>
            {
                var services = scope.ServiceProvider;
                var _businessapiService = App.GetService<IBusinessApiService>(services);
                var _loggerServicec = App.GetService<ILoggerService>(services);
                //判断是否有异常
                if (timer.Exception.Any())
                {
                    _loggerServicec.AddLogger($"{count}定时任务发生异常,{timer.Exception.Values.LastOrDefault()?.Message}", 1);
                    //执行第三次抛异常
                    if (count > 2)
                    {
                        throw Oops.Oh($"{count}定时任务发生异常");
                    }

                }
                else
                {
                    var list = await _businessapiService.GetPushListAsync();
                    if (list.Count > 0)
                    {
                        foreach (W_BusinessPush x in list)
                        {
                            //发送请求
                            var param = new BusinessApiS2CDto
                            {
                                devcode = x.DevCode,
                                devname = x.DevName,
                                address = x.Address.ToStr(),
                                weight = x.Weight,
                                tare = x.Tare,
                                pweight = x.PWeight,
                                type = x.Type,
                                time = x.Time.GetTimeStamp()
                            };
                            var response = await x.PushUrl
                              .SetBody(param)
                              .SetContentType("application/json")
                              .SetContentEncoding(Encoding.UTF8)
                              .PostAsync();
                            if (response.IsSuccessStatusCode)
                            {
                                var returninfo = await response.Content.ReadAsStringAsync();
                                if (returninfo.ToLower() == "success")
                                {
                                    _loggerServicec.AddLogger($"{count}第三方发送成功,参数:{param.ToJson()}\r\n返回值:{returninfo}", 3);
                                }
                                else
                                {
                                    if (x.Cnt < 2)
                                    {
                                        x.Cnt = x.Cnt + 1;
                                        await _businessapiService.InsertPushInfoAsync(x);
                                    }
                                    _loggerServicec.AddLogger($"{count}第三方响应失败,参数:{param.ToJson()}\r\n返回值:{returninfo}", 3);
                                }
                            }
                            else
                            {
                                var returninfo = await response.Content.ReadAsStringAsync();
                                _loggerServicec.AddLogger($"{count}第三方发送失败,参数:{param.ToJson()}\r\n返回值:{returninfo}", 3);
                            }
                        }
                    }
                }
            });
        }
    }
}
