package com.template.controller;


import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.region.Region;
import com.template.api.UploadControllerAPI;
import com.template.model.result.CommonResult;
import com.template.services.SmartUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2023-03-30
 */
@RestController
public class UploadController implements UploadControllerAPI {

    @Autowired
    private SmartUploadService smartUploadService;

    @Override
    public CommonResult toCos(MultipartFile[] files) {
        String result = smartUploadService.upload(files);
        return result == null ? CommonResult.fail("上传失败") : CommonResult.ok("200","上传成功",result);
    }

    @Override
    public CommonResult deleteFile(String fileName) {
        smartUploadService.deleteByFileName(fileName);
        return CommonResult.ok("删除成功");
    }

    @Override
    public CommonResult ossSign(String suffix) {
        //1、初始化
        COSCredentials cred = new BasicCOSCredentials("AKIDCPVZdcWIxgHpy5FYxVyPiqkZGrhdXUBg","NkyCN3cz97qKaeXLvHOGxOcdS8f184pL");

        //2、设置所属地域：https://wanzai-1306339220.cos.ap-shanghai.myqcloud.com
        ClientConfig clientConfig = new ClientConfig();
        Region region = new Region("ap-shanghai");//更换为cos所属地域
        clientConfig.setRegion(region);

        //3、生成cos客户端
        COSClient cosClient = new COSClient(cred,clientConfig);
        //存储桶名称：wanzai-1306339220
        String bucketName = "wanzai-1306339220";
        //对象键（key）,使用UUID生成不重复的随机数，然后凭借文件后最组成前端上传到cos中的文件名
        //文件后缀包含带.
        String key = UUID.randomUUID() + suffix;
        //签名过期时间
        Date expirationTime = new Date(System.currentTimeMillis() + 30 * 60 * 1000);
        //生成预签名上传URL
        //示例
        URL url = cosClient.generatePresignedUrl(bucketName, key, expirationTime, HttpMethodName.PUT, new HashMap<>(), new HashMap<>());


        return CommonResult.ok("200","获取成功",url);
    }
}

