using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Ropin.Inspection.Api.Common;
using Ropin.Inspection.Common.Accessor.Interface;
using Ropin.Inspection.Model.Common;
using Ropin.Inspection.Model.Entities;
using Ropin.Inspection.Repository.Interface;
using Ropin.Inspection.Service;
using Ropin.Inspection.Service.Interface;
using Ropin.Inspection.Tasks.QuartzNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace Ropin.Inspection.Api.Controllers
{
    /// <summary>
    /// 任务管理
    /// </summary>
    public class TasksQzController : BaseController
    {
        private readonly ILogger<TasksQzController> _logger;
        private readonly ITasksQzServices _service;
        private readonly ISchedulerCenter _schedulerCenter;
        private readonly IUnitOfWork _unitOfWork;
        private readonly IClaimsAccessor _claims;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="service"></param>
        /// <param name="schedulerCenter"></param>
        /// <param name="logger"></param>
        /// <param name="unitOfWork"></param>
        /// <param name="claims"></param>
        public TasksQzController(ITasksQzServices service, ISchedulerCenter schedulerCenter, ILogger<TasksQzController> logger, IUnitOfWork unitOfWork, IClaimsAccessor claims)
        {
            _service = service;
            _logger = logger;
            _schedulerCenter = schedulerCenter;
            _unitOfWork = unitOfWork;
            _claims = claims;
        }

        /// <summary>
        /// 获取所有的任务
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetTasksQzsAsync")]
        public async Task<ApiResult> GetTasksQzsAsync()
        {
            try
            {
                var data = await _service.GetAllAsync();
                var dataList = data.ToList();
                if (dataList.Count > 0)
                {
                    foreach (var item in dataList)
                    {
                        item.Triggers = await _schedulerCenter.GetTaskStaus(item);
                    }
                }
                return new ApiResult<IEnumerable<TasksQz>>(data);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 查询网点下所有的任务
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetTasksQzsByStoreAsync")]
        public async Task<ApiResult> GetTasksQzsByStoreAsync(string storeCode, string name)
        {
            if (string.IsNullOrEmpty(storeCode))
            {
                return new ApiResult(ReturnCode.ArgsError, "网点Code");
            }
            try
            {
                var data = await _service.GetAllAsync();
                var dataList = data.Where(i=>i.C_StoreCode == storeCode).OrderByDescending(t=>t.CreateTime).ToList();
                if (dataList.Count > 0)
                {
                    foreach (var item in dataList)
                    {
                        item.Triggers = await _schedulerCenter.GetTaskStaus(item);
                    }
                }
                if (string.IsNullOrWhiteSpace(name))
                    return new ApiResult<IEnumerable<TasksQz>>(dataList);
                else
                    return new ApiResult<IEnumerable<TasksQz>>(dataList.Where(x => x.Name.Contains(name)));
                
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 创建任务
        /// </summary>
        /// <param name="tasksQz"></param>
        /// <returns></returns>
        [Route("CreateTasksQzAsync")]
        [HttpPost]
        public async Task<ApiResult> CreateTasksQzAsync(TasksQz tasksQz)
        {
            var data = new ApiResult();
            if (tasksQz == null)
            {
                data.Code = ReturnCode.ArgsError;
                return data;
            }
            _unitOfWork.BeginTransaction();
            try
            {
                //await _service.CreateOneAsync(tasksQz);
                tasksQz.Id = Guid.NewGuid();
                tasksQz.CreateTime = DateTime.Now;
                tasksQz.CreateBy = _claims.ApiUserId;
                bool bResult =  await _unitOfWork.RegisterNew(tasksQz);
                if (bResult)
                {
                    data.Message = "添加成功";
                    if (tasksQz.IsStart)
                    {
                        //如果是启动自动
                        var ResuleModel = await _schedulerCenter.AddScheduleJobAsync(tasksQz);
                        data.Code = ReturnCode.Success;
                        if (ResuleModel.success)
                        {
                            data.Message = $"{data.Message}=>启动成功=>{ResuleModel.msg}";
                        }
                        else
                        {
                            data.Message = $"{data.Message}=>启动失败=>{ResuleModel.msg}";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            finally
            {
                if (data.Code == ReturnCode.Success)
                   await _unitOfWork.CommitAsync();
                else
                    _unitOfWork.Rollback();
            }
            return new ApiResult(ReturnCode.Success);
        }

        /// <summary>
        /// 通过ID获取计划任务信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("GetByIdAsync/{id}")]
        public async Task<ApiResult> GetByIdAsync(Guid id)
        {
            if (Guid.Empty == id)
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                var tasksQz = await _service.GetByIdAsync(id);
                return new ApiResult<TasksQz>(tasksQz);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }
        ///// <summary>
        ///// 删除任务
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //[HttpDelete("DeleteTasksQzAsync/{id}")]
        //public async Task<ApiResult> DeleteTasksQzAsync(Guid id)
        //{
        //    if (Guid.Empty == id)
        //    {
        //        return new ApiResult(ReturnCode.GeneralError);
        //    }
        //    try
        //    {
        //        await _service.DeleteAsync(id);
        //    }
        //    catch (Exception ex)
        //    {
        //        return new ApiResult(ReturnCode.GeneralError, ex.Message);
        //    }
        //    return new ApiResult(ReturnCode.Success);
        //}

        /// <summary>
        /// 修改计划任务
        /// </summary>
        /// <param name="tasksQz"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ApiResult> Put(TasksQz tasksQz)
        {
            
            var data = new ApiResult();
            if (tasksQz == null)
            {
                data.Code = ReturnCode.ArgsError;
                return data;
            }
            if (tasksQz == null || Guid.Empty == tasksQz.Id)
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            else
            {
                _unitOfWork.BeginTransaction();
                bool bResult = await _unitOfWork.RegisterDirty(tasksQz);
                try
                {
                    if (bResult)
                    {
                        data.Message = "修改成功";
                        if (tasksQz.IsStart)
                        {
                            var ResuleModelStop = await _schedulerCenter.StopScheduleJobAsync(tasksQz);
                            data.Message = $"{data.Message}=>停止:{ResuleModelStop.msg}";
                            var ResuleModelStar = await _schedulerCenter.AddScheduleJobAsync(tasksQz);
                            data.Code = ReturnCode.ProcedureSuccess;
                            data.Message = $"{data.Message}=>启动:{ResuleModelStar.msg}";
                        }
                        else
                        {
                            var ResuleModelStop = await _schedulerCenter.StopScheduleJobAsync(tasksQz);
                            data.Message = $"{data.Message}=>停止:{ResuleModelStop.msg}";
                        }
                    }
                    else
                    {
                        data.Message = "修改失败";
                    }
                }
                catch (Exception ex)
                {
                    return new ApiResult(ReturnCode.GeneralError, ex.Message);
                }
                finally
                {
                    if (data.Code == ReturnCode.ProcedureSuccess)
                        await _unitOfWork.CommitAsync();
                    else
                        _unitOfWork.Rollback();
                    data.Code = ReturnCode.Success;
                }
            }
            return data;
        }
        /// <summary>
        /// 删除一个任务
        /// </summary>
        /// <param name="jobId"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ApiResult> Delete(Guid jobId)
        {
            var data = new ApiResult();

            _unitOfWork.BeginTransaction();
            try
            {
                var model = await _service.GetByIdAsync(jobId);
                bool bResult = await _unitOfWork.RegisterDeleted(model);
                if (bResult)
                {
                    data.Message = "删除成功";
                    var ResuleModel = await _schedulerCenter.StopScheduleJobAsync(model);
                    data.Message = $"{data.Message}=>任务状态=>{ResuleModel.msg}";
                    data.Code = ReturnCode.ProcedureSuccess;
                }
                else
                {
                    data.Message = "删除失败";
                }

            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            finally
            {
                if (data.Code == ReturnCode.ProcedureSuccess)
                    await _unitOfWork.CommitAsync();
                else
                    _unitOfWork.Rollback();
                data.Code = ReturnCode.Success;
            }

            return data;

        }
        /// <summary>
        /// 启动计划任务
        /// </summary>
        /// <param name="jobId"></param>
        /// <returns></returns>
        [HttpGet("StartJob/{jobId}")]
        public async Task<ApiResult> StartJob(Guid jobId)
        {
            var data = new ApiResult();

            var model = await _service.GetByIdAsync(jobId);
            if (model != null)
            {
                _unitOfWork.BeginTransaction();
                try
                {
                    model.IsStart = true;
                    bool bResult = await _unitOfWork.RegisterDirty(model);
                    if (bResult)
                    {
                        data.Message = "更新成功";
                        var ResuleModel = await _schedulerCenter.AddScheduleJobAsync(model);
                        data.Code = ReturnCode.Success;
                        if (ResuleModel.success)
                        {
                            data.Message = $"{data.Message}=>启动成功=>{ResuleModel.msg}";

                        }
                        else
                        {
                            data.Message = $"{data.Message}=>启动失败=>{ResuleModel.msg}";
                        }
                        data.Code = ReturnCode.ProcedureSuccess;
                    }
                    else
                    {
                        data.Message = "更新失败";
                    }
                }
                catch (Exception ex)
                {
                    return new ApiResult(ReturnCode.GeneralError, ex.Message);
                }
                finally
                {
                    if (data.Code == ReturnCode.ProcedureSuccess)
                        await _unitOfWork.CommitAsync();
                    else
                        _unitOfWork.Rollback();
                    data.Code = ReturnCode.Success;
                }
            }
            else
            {
                data.Message = "任务不存在";
            }
            return data;
        }
        /// <summary>
        /// 停止一个计划任务
        /// </summary>
        /// <param name="jobId"></param>
        /// <returns></returns>        
        [HttpGet("StopJob/{jobId}")]
        public async Task<ApiResult> StopJob(Guid jobId)
        {
            var data = new ApiResult();

            try
            {
                var model = await _service.GetByIdAsync(jobId);
                if (model != null)
                {
                    model.IsStart = false;
                    bool bResult = await _unitOfWork.RegisterDirty(model);
                    if (bResult)
                    {
                        data.Message = "更新成功";
                        var ResuleModel = await _schedulerCenter.StopScheduleJobAsync(model);
                        if (ResuleModel.success)
                        {
                            data.Message = $"{data.Message}=>停止成功=>{ResuleModel.msg}";
                        }
                        else
                        {
                            data.Message = $"{data.Message}=>停止失败=>{ResuleModel.msg}";
                        }
                        data.Code = ReturnCode.ProcedureSuccess;
                    }
                    else
                    {
                        data.Message = "更新失败";
                    }
                }
                else
                {
                    data.Message = "任务不存在";
                }
            }
            catch(Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            finally
            {
                if (data.Code == ReturnCode.ProcedureSuccess)
                    await _unitOfWork.CommitAsync();
                else
                    _unitOfWork.Rollback();
                data.Code = ReturnCode.Success;
            }
            
            return data;
        }
        /// <summary>
        /// 暂停一个计划任务
        /// </summary>
        /// <param name="jobId"></param>
        /// <returns></returns>        
        [HttpGet("PauseJob/{jobId}")]
        public async Task<ApiResult> PauseJob(Guid jobId)
        {
            var data = new ApiResult();
            var model = await _service.GetByIdAsync(jobId);
            if (model != null)
            {
                _unitOfWork.BeginTransaction();
                try
                {
                    model.IsStart = false;
                    bool bResult = await _unitOfWork.RegisterDirty(model);
                    if (bResult)
                    {
                        data.Message = "更新成功";
                        var ResuleModel = await _schedulerCenter.PauseJob(model);
                        if (ResuleModel.success)
                        {
                            data.Message = $"{data.Message}=>暂停成功=>{ResuleModel.msg}";
                        }
                        else
                        {
                            data.Message = $"{data.Message}=>暂停失败=>{ResuleModel.msg}";
                        }
                        data.Code = ReturnCode.ProcedureSuccess;
                    }
                    else
                    {
                        data.Message = "更新失败";
                    }
                }
                catch (Exception ex)
                {
                    return new ApiResult(ReturnCode.GeneralError, ex.Message);
                }
                finally
                {
                    if (data.Code == ReturnCode.ProcedureSuccess)
                        await _unitOfWork.CommitAsync();
                    else
                        _unitOfWork.Rollback();
                    data.Code = ReturnCode.Success;
                }
            }
            else
            {
                data.Message = "任务不存在";
            }
            return data;
        }
        /// <summary>
        /// 恢复一个计划任务
        /// </summary>
        /// <param name="jobId"></param>
        /// <returns></returns>        
        [HttpGet("ResumeJob/{jobId}")]
        public async Task<ApiResult> ResumeJob(Guid jobId)
        {
            var data = new ApiResult();
            var model = await _service.GetByIdAsync(jobId);
            if (model != null)
            {
                _unitOfWork.BeginTransaction();
                try
                {
                    model.IsStart = true;
                    bool bResult = await _unitOfWork.RegisterDirty(model);
                    if (bResult)
                    {
                        data.Message = "更新成功";
                        var ResuleModel = await _schedulerCenter.ResumeJob(model);
                        if (ResuleModel.success)
                        {
                            data.Message = $"{data.Message}=>恢复成功=>{ResuleModel.msg}";
                        }
                        else
                        {
                            data.Message = $"{data.Message}=>恢复失败=>{ResuleModel.msg}";
                        }
                        data.Code = ReturnCode.ProcedureSuccess;
                    }
                    else
                    {
                        data.Message = "更新失败";
                    }
                }
                catch (Exception ex)
                {
                    return new ApiResult(ReturnCode.GeneralError, ex.Message);
                }
                finally
                {
                    if (data.Code == ReturnCode.ProcedureSuccess)
                        await _unitOfWork.CommitAsync();
                    else
                        _unitOfWork.Rollback();
                    data.Code = ReturnCode.Success;
                }
            }
            else
            {
                data.Message = "任务不存在";
            }
            return data;
        }
        /// <summary>
        /// 重启一个计划任务
        /// </summary>
        /// <param name="jobId"></param>
        /// <returns></returns>
        [HttpGet("ReCovery/{jobId}")]
        public async Task<ApiResult> ReCovery(Guid jobId)
        {
            var data = new ApiResult();
            var model = await _service.GetByIdAsync(jobId);
            if (model != null)
            {
                _unitOfWork.BeginTransaction();
                try
                {
                    model.IsStart = true;
                    bool bResult = await _unitOfWork.RegisterDirty(model);
                    if (bResult)
                    {
                        data.Message = "更新成功";
                        var ResuleModelStop = await _schedulerCenter.StopScheduleJobAsync(model);
                        var ResuleModelStar = await _schedulerCenter.AddScheduleJobAsync(model);
                        if (ResuleModelStar.success)
                        {
                            data.Message = $"{data.Message}=>停止:{ResuleModelStop.msg}=>启动:{ResuleModelStar.msg}";
                            
                        }
                        else
                        {
                            data.Message = $"{data.Message}=>停止:{ResuleModelStop.msg}=>启动:{ResuleModelStar.msg}";
                           
                        }
                        data.Code = ReturnCode.ProcedureSuccess;
                    }
                    else
                    {
                        data.Message = "更新失败";
                    }
                }
                catch (Exception ex)
                {
                    return new ApiResult(ReturnCode.GeneralError, ex.Message);
                }
                finally
                {
                    if (data.Code == ReturnCode.ProcedureSuccess)
                        await _unitOfWork.CommitAsync();
                    else
                        _unitOfWork.Rollback();
                    data.Code = ReturnCode.Success;
                }
            }
            else
            {
                data.Message = "任务不存在";
            }
            return data;

        }

        /// <summary>
        /// 立即执行任务
        /// </summary>
        /// <param name="jobId"></param>
        /// <returns></returns>
        [HttpGet("ExecuteJob/{jobId}")]
        public async Task<ApiResult> ExecuteJob(Guid jobId)
        {
            var data = new ApiResult();

            try
            {
                var model = await _service.GetByIdAsync(jobId);
                if (model != null)
                {
                    var ResuleModel = await _schedulerCenter.ExecuteJobAsync(model);
                    if (ResuleModel.success)
                    {
                        data.Message = $"{data.Message}=>执行成功=>{ResuleModel.msg}";
                    }
                    else
                    {
                        data.Message = $"{data.Message}=>执行失败=>{ResuleModel.msg}";
                    }
                    data.Code = ReturnCode.Success;
                }
                else
                {
                    data.Message = "任务不存在";
                }
            }
            catch(Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            finally
            {
                if (data.Code == ReturnCode.ProcedureSuccess)
                    await _unitOfWork.CommitAsync();
                else
                    _unitOfWork.Rollback();
                data.Code = ReturnCode.Success;
            }
            
            return data;
        }

    }
}