package cn.com.qmth.examcloud.tool.controller;

import cn.com.qmth.examcloud.tool.config.SysProperty;
import cn.com.qmth.examcloud.tool.entity.TaskEntity;
import cn.com.qmth.examcloud.tool.service.TaskService;
import cn.com.qmth.examcloud.tool.utils.StatusException;
import cn.com.qmth.examcloud.tool.vo.task.TaskAdd;
import cn.com.qmth.examcloud.tool.vo.task.TaskQuery;
import cn.com.qmth.examcloud.tool.vo.user.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;

@Controller
public class TaskController extends BaseController {

    @Autowired
    private TaskService taskService;

    @Autowired
    private SysProperty sysProperty;

    @ResponseBody
    @PostMapping(value = "/api/task/list")
    public Page<TaskEntity> taskList(@RequestBody TaskQuery req) {
        return taskService.getTaskList(req);
    }

    @ResponseBody
    @PostMapping(value = "/api/task/add")
    public void taskAdd(@RequestBody TaskAdd req) {
        User user = currentLoginUser();
        req.setOperatorId(user.getUserId());
        req.setOperatorName(user.getDisplayName());
        req.setUserToken(user.getToken());
        taskService.addTask(req);
    }

    @GetMapping(value = "/api/task/download/{taskId}")
    public void taskDownload(@PathVariable Long taskId, HttpServletResponse response) {
        TaskEntity task = taskService.getTaskById(taskId);
        if (task == null || StringUtils.isEmpty(task.getFilePath())) {
            throw new StatusException("任务或文件不存在！");
        }

        File file = new File(sysProperty.getDataDir() + "/" + task.getFilePath());
        super.download(response, file, file.getName());
    }

}
