package edu.whut.smilepicturebackend.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import edu.whut.smilepicturebackend.config.CosClientConfig;
import edu.whut.smilepicturebackend.exception.BusinessException;
import edu.whut.smilepicturebackend.exception.ErrorCode;
import edu.whut.smilepicturebackend.exception.ThrowUtils;
import edu.whut.smilepicturebackend.model.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 文件服务
 * @deprecated 已废弃，改为使用 upload 包的模板方法优化
 */
@Slf4j
@Service
@Deprecated
public class FileManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 上传图片
     *
     * @param multipartFile    文件
     * @param uploadPathPrefix 上传路径前缀
     * @return
     */
    public UploadPictureResult uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        // 1. 校验图片
        validPicture(multipartFile);

        // 2. 生成存储路径：日期_随机串.后缀，避免目录穿越，防止用户上传的文件名中存在恶意字符造成上传失败或对本地文件产生影响。
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = FileUtil.getSuffix(originalFilename);
        String uuid   = RandomUtil.randomString(16);
        String date   = DateUtil.formatDate(new Date()); // 默认 yyyy-MM-dd
        String uploadFilename = String.format("%s_%s.%s", date, uuid, suffix);
        //如果多个项目共享存储桶，请在桶的根目录下以各项目名作为目录。
        String projectName="smile-picture";
        String uploadPath = String.format("/%s/%s/%s", projectName,uploadPathPrefix, uploadFilename);

        try (InputStream in = multipartFile.getInputStream()) {
            // 3. 调用流式上传并触发 CI 获取原图信息
            PutObjectResult putResult = cosManager.putPictureObjectStream(
                    uploadPath,
                    in,
                    multipartFile.getSize(),
                    multipartFile.getContentType()
            );

            // 4. 解析图片信息
            ImageInfo imageInfo = putResult
                    .getCiUploadResult()
                    .getOriginalInfo()
                    .getImageInfo();

            int picWidth  = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round((double)picWidth / picHeight, 2).doubleValue();

            // 5. 封装返回对象
            UploadPictureResult result = new UploadPictureResult();
            result.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            result.setName(FileUtil.mainName(originalFilename));
            result.setPicSize(multipartFile.getSize());
            result.setPicWidth(picWidth);
            result.setPicHeight(picHeight);
            result.setPicScale(picScale);
            result.setPicFormat(imageInfo.getFormat());

            return result;

        } catch (IOException e) {
            log.error("读取 MultipartFile 流失败，uploadPath = {}", uploadPath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } catch (Exception e) {
            log.error("图片流式上传到对象存储失败，uploadPath = {}", uploadPath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        }
    }

    /**
     * 校验文件
     *
     * @param multipartFile
     */
    private void validPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空");
        // 1. 校验文件大小
        long fileSize = multipartFile.getSize();
        final long ONE_M = 1024 * 1024;
        ThrowUtils.throwIf(fileSize > 2 * ONE_M, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2MB");
        // 2. 校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 允许上传的文件后缀列表（或者集合）
        final List<String> ALLOW_FORMAT_LIST = Arrays.asList("jpeg", "png", "jpg", "webp");
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "文件类型错误");
    }

    /**
     * 清理临时文件
     *
     * @param file
     */
    public void deleteTempFile(File file) {
        if (file == null) {
            return;
        }
        // 删除临时文件
        boolean deleteResult = file.delete();
        if (!deleteResult) {
            log.error("file delete error, filepath = {}", file.getAbsolutePath());
        }
    }
}













