package com.zksy.basicData.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.basicData.domain.XcrFile;
import com.zksy.basicData.mapper.XcrFileMapper;
import com.zksy.basicData.service.IXcrFileService;
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;

/**
 * 文件管理Service业务层处理
 *
 * @author sy
 * @date 2024-05-20
 */
@Service
public class XcrFileServiceImpl extends ServiceImpl<XcrFileMapper, XcrFile> implements IXcrFileService {
    @Autowired
    private MinioFileStorageService minioFileStorageService;

    @Override
    public List<XcrFile> selectByFids(List<String> fids) {
        QueryWrapper<XcrFile> queryWrapper =new QueryWrapper<>();
        queryWrapper.in("fid",fids);
        List<XcrFile> crmFileList = getBaseMapper().selectList(queryWrapper);
        return crmFileList;
    }

    @Override
    public List<XcrFile> selectByFid(Long fid) {
        QueryWrapper<XcrFile> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("fid",fid);
        List<XcrFile> crmFileList = getBaseMapper().selectList(queryWrapper);
        return crmFileList;
    }

    @Override
    public boolean saveMinio(XcrFile crmFile, MultipartFile multipartFile) {
        try {
            String path = minioFileStorageService.uploadFile(multipartFile,crmFile.getModuleName());
            crmFile.setFileUrl(path);
            return save(crmFile);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

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

    @Override
    public boolean deleteFile(String id) {
        XcrFile xcrFile = getById(id);
        //删除minio文件
        minioFileStorageService.deleteFile(xcrFile.getFileUrl());
        return removeById(id);
    }
}
