using System;
using SystemData = System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Hangfire;
using System.Text;
using System.IO;
using System.Net;
using System.Linq.Expressions;
using System.Common;
using System.IRepositories;
using System.Model;
using TVShoppingCallCenter_ZLJ.Models.Inputs;
using Utility;
using SqlSugar;
using TVShoppingCallCenter_ZLJ.Controllers.Order;
using Microsoft.Extensions.Configuration;
using System.Repositories;
using TVShoppingCallCenter_ZLJ.Controllers.CallCenter;
using Microsoft.EntityFrameworkCore.Metadata.Internal;

namespace TVShoppingCallCenter_ZLJ.Controllers.hangfire
{
    /// <summary>
    /// 任务调度Hangfire
    /// </summary>
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class HangfireController : BaseController
    {
        private readonly OrderFunctionController busOrderFunctionController;
        
        private readonly CallFunctionController busCallFunctionController;
        private readonly GradeController busGradeController;
        private readonly TeamGradeController busTeamGradeController;

        private readonly ILogger<HangfireController> _logger;
        private readonly IBus_OrderDetailRepository bus_OrderDetailRepository;
        private readonly IBus_OrderRepository bus_OrderRepository;
        private readonly IBus_ProductRepository bus_productRepository;
        private readonly ICus_VipInfoRepository cus_vip_infoRepository;
        private readonly IBus_StockLogRepository bus_StockLogRepository;
        private readonly IConfiguration config;



        public HangfireController(TeamGradeController _busTeamGradeController,GradeController _busGradeController, CallFunctionController _busCallFunctionController, ILogger<HangfireController> logger, IBus_StockLogRepository _bus_StockLogRepository, IBus_OrderRepository _bus_OrderRepository, IBus_OrderDetailRepository _bus_OrderDetailRepository, OrderFunctionController _OrderFunctionController, IBus_ProductRepository _productRepository, ICus_VipInfoRepository _cus_vip_infoRepository, IConfiguration _configuration)
        {
            busTeamGradeController = _busTeamGradeController;
            busGradeController = _busGradeController;
            busCallFunctionController = _busCallFunctionController;

            _logger = logger;
            bus_OrderDetailRepository = _bus_OrderDetailRepository;
            bus_OrderRepository = _bus_OrderRepository;
            busOrderFunctionController = _OrderFunctionController;
            bus_productRepository = _productRepository;
            cus_vip_infoRepository = _cus_vip_infoRepository;
            bus_StockLogRepository = _bus_StockLogRepository;
            config = _configuration;
        }



        #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()
        {
            //_logger.LogError("定时任务执行  Recurring ");
            RecurringJob.AddOrUpdate(() => Console.Write("定时任务执行  Recurring "), "1/1  * * * *");
            return Success($"定时任务执行  Recurring ");
        }

        /// <summary>
        /// 延续性任务执行
        /// </summary>
        /// <param name="jobId"></param>
        /// <returns></returns>
        [Obsolete]
        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/");
            }
        }

        #region 日循环  
        /// <summary>
        /// 创建生日订单 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [NonAction]
        public async Task<IActionResult> DailyRecurring()
        {
            string str = "";
            //创建生日订单
            str = await busOrderFunctionController.AddBirthDayOrder();
            return Success(str);           
        }
        #endregion


        #region 分循环 
        /// <summary>
        /// 同步通话记录
        /// </summary>
        /// <returns></returns>
        [NonAction]
        public async Task<IActionResult> MinutelyRecurring()
        {
            string str = "";
            //同步通话记录
            str = await busCallFunctionController.SyncCallRecord();
            return Success(str);
        }
        #endregion

        /// <summary>
        /// 同步自动外呼通话记录
        /// </summary>
        /// <returns></returns>
        [NonAction]
        public async Task<IActionResult> MinutelyOutbound()
        {
            string str = "";
            //同步通话记录
            str = await busCallFunctionController.SyncOutbound();
            return Success(str);
        }
        /// <summary>
        /// 同步自动外呼通话记录
        /// </summary>
        /// <returns></returns>
        [NonAction]
        public async Task<IActionResult> AutodialOutbound()
        {
            string str = "";
            //同步通话记录
            str = await busCallFunctionController.SyncAutodial();
            return Success(str);
        }
        
        #region 月12循环 

        /// <summary>
        /// 月度循环任务每月12日执行
        /// </summary>
        /// <returns></returns>
        [NonAction]
        public async Task<IActionResult> Month12Recurring()
        {
            string str = "";
            //同步绩效统计 报表统计
            str +="员工绩效汇总："+ await busGradeController.UpdateGrade("", "", 0, 0, 0);
            str += "部门团队绩效汇总：" + await busTeamGradeController.UpdateTeamGrade("", 0, 0, 0);
            return Success(str);
        }



        #endregion
    }
}