using System.Reflection;
using Tiobon.Core.Tasks;
using Quartz;

namespace Tiobon.Core.Controllers;

[Route("api/[controller]/[action]")]
[ApiController]
[Authorize(Permissions.Name), ApiExplorerSettings(GroupName = Grouping.GroupName_System)]
public class TasksQzController : ControllerBase
{
    private readonly ITasksQzServices _tasksQzServices;
    private readonly ITasksLogServices _tasksLogServices;
    private readonly ISchedulerCenter _schedulerCenter;
    private readonly IUnitOfWorkManage _unitOfWorkManage;

    public TasksQzController(ITasksQzServices tasksQzServices, ISchedulerCenter schedulerCenter, IUnitOfWorkManage unitOfWorkManage, ITasksLogServices tasksLogServices)
    {
        _unitOfWorkManage = unitOfWorkManage;
        _tasksQzServices = tasksQzServices;
        _schedulerCenter = schedulerCenter;
        _tasksLogServices = tasksLogServices;
    }

    /// <summary>
    /// 分页获取
    /// </summary>
    /// <param name="page"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    // GET: api/Buttons/5
    [HttpGet]
    public async Task<ServiceResult<PageModel<Ghre_TasksQz>>> Get(int page = 1, string key = "")
    {
        if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
        {
            key = "";
        }
        int intPageSize = 50;

        Expression<Func<Ghre_TasksQz, bool>> whereExpression = a => a.IsEnable == 1 && (a.Name != null && a.Name.Contains(key));

        var data = await _tasksQzServices.QueryPage(whereExpression, page, intPageSize, " Id desc ");
        if (data.dataCount > 0)
        {
            foreach (var item in data.data)
            {
                item.Triggers = await _schedulerCenter.GetTaskStaus(item);
            }
        }
        return ServiceResult<PageModel<Ghre_TasksQz>>.OprateSuccess(data.dataCount >= 0, "获取成功", data);
    }

    /// <summary>
    /// 添加计划任务
    /// </summary>
    /// <param name="tasksQz"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<ServiceResult<string>> Post([FromBody] Ghre_TasksQz tasksQz)
    {
        var data = new ServiceResult<string>();
        _unitOfWorkManage.BeginTran();
        var id = (await _tasksQzServices.Add(tasksQz));
        data.Success = id > 0;
        try
        {
            if (data.Success)
            {
                tasksQz.Id = id;
                data.Data = id.ObjToString();
                data.Message = "添加成功";
                if (tasksQz.IsStart)
                {
                    //如果是启动自动
                    var ResuleModel = await _schedulerCenter.AddScheduleJobAsync(tasksQz);
                    data.Success = ResuleModel.Success;
                    if (ResuleModel.Success)
                    {
                        data.Message = $"{data.Message}=>启动成功=>{ResuleModel.Message}";
                    }
                    else
                    {
                        data.Message = $"{data.Message}=>启动失败=>{ResuleModel.Message}";
                    }
                }
            }
            else
            {
                data.Message = "添加失败";

            }
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            if (data.Success)
                _unitOfWorkManage.CommitTran();
            else
                _unitOfWorkManage.RollbackTran();
        }
        return data;
    }


    /// <summary>
    /// 修改计划任务
    /// </summary>
    /// <param name="tasksQz"></param>
    /// <returns></returns>
    [HttpPut]
    public async Task<ServiceResult<string>> Put([FromBody] Ghre_TasksQz tasksQz)
    {
        var data = new ServiceResult<string>();
        if (tasksQz != null && tasksQz.Id > 0)
        {
            _unitOfWorkManage.BeginTran();
            data.Success = await _tasksQzServices.Update(tasksQz);
            try
            {
                if (data.Success)
                {
                    data.Message = "修改成功";
                    data.Data = tasksQz?.Id.ObjToString();
                    if (tasksQz.IsStart)
                    {
                        var ResuleModelStop = await _schedulerCenter.StopScheduleJobAsync(tasksQz);
                        data.Message = $"{data.Message}=>停止:{ResuleModelStop.Message}";
                        var ResuleModelStar = await _schedulerCenter.AddScheduleJobAsync(tasksQz);
                        data.Success = ResuleModelStar.Success;
                        data.Message = $"{data.Message}=>启动:{ResuleModelStar.Message}";
                    }
                    else
                    {
                        var ResuleModelStop = await _schedulerCenter.StopScheduleJobAsync(tasksQz);
                        data.Message = $"{data.Message}=>停止:{ResuleModelStop.Message}";
                    }
                }
                else
                {
                    data.Message = "修改失败";
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (data.Success)
                    _unitOfWorkManage.CommitTran();
                else
                    _unitOfWorkManage.RollbackTran();
            }
        }
        return data;
    }
    /// <summary>
    /// 删除一个任务
    /// </summary>
    /// <param name="jobId"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<ServiceResult<string>> Delete(long jobId)
    {
        var data = new ServiceResult<string>();

        var model = await _tasksQzServices.QueryById(jobId);
        if (model != null)
        {
            _unitOfWorkManage.BeginTran();
            data.Success = await _tasksQzServices.Delete(model);
            try
            {
                data.Data = jobId.ObjToString();
                if (data.Success)
                {
                    data.Message = "删除成功";
                    var ResuleModel = await _schedulerCenter.StopScheduleJobAsync(model);
                    data.Message = $"{data.Message}=>任务状态=>{ResuleModel.Message}";
                }
                else
                {
                    data.Message = "删除失败";
                }

            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (data.Success)
                    _unitOfWorkManage.CommitTran();
                else
                    _unitOfWorkManage.RollbackTran();
            }
        }
        else
        {
            data.Message = "任务不存在";
        }
        return data;

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

        var model = await _tasksQzServices.QueryById(jobId);
        if (model != null)
        {
            _unitOfWorkManage.BeginTran();
            try
            {
                model.IsStart = true;
                data.Success = await _tasksQzServices.Update(model);
                data.Data = jobId.ObjToString();
                if (data.Success)
                {
                    data.Message = "更新成功";
                    var ResuleModel = await _schedulerCenter.AddScheduleJobAsync(model);
                    data.Success = ResuleModel.Success;
                    if (ResuleModel.Success)
                    {
                        data.Message = $"{data.Message}=>启动成功=>{ResuleModel.Message}";

                    }
                    else
                    {
                        data.Message = $"{data.Message}=>启动失败=>{ResuleModel.Message}";
                    }
                }
                else
                {
                    data.Message = "更新失败";
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (data.Success)
                    _unitOfWorkManage.CommitTran();
                else
                    _unitOfWorkManage.RollbackTran();
            }
        }
        else
        {
            data.Message = "任务不存在";
        }
        return data;
    }
    /// <summary>
    /// 停止一个计划任务
    /// </summary>
    /// <param name="jobId"></param>
    /// <returns></returns>        
    [HttpGet]
    public async Task<ServiceResult<string>> StopJob(long jobId)
    {
        var data = new ServiceResult<string>();

        var model = await _tasksQzServices.QueryById(jobId);
        if (model != null)
        {
            model.IsStart = false;
            data.Success = await _tasksQzServices.Update(model);
            data.Data = jobId.ObjToString();
            if (data.Success)
            {
                data.Message = "更新成功";
                var ResuleModel = await _schedulerCenter.StopScheduleJobAsync(model);
                if (ResuleModel.Success)
                {
                    data.Message = $"{data.Message}=>停止成功=>{ResuleModel.Message}";
                }
                else
                {
                    data.Message = $"{data.Message}=>停止失败=>{ResuleModel.Message}";
                }
            }
            else
            {
                data.Message = "更新失败";
            }
        }
        else
        {
            data.Message = "任务不存在";
        }
        return data;
    }
    /// <summary>
    /// 暂停一个计划任务
    /// </summary>
    /// <param name="jobId"></param>
    /// <returns></returns>        
    [HttpGet]
    public async Task<ServiceResult<string>> PauseJob(long jobId)
    {
        var data = new ServiceResult<string>();
        var model = await _tasksQzServices.QueryById(jobId);
        if (model != null)
        {
            _unitOfWorkManage.BeginTran();
            try
            {
                data.Success = await _tasksQzServices.Update(model);
                data.Data = jobId.ObjToString();
                if (data.Success)
                {
                    data.Message = "更新成功";
                    var ResuleModel = await _schedulerCenter.PauseJob(model);
                    if (ResuleModel.Success)
                    {
                        data.Message = $"{data.Message}=>暂停成功=>{ResuleModel.Message}";
                    }
                    else
                    {
                        data.Message = $"{data.Message}=>暂停失败=>{ResuleModel.Message}";
                    }
                    data.Success = ResuleModel.Success;
                }
                else
                {
                    data.Message = "更新失败";
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (data.Success)
                    _unitOfWorkManage.CommitTran();
                else
                    _unitOfWorkManage.RollbackTran();
            }
        }
        else
        {
            data.Message = "任务不存在";
        }
        return data;
    }
    /// <summary>
    /// 恢复一个计划任务
    /// </summary>
    /// <param name="jobId"></param>
    /// <returns></returns>        
    [HttpGet]
    public async Task<ServiceResult<string>> ResumeJob(long jobId)
    {
        var data = new ServiceResult<string>();

        var model = await _tasksQzServices.QueryById(jobId);
        if (model != null)
        {
            _unitOfWorkManage.BeginTran();
            try
            {
                model.IsStart = true;
                data.Success = await _tasksQzServices.Update(model);
                data.Data = jobId.ObjToString();
                if (data.Success)
                {
                    data.Message = "更新成功";
                    var ResuleModel = await _schedulerCenter.ResumeJob(model);
                    if (ResuleModel.Success)
                    {
                        data.Message = $"{data.Message}=>恢复成功=>{ResuleModel.Message}";
                    }
                    else
                    {
                        data.Message = $"{data.Message}=>恢复失败=>{ResuleModel.Message}";
                    }
                    data.Success = ResuleModel.Success;
                }
                else
                {
                    data.Message = "更新失败";
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (data.Success)
                    _unitOfWorkManage.CommitTran();
                else
                    _unitOfWorkManage.RollbackTran();
            }
        }
        else
        {
            data.Message = "任务不存在";
        }
        return data;
    }
    /// <summary>
    /// 重启一个计划任务
    /// </summary>
    /// <param name="jobId"></param>
    /// <returns></returns>
    [HttpGet]
    public async Task<ServiceResult<string>> ReCovery(long jobId)
    {
        var data = new ServiceResult<string>();
        var model = await _tasksQzServices.QueryById(jobId);
        if (model != null)
        {

            _unitOfWorkManage.BeginTran();
            try
            {
                model.IsStart = true;
                data.Success = await _tasksQzServices.Update(model);
                data.Data = jobId.ObjToString();
                if (data.Success)
                {
                    data.Message = "更新成功";
                    var ResuleModelStop = await _schedulerCenter.StopScheduleJobAsync(model);
                    var ResuleModelStar = await _schedulerCenter.AddScheduleJobAsync(model);
                    if (ResuleModelStar.Success)
                    {
                        data.Message = $"{data.Message}=>停止:{ResuleModelStop.Message}=>启动:{ResuleModelStar.Message}";
                        data.Data = jobId.ObjToString();

                    }
                    else
                    {
                        data.Message = $"{data.Message}=>停止:{ResuleModelStop.Message}=>启动:{ResuleModelStar.Message}";
                        data.Data = jobId.ObjToString();
                    }
                    data.Success = ResuleModelStar.Success;
                }
                else
                {
                    data.Message = "更新失败";
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (data.Success)
                    _unitOfWorkManage.CommitTran();
                else
                    _unitOfWorkManage.RollbackTran();
            }
        }
        else
        {
            data.Message = "任务不存在";
        }
        return data;

    }
    /// <summary>
    /// 获取任务命名空间
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public ServiceResult<List<QuartzReflectionViewModel>> GetTaskNameSpace()
    {
        var baseType = typeof(IJob);
        var path = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
        var referencedAssemblies = System.IO.Directory.GetFiles(path, "Tiobon.Core.Tasks.dll").Select(Assembly.LoadFrom).ToArray();
        var types = referencedAssemblies
            .SelectMany(a => a.DefinedTypes)
            .Select(type => type.AsType())
            .Where(x => x != baseType && baseType.IsAssignableFrom(x)).ToArray();
        var implementTypes = types.Where(x => x.IsClass).Select(item => new QuartzReflectionViewModel { nameSpace = item.Namespace, nameClass = item.Name, remark = "" }).ToList();
        return ServiceResult<List<QuartzReflectionViewModel>>.OprateSuccess("获取成功", implementTypes);
    }

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

        var model = await _tasksQzServices.QueryById(jobId);
        if (model != null)
        {
            return await _schedulerCenter.ExecuteJobAsync(model);
        }
        else
        {
            data.Message = "任务不存在";
        }
        return data;
    }
    /// <summary>
    /// 获取任务运行日志
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public async Task<ServiceResult<PageModel<Ghre_TasksLog>>> GetTaskLogs(long jobId, int page = 1, int pageSize = 10, DateTime? runTimeStart = null, DateTime? runTimeEnd = null)
    {
        var model = await _tasksLogServices.GetTaskLogs(jobId, page, pageSize, runTimeStart, runTimeEnd);
        return ServiceResult<PageModel<Ghre_TasksLog>>.OprateSuccess(model.dataCount >= 0, "获取成功", model);
    }
    /// <summary>
    /// 任务概况
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public async Task<ServiceResult<object>> GetTaskOverview(long jobId, int page = 1, int pageSize = 10, DateTime? runTimeStart = null, DateTime? runTimeEnd = null, string type = "month")
    {
        var model = await _tasksLogServices.GetTaskOverview(jobId, runTimeStart, runTimeEnd, type);
        return ServiceResult<object>.OprateSuccess(true, "获取成功", model);
    }

}
