package cn.ey.biz.module.system.controller.admin.file;

import cn.ey.biz.common.pojo.PageResult;
import cn.ey.biz.common.pojo.R;
import cn.ey.biz.common.util.servlet.ServletUtils;
import cn.ey.biz.framework.operatelog.core.annotations.OperateLog;
import cn.ey.biz.module.system.controller.admin.file.vo.file.FilePageReqVO;
import cn.ey.biz.module.system.controller.admin.file.vo.file.FileRespVO;
import cn.ey.biz.module.system.convert.file.FileConvert;
import cn.ey.biz.module.system.dal.dataobject.file.FileDO;
import cn.ey.biz.module.system.dal.redis.file.FileDAO;
import cn.ey.biz.module.system.service.file.FileService;
import cn.ey.biz.module.system.service.file.FileTypeCheck;
import cn.hutool.core.io.IoUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

import static cn.ey.biz.common.pojo.R.success;

@Api(tags = "管理后台 - 文件存储")
@RestController
@RequestMapping("/infra/file")
@Validated
@Slf4j
public class FileController {

    @Resource
    private FileService fileService;
    @Resource
    private FileDAO fileDAO;

    @Value("${ey.file.suffixes:}")
    private String suffixes;

    @Value("${ey.file.types:}")
    private String types;

    @PostMapping("/upload")
    @ApiOperation("上传文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件附件", required = true, dataTypeClass = MultipartFile.class),
            @ApiImplicitParam(name = "path", value = "文件路径", example = "xxx.png", dataTypeClass = String.class),
            @ApiImplicitParam(name = "fileType", value = "文件类型", required = true, dataTypeClass = String.class),
    })
    @OperateLog(logArgs = false) // 上传文件，没有记录操作日志的必要
//    @PreAuthorize("@ss.hasPermission('infra:file:upload')")
    public R<String> uploadFile(@RequestParam("file") MultipartFile file,
                                @RequestParam(value = "path", required = false) String path,
                                @RequestParam(value = "fileType", required = false) String fileType) throws Exception {

        // 不满足后缀名的通过文件头验证
        FileTypeCheck.checkFileBySuffixes(file, suffixes.split(","));
        FileTypeCheck.checkFileByActualType(file, types.split(","));

        FileDO fileDO = fileService.createFile(file.getOriginalFilename(), path, IoUtil.readBytes(file.getInputStream()), fileType);
        return success(fileDO == null ? null : fileDO.getUrl());
    }

    @PostMapping("/batch-upload")
    @ApiOperation("上传文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "files", value = "文件附件集合", required = true, dataTypeClass = MultipartFile.class),
    })
    @OperateLog(logArgs = false) // 上传文件，没有记录操作日志的必要
//    @PreAuthorize("@ss.hasPermission('infra:file:upload')")
    public R<List<FileRespVO>> batchUploadFile(@RequestParam("files") MultipartFile[] files) throws Exception {

        for (MultipartFile file : files) {
            FileTypeCheck.checkFileBySuffixes(file, suffixes.split(","));
            FileTypeCheck.checkFileByActualType(file, types.split(","));
        }

        return R.success(FileConvert.INSTANCE.convertList(fileService.batchCreateFile(files)));
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除文件")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('infra:file:delete')")
    public R<Boolean> deleteFile(@RequestParam("id") Long id) throws Exception {
        fileService.deleteFile(id);
        return success(true);
    }

    @GetMapping("/{configId}/get/{path}")
    @ApiOperation("下载文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "configId", value = "配置编号", required = true, dataTypeClass = Long.class),
            @ApiImplicitParam(name = "path", value = "文件路径", required = true, dataTypeClass = String.class)
    })
    public void getFileContent(HttpServletResponse response,
                               @PathVariable("configId") Long configId,
                               @PathVariable("path") String path) throws Exception {

        byte[] content = fileService.getFileContent(configId, path);
        if (content == null) {
            log.warn("[getFileContent][configId({}) path({}) 文件不存在]", configId, path);
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        FileDO file = fileService.getFile(configId, path);
        String fileName = (file != null ? file.getName() : path);
        ServletUtils.writeAttachment(response, fileName, content);
    }

    @GetMapping("/temp/{configId}/get/{path}")
    @ApiOperation("下载文件(临时)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "configId", value = "配置编号", required = true, dataTypeClass = Long.class),
            @ApiImplicitParam(name = "path", value = "文件路径", required = true, dataTypeClass = String.class)
    })
    @PermitAll
    public void getTempFileContent(HttpServletResponse response,
                               @PathVariable("configId") Long configId,
                               @PathVariable("path") String path) throws Exception {
        String uri = fileDAO.get(configId, path);
        if (uri == null) {
            log.warn("[getTempFileContent][configId({}) path({}) 文件不存在]", configId, path);
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        byte[] content = fileService.getFileContent(configId, uri);
        if (content == null) {
            log.warn("[getTempFileContent][configId({}) path({}) 文件不存在]", configId, uri);
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        FileDO file = fileService.getFile(configId, uri);
        String fileName = (file != null ? file.getName() : uri);
        ServletUtils.writeAttachment(response, fileName, content);
    }

    @GetMapping("/page")
    @ApiOperation("获得文件分页")
    @PreAuthorize("@ss.hasPermission('infra:file:query')")
    public R<PageResult<FileRespVO>> getFilePage(@Valid FilePageReqVO pageVO) {
        PageResult<FileDO> pageResult = fileService.getFilePage(pageVO);
        return success(FileConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/get-file")
    @ApiOperation("获得文件")
    @PreAuthorize("@ss.hasPermission('infra:file:query')")
    public R<FileRespVO> getFile(@Valid @RequestParam("name") String name) {
        FileDO fileDO = fileService.getFile(name);
        return success(FileConvert.INSTANCE.convert(fileDO));
    }

    @GetMapping("/get-file-by-type")
    @ApiOperation("根据类型获取文件")
    @PreAuthorize("@ss.hasPermission('infra:file:query')")
    public R<List<FileRespVO>> getFileByType(@Valid @RequestParam("fileType") String fileType) {
        List<FileDO> fileDO = fileService.getFileList(fileType);
        return success(FileConvert.INSTANCE.convertList(fileDO));
    }

}
