using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MadRunFabric.Common;
using Api.SignToken;
using Microsoft.Extensions.Logging;
using MadRunFabric.Model;
using Hangfire;

namespace HangfireApi.Controllers
{
    /// <summary>
    /// 配送物品计划
    /// </summary>
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class HangfireDistributionPlanController : BaseController
    {
        private readonly ILogger<HangfireDistributionPlanController> _logger;
        private readonly IDistributionPlanService _distributionplanService;
        public HangfireDistributionPlanController(
            ILogger<HangfireDistributionPlanController> logger, 
            IDistributionPlanService distributionplanService
            )
        {
            _logger = logger;
            _distributionplanService = distributionplanService;
        }

        #region 配送计划
        /// <summary>
        /// 物品配送计划
        /// </summary>
        /// <param name="id">计划id</param>
        /// <param name="action"></param>
        /// <param name="day">周期天数</param>
        /// <param name="hour">周期小时</param>
        /// <param name="extensiontime">开始结束 时间段 List<ExtensionTimeModel></param>
        /// <returns></returns>
        [HttpPost("adddistributionplan")]
        public IActionResult AddDistriWorkOrderPlanAsync(string id, int plancycle, int planinterval, int plantimes,string extensiontime)
        {
            _logger.LogError("AddDistriWorkOrderPlanAsync start ");
            string dd = "";
            #region
            //ptype: 1每天，2每周，3每月 
            string cycle = "";
            if (plancycle == (int)EnumDistributionPlanCycle.yearly)
            {
                //每年执行
                dd = Cron.Yearly();
                cycle = "每年";
            }
            else if (plancycle == (int)EnumDistributionPlanCycle.monthly)
            {
                if (planinterval > 1)
                {//间隔>1 即为几月执行一次
                    dd = Cron.MonthInterval(planinterval);
                }
                else
                {//每月第几天执行1次
                    dd = Cron.Monthly();
                }
                cycle = "每月";
            }
            else if (plancycle == (int)EnumDistributionPlanCycle.darly)
            {
                var list_extensiontime = JsonHelper.JsonToList<ExtensionTimeModel>(extensiontime);
                _logger.LogError("配送计划 Cron start cycle:" + cycle + " express:" + dd);
                if (planinterval > 1)
                {
                    //间隔>1 即为几天执行一次
                    //dd = Cron.DayInterval(planinterval);
                    ////dd = "30 12 */{interval} * *";    //每隔几天（12：30）激发一次
                    ////dd = "0-10 11 */{interval} * *";  //每隔几天（11:00到11:10之间）激发一次

                    #region 间隔>1 即为几天执行一次
                    var model_startdate = list_extensiontime.OrderBy(x => x.startdate).FirstOrDefault();
                    string hours = model_startdate.starttime.ToString("HH");  //07:59 获取小时
                    string minutes = model_startdate.starttime.ToString("mm");  //07:59 获取分钟
                    int hour = int.Parse(hours);
                    int minute = int.Parse(minutes);
                    dd = $"{minute} {hour} */{planinterval} * *";  //每隔几天（11:00到11:10之间）激发一次
                    #endregion
                    _logger.LogError("配送计划1 Cron start cycle:" + cycle + " express:" + dd);
                }
                else
                {
                    //每天执行几次
                    ////dd = Cron.Daily();

                    ////dd = "30 14,16 * * *";  //下午02:30和下午04:30
                    ////dd = "30 6,14,16 * * *";  //上午06:30，下午02:30，下午04:30
                    ////dd = "1 11,12 * * *";  //上午06:30，下午02:30，下午04:30
                    ////dd = "0-10 11 * * *";  //上午11:00到11:10之间的每一分钟
                    ////dd = "0-59 6,14,16 * * *";  //上午06:00到06:59，下午02:00到06:59，下午04:00到06:59之间的每一分钟 ------

                    #region 拼接小时数
                    string str = "";
                    foreach (var item in list_extensiontime)
                    {
                        string hours = item.starttime.ToString("HH");  //07:59 获取小时
                        int hour = int.Parse(hours);
                        str += hour + ",";
                    }
                    str = str.TrimEnd(',');
                    _logger.LogError("配送计划2 Cron start cycle:" + cycle + " express:" + dd + " extensiontime:" + list_extensiontime.ToJson());
                    #endregion

                    //每天执行几次 - 整点激发定时任务（上午06:00，下午02:00，下午04:00 ）
                    dd = $"1 {str} * * *";
                }
                cycle = "每天";
            }
            #endregion
            _logger.LogError("配送计划 Cron start cycle:" + cycle + " express:" + dd);
            RecurringJob.AddOrUpdate(id, () => httpDistributionAsync(id), dd, TimeZoneInfo.Local);
            _logger.LogError("AddDistriWorkOrderPlanAsync end");
            return Success($"定时任务执行  Recurring ");
        }
        public async Task httpDistributionAsync(string id)
        {
            var res = await _distributionplanService.AddDistriWorkOrderPlanAsync(id);
            _logger.LogError("AddDistriWorkOrderPlanAsync res =" + res);
        }

        /// <summary>
        /// 关闭计划
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("ceshi")]
        public IActionResult GetCeshi(int planinterval,int type, List<ExtensionTimeModel> extensiontime)
        {
            string dd = "";
            if (type == 1)
            {
                dd = Cron.DayInterval(planinterval);
            }
            else if (type == 2)
            {
                dd = Cron.Daily();
            }
            else if (type == 3)
            {
                dd = "0-10 11 * * *";
            }
            else if (type == 4)
            {
                #region 拼接小时数
                string str = "";
                foreach (var item in extensiontime)
                {
                    string hours = item.starttime.ToString("HH");  //07:59 获取小时
                    str += hours + ",";
                }
                str = str.TrimEnd(',');
                #endregion
                //每天执行几次 - 整点激发定时任务（上午06:00，下午02:00，下午04:00 ）
                dd = $"* {str} * * *";
            }
            else
            {
                var model_startdate = extensiontime.OrderBy(x => x.startdate).FirstOrDefault();
                string hours = model_startdate.starttime.ToString("HH");  //07:59 获取小时
                string minutes = model_startdate.starttime.ToString("mm");  //07:59 获取分钟
                int hour = int.Parse(hours);
                int minute = int.Parse(minutes);
                dd = $"{minute} {hour} */{planinterval} * *";  //每隔几天（11:00到11:10之间）激发一次
            }
            return Success("成功", dd);
        }

        /// <summary>
        /// 关闭计划
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("remove")]
        public IActionResult removeAsync(string id)
        {
            RecurringJob.RemoveIfExists(id);
            return Success($"关闭定时任务执行  Recurring ");
        }

        /// <summary>
        /// 自动定时计划 - 自动分配
        /// </summary>
        /// <param name="id"></param>
        /// <param name="wotype"></param>
        /// <param name="plancycle"></param>
        /// <param name="planinterval"></param>
        /// <returns></returns>
        [HttpPost("saveautoassign")]
        public IActionResult SaveAutoAssignAsync(string id, int wotype, int plancycle, int planinterval)
        {
            _logger.LogError("SaveTimeOutAsync start");
            #region
            string dd = "0/3 * * * *";//每3分钟执行一次
            //string dd = "0/5 * * * *";//每5分钟执行一次
            //ptype: 超时任务周期：4小时，5分钟，6秒

            //定时任务周期：1年，2月，3周，4日，5时，6分
            //超时任务周期：5时，6分

            string cycle = "小时";
            if (plancycle == (int)EnumDistributionPlanCycle.hourly)
            {
                dd = Cron.HourInterval(planinterval);//每小时执行
                cycle = "小时";
            }
            else if (plancycle == (int)EnumDistributionPlanCycle.minutely)
            {
                dd = Cron.MinuteInterval(planinterval);
                cycle = "分钟";
            }
            #endregion
            _logger.LogError("自动定时任务 Cron start cycle:" + cycle + " express:" + dd);
            RecurringJob.AddOrUpdate(id, () => httpAutoAssignAsync(wotype), dd, TimeZoneInfo.Local);
            _logger.LogError("SaveTimeOutAsync end");
            return Success($"定时任务执行  Recurring ");
        }
        public async Task httpAutoAssignAsync(int wotype)
        {
            var res = await _distributionplanService.SaveAutoAssignAsync(wotype);
            _logger.LogError("SaveTimeOutAsync res =" + res);
        }
        #endregion



    }
}