package com.test.bijihoudaun.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.stream.CollectorUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.bijihoudaun.entity.Image;
import com.test.bijihoudaun.mapper.ImageMapper;
import com.test.bijihoudaun.service.ImageService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class ImageServiceImpl
        extends ServiceImpl<ImageMapper, Image>
        implements ImageService {

    @Value("${file.upload-dir}")
    private String uploadDir;
    @Resource
    private ImageMapper imageMapper;

    @Override
    public Image uploadImage( MultipartFile file, Long userId, Long markdownId) throws IOException {
        // 创建上传目录
        Path uploadPath = Paths.get(uploadDir);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String storedName = UUID.randomUUID() + extension;

        // 保存文件
        Path filePath = uploadPath.resolve(storedName);
        Files.copy(file.getInputStream(), filePath);

        // 创建图片实体
        Image image = new Image();
        image.setOriginalName(originalFilename);
        image.setStoredName(storedName);
        image.setUrl("/api/images/preview/" + storedName);
        image.setSize(file.getSize());
        image.setContentType(file.getContentType());
        image.setCreatedAt(new Date());
        image.setMarkdownId(markdownId);

        this.save(image);
        return image;
    }

    @Override
    public boolean deleteImage(Long id) {
        Image image = imageMapper.selectById(id);
        if (image == null) {
            return false;
        }
        try {
            // 删除文件系统中的图片
            Path filePath = Paths.get(uploadDir, image.getStoredName());
            Files.deleteIfExists(filePath);

            // 删除数据库记录
            this.removeById(id);
            return true;
        } catch (IOException e) {
            throw new RuntimeException("删除图片失败", e);
        }
    }

    @Override
    public boolean deleteImageByUrl(String url) {
        Image image = imageMapper.selectOne(new QueryWrapper<Image>().eq("url", url));
        if (image == null) {
            return false;
        }
        try {
            // 删除文件系统中的图片
            Path filePath = Paths.get(uploadDir, image.getStoredName());
            Files.deleteIfExists(filePath);

            // 删除数据库记录
            this.removeById(image.getId());
            return true;
        } catch (IOException e) {
            throw new RuntimeException("删除图片失败", e);
        }
    }
    @Override
    public boolean deleteImageByUrls(List<String> urls) {
        if (CollUtil.isEmpty(urls)) {
            return false;
        }
        for (String url : urls) {
            Image image = imageMapper.selectOne(new QueryWrapper<Image>().eq("url", url));
            if (image != null) {
                this.deleteImageByUrl(url);
            }
        }
        return true;
    }
}
