package controllers

import (
	"fmt"
	"runtime"
	"time"

	"git.rosy.net.cn/jx-callback/business/jxutils"

	"git.rosy.net.cn/jx-callback/business/jxutils/tasksch"
	"github.com/astaxie/beego/server/web"
)

type TaskController struct {
	web.Controller
}

// @Title 查询长时间运行任务
// @Description 查询长时间运行任务
// @Param	token			header		string	true	"认证token"
// @Param	taskID			query		string	false	"任务ID"
// @Param	fromStatus		query		int		false	"起始状态"
// @Param	toStatus		query		int		false	"结束状态"
// @Param	lastHours		query		int		false	"多少小时以内的"
// @Param	createdBy		query		string	false	"创建人"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /GetTasks [get]
func (c *TaskController) GetTasks() {
	c.callGetTasks(func(params *tTaskGetTasksParams) (retVal interface{}, errCode string, err error) {
		if params.MapData["fromStatus"] == nil {
			params.FromStatus = tasksch.TaskStatusBegin
			if params.MapData["toStatus"] == nil {
				params.ToStatus = tasksch.TaskStatusEnd
			}
		} else if params.MapData["toStatus"] == nil {
			params.ToStatus = params.FromStatus
		}
		retVal = tasksch.GetTasks(params.TaskID, params.FromStatus, params.ToStatus, params.LastHours, params.CreatedBy)
		return retVal, "", err
	})
}

// @Title 取消长时间运行任务
// @Description 取消长时间运行任务
// @Param	token			header		string	true	"认证token"
// @Param	taskID			query		string	true	"任务ID"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /CancelTask [put]
func (c *TaskController) CancelTask() {
	c.callCancelTask(func(params *tTaskCancelTaskParams) (retVal interface{}, errCode string, err error) {
		tasks := tasksch.GetTasks(params.TaskID, tasksch.TaskStatusBegin, tasksch.TaskStatusEnd, 3*24, "")
		if len(tasks) != 1 {
			return nil, "", fmt.Errorf("taskID:%s,找不到或找到不仅一个任务", params.TaskID)
		}
		tasks[0].Cancel()
		return retVal, "", err
	})
}

// @Title 取消管理任务
// @Description 取消管理任务
// @Param	token			header		string	true	"认证token"
// @Param	taskIDs			query		string	false	"任务ID列表"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /UnmanageTasks [put]
func (c *TaskController) UnmanageTasks() {
	c.callUnmanageTasks(func(params *tTaskUnmanageTasksParams) (retVal interface{}, errCode string, err error) {
		var taskIDs []string
		if err = jxutils.Strings2Objs(params.TaskIDs, &taskIDs); err == nil {
			tasksch.UnmanageTasks(taskIDs)
			runtime.GC()
			time.Sleep(3 * time.Second)
		}
		return retVal, "", err
	})
}
