package com.zksy.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.common.domain.FileManager;
import com.zksy.common.mapper.FileManagerMapper;
import com.zksy.common.service.FileManagerService;
import com.zksy.service.MinioFileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author sy
 * @date 2025-06-25
 */
@Service
public class FileManagerServiceImpl extends ServiceImpl<FileManagerMapper, FileManager> implements FileManagerService {

    @Autowired
    private MinioFileStorageService minioFileStorageService;

    @Override
    public boolean saveMinio(FileManager crmFile, MultipartFile multipartFile) {
        try {
            String path = minioFileStorageService.uploadFile(multipartFile, crmFile.getModuleName());
            crmFile.setFileName(path.substring(path.lastIndexOf("/") + 1));
            crmFile.setFileUrl(path);
            return save(crmFile);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean updateMinio(FileManager crmFile, MultipartFile multipartFile) {
        try {
            // 删除minio文件
            minioFileStorageService.deleteFile(crmFile.getFileUrl());
            // 新增minio文件
            String path = minioFileStorageService.uploadFile(multipartFile, crmFile.getModuleName());
            crmFile.setFileName(path.substring(path.lastIndexOf("/") + 1));
            crmFile.setFileUrl(path);
            return updateById(crmFile);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean deleteFile(String id) {
        FileManager fileManager = getById(id);
        if (null == fileManager) {
            throw new RuntimeException("文件id = " + id + " 的文件不存在");
        }
        // 删除minio文件
        minioFileStorageService.deleteFile(fileManager.getFileUrl());
        return removeById(id);
    }

    @Override
    public List<FileManager> getFileByFid(String fid) {
        LambdaQueryWrapper<FileManager> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(fid != null,FileManager::getFid, fid);
        return list(queryWrapper);
    }

}
