package com.bonus.obs.service.impl;

import com.alibaba.nacos.common.utils.UuidUtils;
import com.bonus.common.core.domain.R;
import com.bonus.common.core.utils.file.FileUtils;
import com.bonus.obs.domain.ObsInfo;
import com.bonus.obs.service.ObsService;
import com.bonus.obs.utils.ObsUtils;
import com.obs.services.model.DeleteObjectResult;
import com.obs.services.model.ObsObject;
import com.obs.services.model.PutObjectResult;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ObsServiceImpl implements ObsService {
    @Resource
    private ObsUtils obsUtils;

    /**
     * 文件上传
     *
     * @param file 文件流
     * @return 文件信息
     */
    @Override
    public R<ObsInfo> uploadFile(MultipartFile file) {
        try {
            String originalFilename = Objects.requireNonNull(file.getOriginalFilename(), "文件名不能为空");
            String extension = originalFilename.substring(originalFilename.lastIndexOf('.'));
            String objectKey = UuidUtils.generateUuid() + extension;
            objectKey = FileUtils.generateObjectName(objectKey);
            ObsInfo obsInfo = obsUtils.uploadFile(objectKey, FileUtils.multipartFileToFile(file));
            return R.ok(obsInfo);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 删除文件从OBS
     *
     * @param objectKey 文件在OBS中的键
     */
    @Override
    public R<DeleteObjectResult> deleteFile(String objectKey) {
        return obsUtils.deleteFile(objectKey);
    }

    /**
     * 下载文件从OBS
     *
     * @param objectKey 文件在OBS中的键
     */
    @Override
    public R<ObsObject> downloadFile(String objectKey) {
        return obsUtils.downloadFile(objectKey);
    }

    /**
     * 文件上传
     *
     * @param files 文件流
     * @return 文件信息
     */
    @Override
    public R<List<ObsInfo>> uploadFiles(MultipartFile[] files) {
        try {
            List<ObsInfo> obsInfos = new ArrayList<>();
            for (MultipartFile multipartFile : files) {
                String originalFilename = Objects.requireNonNull(multipartFile.getOriginalFilename(), "文件名不能为空");
                String extension = originalFilename.substring(originalFilename.lastIndexOf('.'));
                String objectKey = UuidUtils.generateUuid() + extension;
                objectKey = FileUtils.generateObjectName(objectKey);
                obsInfos.add(obsUtils.uploadFile(objectKey, FileUtils.multipartFileToFile(multipartFile)));
            }
            return R.ok(obsInfos, "文件上传成功");
        } catch (Exception e) {
            return R.fail("File upload failed.");
        }
    }
}
