using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MadRunFabric.Common;
using Microsoft.Extensions.Logging;
using Hangfire;
using System.Text;
using System.IO;
using System.Net;
using System.Linq.Expressions;
using Api.SignToken;

namespace HangfireApi.Controllers
{
    /// <summary>
    /// 任务调度Hangfire
    /// </summary>
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class HangfireController : BaseController
    {
        private readonly ILogger<HangfireController> _logger;
        private readonly IEquipmentService _equipmentService;
        public HangfireController(
            ILogger<HangfireController> logger, IEquipmentService equipmentService
            )
        {
            _logger = logger;
            _equipmentService = equipmentService;
        }

        

        #region 四个定时基础方法
        /// <summary>
        /// 基于队列的任务处理(Fire-and-forget jobs)
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public IActionResult EnqueueAsync(string str)
        {
            var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget!"));
            return Success($"基于队列的任务处理  Enqueue :  jobId={jobId}");
        }

        /// <summary>
        /// 延迟任务执行(Delayed jobs)
        /// </summary>
        /// <returns></returns>
        public IActionResult Delayed()
        {
            var jobId = BackgroundJob.Schedule(() => Console.WriteLine("Delayed!"),
                TimeSpan.FromSeconds(10));
            return Success($"延迟任务执行  Delayed :  jobId={jobId}");
        }

        /// <summary>
        /// 定时任务执行(Recurring jobs)
        /// </summary>
        /// <returns></returns>
        public IActionResult Recurring()
        {
            RecurringJob.AddOrUpdate(() => Console.Write("定时任务执行  Recurring "), "1/1  * * * *");
            return Success($"定时任务执行  Recurring ");
        }

        /// <summary>
        /// 延续性任务执行
        /// </summary>
        /// <param name="jobId"></param>
        /// <returns></returns>
        public IActionResult Continuations(string jobId)
        {
            BackgroundJob.ContinueWith(jobId, () => Console.WriteLine("Continuation!"));
            return Success($"延续性任务执行  Continuation ");
        }
        #endregion




        /// <summary>
        /// 定时任务执行导出
        /// </summary>
        /// <returns></returns>
        public IActionResult RecurringToExport()
        {
            RecurringJob.AddOrUpdate(() => HttpGetExport(), Cron.Minutely);
            return Success($"定时任务执行导出  api/Values/Export/ ");
        }

        /// <summary>
        /// 执行导出
        /// </summary>
        private void HttpGetExport()
        {
            try
            {
                _logger.LogInformation("定时任务执行【导出】【开始】  api/Values/Export/");
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:8082/api/Values/Export?start=2017-12-08&end=2017-12-09");
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                var result = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                if (result != "定时导出Excel文件，并保存Excel文件信息到数据库中")
                    throw new Exception("导出错误");
                _logger.LogInformation("定时任务执行【导出】【结束】  api/Values/Export/");
            }
            catch (Exception e)
            {
                _logger.LogError(e, "定时任务执行【导出】【失败】  api/Values/Export/");
            }
        }
    }
}