package com.koobietech.eas.controller;

import com.koobietech.eas.common.result.JsonResult;
import com.koobietech.eas.common.utils.SecurityManager;
import com.koobietech.eas.mbg.model.EasArcArchives;
import com.koobietech.eas.service.EasArcArchivesService;
import com.koobietech.eas.service.EasArchiveFileDownloadService;
import com.koobietech.eas.service.EasArchivesFilesService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author lc
 */
@Tag(name = "下载文件模块")
@RestController
@RequestMapping("/archive")
public class EasArcTlsFileDownloadController {

    @Resource
    EasArchiveFileDownloadService easArchiveFileDownloadService;

    @Resource
    EasArcArchivesService easArcArchivesService;

    @Resource
    EasArchivesFilesService easArchivesFilesService;;


    @GetMapping("/refreshArchive")
    @Operation(summary = "刷新档案", description = "刷新档案")
    public JsonResult refreshArchive(@RequestParam(required = false) String studentNumber) {

        if ( SecurityManager.isStudentUser() ) {
            easArchivesFilesService.refreshProfile(SecurityManager.getStudentNumber());
            return JsonResult.ok();
        }

        easArchivesFilesService.refreshProfile(studentNumber);

        return JsonResult.ok();
    }

    @GetMapping("/getTokenByArchiveNumber")
    @Operation(summary = "获取下载token", description = "前端传入archiveId，后端返回下载token")
    public JsonResult getFile(@RequestParam String archiveNumber) {

        if ( SecurityManager.isStudentUser() ) {
            if ( ! easArchiveFileDownloadService.
                    validateArchiveNumberByUser(archiveNumber,  SecurityManager.getStudentNumber() ) ) {
                return JsonResult.fail("非法访问");
            }
        }

        String archiveToken = easArchiveFileDownloadService.getArchiveToken(archiveNumber);

        return JsonResult.data(archiveToken);
    }

    @GetMapping("/getFileByToken")
    @Operation(summary = "获取文件流", description = "前端把token传入请求头，后端返回文件流")
    public void getFileByToken(@RequestParam String archiveToken, HttpServletResponse response) {

        //加if判断，如果返回的是false，说明token已经过期，返回null
        easArchiveFileDownloadService.downloadFileByToken(archiveToken, response);
    }

    @PostMapping("/getArchives")
    @Operation(summary = "获取档案", description = "获取档案")
    public JsonResult getArchives(@RequestBody EasArcArchives easArcArchives){
        if ( SecurityManager.isStudentUser() ) {
            easArcArchives.setStudentNumber(SecurityManager.getStudentNumber() );
        }
        List<EasArcArchives> res = easArcArchivesService.getArchives(easArcArchives);
        return JsonResult.data(res);
    }


}
