package com.upload.service;

import cn.hutool.core.util.StrUtil;
import com.upload.config.IdWorker;
import com.upload.config.Validate;
import com.upload.config.ValuePool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

@Service
@Slf4j
public class UploadService {
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd");

    /**
     * 校验文件大小，文件格式，生成新文件名
     *
     * @param file the {@link MultipartFile} to upload
     * @return the name string of the file.
     */
    public String handleFile(MultipartFile file) {
        Validate.notTrue(Objects.isNull(file) || file.isEmpty(), ValuePool.UPLOAD_DATA_MISSING);
        // 获取文件名，带后缀
        String originalFilename = file.getOriginalFilename();
        log.info("the original file name：{}", originalFilename);
        // 获取文件的后缀格式
        Validate.notNull(originalFilename, ValuePool.UPLOAD_ORIGINAL_NAME_MISSING);
        int lastDotIndex = originalFilename.lastIndexOf(ValuePool.DOT);
        Validate.notTrue(-1 == lastDotIndex, ValuePool.UPLOAD_FORMAT_MISSING);
        String fileSuffix = originalFilename.substring(lastDotIndex).toLowerCase();
        Validate.notNull(fileSuffix, ValuePool.UPLOAD_FORMAT_ILLEGAL);
        long fileSize = file.getSize();
        log.info("the size of file: {}", fileSize);
        if (StrUtil.equalsAny(fileSuffix, ValuePool.UPLOAD_TYPE_PICS)) {
            Validate.notTrue(fileSize > ValuePool.UPLOAD_MAX_SIZE_PIC, ValuePool.UPLOAD_MAX_SIZE_PIC_DESC);
        } else if (StrUtil.equalsAny(fileSuffix, ValuePool.UPLOAD_TYPE_FILES)) {
            Validate.notTrue(fileSize > ValuePool.UPLOAD_MAX_SIZE_FILE, ValuePool.UPLOAD_MAX_SIZE_FILE_DESC);
        } else if (StrUtil.equalsAny(fileSuffix, ValuePool.UPLOAD_TYPE_VIDEOS)) {
            Validate.notTrue(fileSize > ValuePool.UPLOAD_MAX_SIZE_VIDEO, ValuePool.UPLOAD_MAX_SIZE_VIDEO_DESC);
        } else {
            throw Validate.validateException(ValuePool.UPLOAD_FORMAT_NOT_SUPPORT);
        }
        String fileName = StrUtil.format("{}/{}{}", DATE_TIME_FORMATTER.format(LocalDate.now()), new IdWorker().nextId(), fileSuffix);
        log.info("the new file name：{}", fileName);
        return fileName;
    }
}
