package org.dromara.wflow.service.impl;

import cn.hutool.crypto.SecureUtil;
import org.dromara.wflow.bean.vo.FileResourceVo;
import org.dromara.wflow.exception.BusinessException;
import org.dromara.wflow.minio.client.MinioService;
import org.dromara.wflow.minio.service.FileService;
import org.dromara.wflow.minio.util.FileUtil;
import org.dromara.wflow.minio.vo.UploadImageVO;
import org.dromara.wflow.service.FileManagerService;
import lombok.RequiredArgsConstructor;
import org.dromara.wflow.workflow.utils.DeptIdUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RequiredArgsConstructor
@Service
public class MinioFileManagerServiceImpl implements FileManagerService {

    @Value("${wflow.file.max-size:20}")
    private Integer maxSize;

    private final FileService fileService;

    private final MinioService minioService;



    @Override
    public FileResourceVo uploadFile(MultipartFile file, Boolean isImg, Boolean isSign) throws IOException {
        if (file.getSize() / 1048576 > maxSize){
            throw new BusinessException("管理员限制了最大文件大小为" + maxSize + "MB");
        }
        String name = file.getOriginalFilename();
        String md5 = SecureUtil.md5(file.getInputStream()).substring(8, 24);
        String type = name.substring(name.lastIndexOf("."));
        FileResourceVo.FileResourceVoBuilder fileResourceVoBuilder = FileResourceVo.builder().id(md5 + type).isImage(isImg)
                .size(file.getSize()).name(name);
        if (isImg){
            UploadImageVO uploadImageVO = fileService.uploadImage(file, true);
            fileResourceVoBuilder.url(uploadImageVO.getOriginUrl()).thumbUrl(uploadImageVO.getThumbUrl());
        }else{
            String url = fileService.uploadFile(file);
            fileResourceVoBuilder.url(url);
        }
        return fileResourceVoBuilder.build();
    }



    @Override
    public void delFileById(String fileId, Boolean isSign) {
//        boolean isImage = StringUtils.isNotBlank(fileId) && (fileId.endsWith(".jpg") || fileId.endsWith(".png"));
        boolean isImage = FileUtil.isImage(fileId);
        fileService.delFile(fileId,isImage);
    }

    @Override
    public InputStreamResource getFileById(String fileId, String name, Boolean isSign) throws IOException {
        fileService.getFileById(fileId, name, isSign);
        return null;
    }
}
