package rd.controller.score;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaMode;
import cn.hutool.core.net.URLEncodeUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;
import rd.data.code.ServiceCode;
import rd.data.model.response.Response;

import rd.service.score.ScoreService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/score")
public class ScoreController {
    private final ScoreService scoreService;

    private final ObjectMapper objectMapper;

    public ScoreController(ScoreService scoreService, ObjectMapper objectMapper) {
        this.scoreService = scoreService;
        this.objectMapper = objectMapper;
    }

    @SaCheckRole(value = {"TEACHER", "ADMIN"}, mode = SaMode.OR)
    @RequestMapping("/export")
    public void exportCourseTermScoreList(@RequestParam("course") Long course,
                                          @RequestParam("term") String term,
                                          HttpServletResponse response
    ) throws IOException {
        if (course == null) {
            Response<String> responseData = Response.error(ServiceCode.ParamWrong);
            response.setContentType("application/json");
            response.getWriter().write(objectMapper.writeValueAsString(responseData));
            return;
        }

        var data = scoreService.exportTermCourseAllStudentScoreExcel(course, term);

        if (data == null) {
            Response<String> responseData = Response.success("数据是空的");
            response.setContentType("application/json");
            response.getWriter().write(objectMapper.writeValueAsString(responseData));
            return;
        }

        response.setContentLength(data.getData().length);
        response.setContentType("application/octet-stream");

        var filename = String.format("export_score_%s_%s_%d.xlsx", data.getFileName(), term, course);
        filename = URLEncodeUtil.encodeAll(filename);

        response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", filename));

        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");

        response.getOutputStream().write(data.getData());
    }
}
