using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Api.SignToken;
using EquipmentApi.IRepositories;
using MadRunFabric.Common;
using MadRunFabric.Model.HangfireApi.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;

namespace EquipmentApi.Controllers
{
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class HangfirePlanController : BaseController
    {
        private readonly ILogger<HangfirePlanController> _logger;
        private readonly IHangfire_PlanRepository _hangfire_planrepository;
        private readonly IHangfireService _hangfireService;
        public HangfirePlanController(ILogger<HangfirePlanController> logger, 
            IHangfire_PlanRepository hangfire_planrepository, IHangfireService hangfireService)
        {
            _logger = logger;
            _hangfire_planrepository = hangfire_planrepository;
            _hangfireService = hangfireService;
        }

        [HttpPost("addtimeout")]
        public async Task<IActionResult> AddTimeOutAsync(int wotype, int plancycle, int planinterval)
        {
            var model = new HangfirePlan();
            model.id = ObjectId.GenerateNewId().ToString();
            model.wotype = wotype;
            model.plantype = (int)EnumPlanType.timeout;
            model.plancycle = plancycle;
            model.planinterval = planinterval;
            model.planstate = (int)EnumPlanState.start;//默认计划开启
            model.createby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            model.createtime = DateTime.Now;
            model.isdelete = 0;
            bool b = await _hangfire_planrepository.Add(model);
            if (b)
            {
                SetTask(model.id, model.wotype, model.plancycle, model.planinterval);
                return Success("添加成功");
            }
            return Error("添加失败");
        }

        #region 设置定时任务
        private void SetTask(string id,int wotype, int plancycle, int planinterval)
        {
            _hangfireService.SaveTimeOutRunning(id, wotype, plancycle, planinterval);
        }
        #endregion
    }
}