package com.ruoyi.file.object;

import cn.hutool.core.io.FileUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.PathUtils;
import com.ruoyi.common.utils.uuid.Seq;
import lombok.Data;
import lombok.experimental.Accessors;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

@Data
@Accessors(chain = true)
public final class UploadTask
{
    private MultipartFile file;
    private String diskPath;
    private String    thumbnailFolderName;
    private String    directory = "upload";
    public final Date time      = new Date();

    public long UploadSize()
    {
        return file.getSize();
    }

    public String OriginFileName()
    {
        return file.getOriginalFilename();
    }

    public String OriginFileExtension()
    {
        return FileUtil.getSuffix(file.getOriginalFilename());
    }

    public byte[] UploadBytes()
    {
        try
        {
            return file.getBytes();
        }
        catch(Exception e)
        {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public UploadResult GenerateResult()
    {
        UploadResult res = new UploadResult();

        String originalFilename = file.getOriginalFilename();
        String extension = FileUtil.getSuffix(originalFilename);

        String newBaseName = StringUtils.format("{}_{}",
                FilenameUtils.getBaseName(originalFilename),
                Seq.getId(Seq.uploadSeqType)
        );

        // directory/yyyy/MM/dd/filename_uuid.extension
        String baseUrl = StringUtils.format("{}/{}/{}.{}",
                directory,
                DateUtils.datePath(),
                newBaseName,
                extension
        );
        res.setFileUrl(PathUtils.appendPaths(Constants.RESOURCE_PREFIX, baseUrl));
        res.setFilePath(PathUtils.appendPaths(diskPath, baseUrl));

        // thumbnailFolderName/directory/yyyy/MM/dd/filename_uuid_thumbnail.extension
        String thumbBaseUrl = StringUtils.format("{}/{}/{}/{}_thumbnail.{}",
                thumbnailFolderName,
                directory,
                DateUtils.datePath(),
                newBaseName,
                "jpg"
        );
        res.setThumbnailFileUrl(PathUtils.appendPaths(Constants.RESOURCE_PREFIX, thumbBaseUrl));
        res.setThumbnailFilePath(PathUtils.appendPaths(diskPath, thumbBaseUrl));

        return res;
    }
}
