package com.mcwl.web.controller.communityCenter;

import com.mcwl.common.core.domain.R;
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.DownloadFileRequest;
import com.obs.services.model.DownloadFileResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author DaiZibo
 * @date 2025/3/8
 * @apiNote
 */

@RequestMapping("/downFile")
@RestController
public class DownloadFile {

    @Autowired
    private ObsClient obsClient;

    @Value("${huawei.obs.bucketName}")
    private String bucketName;

    @GetMapping("/down")
    public R down(@RequestParam String objectKey, String path) {

        try {
            DownloadFileRequest request = new DownloadFileRequest(bucketName, objectKey);
            // 设置下载对象的本地文件路径
            request.setDownloadFile(path);
            // 设置分段下载时的最大并发数
            request.setTaskNum(10);
            // 设置分段大小为10MB
            request.setPartSize(10 * 1024 * 1024);
            // 开启断点续传模式
            request.setEnableCheckpoint(true);
            // 进行断点续传下载
            DownloadFileResult result = obsClient.downloadFile(request);
            System.out.println("downloadFile successfully");
            System.out.println("Etag:" + result.getObjectMetadata().getEtag());
        } catch (ObsException e) {
            System.out.println("downloadFile failed");
            // 请求失败,打印http状态码
            System.out.println("HTTP Code:" + e.getResponseCode());
            // 请求失败,打印服务端错误码
            System.out.println("Error Code:" + e.getErrorCode());
            // 请求失败,打印详细错误信息
            System.out.println("Error Message:" + e.getErrorMessage());
            // 请求失败,打印请求id
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("downloadFile failed");
            // 其他异常信息打印
            e.printStackTrace();
        }
        return R.ok();
    }
}
