package com.lutao.cloud.collect.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.lutao.cloud.common.core.util.MessageInfo;
import com.lutao.cloud.common.core.util.UUIDUtil;
import com.lutao.cloud.common.oss.OssProperties;
import com.lutao.cloud.common.oss.service.OssTemplate;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.bind.DatatypeConverter;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

@Service
@AllArgsConstructor
@Slf4j
public class StorageService {

    private final OssProperties ossProperties;

    private final OssTemplate minioTemplate;

    @SneakyThrows
    public MessageInfo uploadImage(MultipartFile file) {
        log.info("[通过MultipartFile对象保存文件方法(uploadByMultipartFile)][params:MultipartFile={}]", file);
        /*
         * 方法所需数据声明
         */
        // 校验
        if (StrUtil.isBlank(ossProperties.getEndpoint())) {
            return MessageInfo.failed("访问地址配置错误！");
        }
        String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
        Map<String, String> resultMap = new HashMap<>(4);
        resultMap.put("bucketName", ossProperties.getBucketName());
        resultMap.put("fileName", file.getOriginalFilename());
        DecimalFormat df = new DecimalFormat("#0");
        String fileSize = df.format(file.getSize() / 1024);
        resultMap.put("fileSize", fileSize);
        resultMap.put("type",FileUtil.extName(file.getOriginalFilename()));
        resultMap.put("url", String.format("/file/sys-file/%s/%s", ossProperties.getBucketName(), fileName));
        resultMap.put("fileRealName", fileName);

        try {
            minioTemplate.putObject(ossProperties.getBucketName(), fileName, file.getInputStream());
            // 文件管理数据记录,收集管理追踪文件
        }
        catch (Exception e) {
            log.error("上传失败", e);
            return MessageInfo.failed(e.getLocalizedMessage());
        }
        return MessageInfo.ok(resultMap);
    }


    public String uploadFileBase64(String base64Data) {

        log.info("[通过base64Data保存文件方法(uploadFileBase64)]");
        /**
         * 方法所需数据声明
         */
        // 校验
        if (StrUtil.isBlank(ossProperties.getEndpoint())) {
            throw new RuntimeException("存储服务配置错误");
        }
        String filePrefix = base64Data.split(",")[0]; //获取图片前缀
        String type = filePrefix.split("/")[1]; //获取图片格式
        String fileName = UUIDUtil.get24UUID() + "." + type;
        String url = String.format("/file/sys-file/%s/%s", ossProperties.getBucketName(), fileName);
        log.info("fileName:{} type:{}", fileName , type);

        // 转字节数组
        byte[] bytes = DatatypeConverter.parseBase64Binary(base64Data.split(",")[1]);
        InputStream inputStream = new ByteArrayInputStream(bytes);

        // 上传
        long startTime = System.currentTimeMillis();
        try {
            minioTemplate.putObject(ossProperties.getBucketName(), fileName, inputStream);
            // 文件管理数据记录,收集管理追踪文件
        } catch (Exception e) {
            log.error("上传失败", e);
            throw new RuntimeException("上传失败" + e.getMessage());
        }
        long endTime = System.currentTimeMillis();
        log.info("上传文件 url:{} 耗时:{}",url,endTime - startTime);
        return url;
    }
}
