package com.backendsys.modules.upload.controller;

import com.backendsys.modules.common.aspect.SysLog;
import com.backendsys.modules.common.utils.Result;
import com.backendsys.modules.upload.entity.MultipartUploadParams;
import com.backendsys.modules.upload.entity.SysFile;
import com.backendsys.modules.upload.service.SysFileMultipartService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
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;


@Validated
@RestController
@Tag(name = "上传文件 (分块上传)")
public class SysFileMultipartController {

    @Autowired
    private SysFileMultipartService sysFileMultipartService;

    /*
        分块上传的流程：
        1.初始化分块上传（Initiate Multipart Upload），得到 UploadId。
        2.使用 UploadId 上传分块（Upload Part）。
        3.完成分块上传（Complete Multipart Upload）。
     */

    @SysLog("初始化分块上传")
    @Operation(summary = "初始化分块上传")
    @PreAuthorize("@sr.hasPermission('1.1.3')")
    @PostMapping("/api/upload/multipartUploadInit")
//    public Result multipartUploadInit(Long category_id, Integer upload_chunk_count, String md5) {
    public Result multipartUploadInit(@Validated(MultipartUploadParams.Init.class) @RequestBody MultipartUploadParams multipartUploadParams) {
        return Result.success().put("data", sysFileMultipartService.multipartUploadInit(multipartUploadParams));
    }

    @SysLog("上传分块")
    @Operation(summary = "上传分块")
    @PreAuthorize("@sr.hasPermission('1.1.3')")
    @PostMapping("/api/upload/multipartUpload")
    public Result multipartUpload(@RequestParam("file") MultipartFile multipartFile, String upload_id, Integer upload_chunk_index) {
        return Result.success().put("data", sysFileMultipartService.multipartUpload(multipartFile, upload_id, upload_chunk_index));
    }

    @SysLog("合并分块")
    @Operation(summary = "合并分块")
    @PreAuthorize("@sr.hasPermission('1.1.3')")
    @PostMapping("/api/upload/multipartUploadComplete")
    public Result multipartUploadComplete(String upload_id, Integer is_watermark) {
        return Result.success().put("data", sysFileMultipartService.multipartUploadComplete(upload_id, is_watermark));
    }

    @Operation(summary = "查询分块上传情况")
    @PreAuthorize("@sr.hasPermission('1.1.3')")
    @GetMapping("/api/upload/getListParts")
    public Result getListParts(String upload_id, String object_key) {
        return Result.success().put("data", sysFileMultipartService.listParts(upload_id, object_key));
    }

}
