package com.fkzy.warn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fkzy.warn.service.FileService;
import com.fkzy.warn.common.conf.MinioConfig;
import com.fkzy.warn.common.response.ApiResponse;
import com.fkzy.warn.mapper.FileMapper;
import com.fkzy.warn.model.File;
import com.fkzy.warn.model.vo.FileVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yuyantian
 * @Date 2021/09/09 14:00
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements FileService {

    private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);


    @Autowired
    private MinioConfig minioConfig;

    @Value(value = "${file.preViewRealPath}")
    private String url;

    @Override
    public ApiResponse uploadFile(MultipartFile multipartFile) {
        ApiResponse apiResponse = new ApiResponse();
        String fileName = "";
        try {
//            fileName = minioConfig.putObject(multipartFile, "\\" + TimeUtil.formatTimeyyyyMMdd() + java.io.File.separator);
            fileName = minioConfig.putObject(multipartFile);
            if (StringUtils.isNotBlank(fileName)) {
                File sysAttrFile = new File();
                sysAttrFile.setFileName(multipartFile.getOriginalFilename());
                sysAttrFile.setFilePath(fileName);//非全路径（排除跟目录）
                sysAttrFile.setFileSize((int) (multipartFile.getSize()));
                sysAttrFile.setCreateTime(new Date());
                sysAttrFile.setIsDel(0);
                sysAttrFile.setUrl(url + fileName);
                /**附件表新增数据*/
                save(sysAttrFile);
                Map<String, Object> result = new HashMap<>();
                result.put("file", sysAttrFile);
                apiResponse.setData(result);
            }
        } catch (Exception e) {
            apiResponse.recordError("附件上传失败,errMsg{" + e.getMessage() + "}");
        }
        return apiResponse;
    }

    @Override
    public File uploadFile2File(MultipartFile file) {
        File sysAttrFile = null;
        String fileName = "";
        try {
        fileName = minioConfig.putObject(file);
            if (StringUtils.isNotBlank(fileName)) {
                sysAttrFile=new File();
                sysAttrFile.setFileName(file.getOriginalFilename());
                sysAttrFile.setFilePath(fileName);//非全路径（排除跟目录）
                sysAttrFile.setFileSize((int) (file.getSize()));
                sysAttrFile.setCreateTime(new Date());
                sysAttrFile.setIsDel(0);
                sysAttrFile.setUrl(url + fileName);
                /**附件表新增数据*/
                save(sysAttrFile);
            }
        } catch (Exception e) {
            log.error("附件上传失败,errMsg{" + e.getMessage() + "}");

        }
        return sysAttrFile;
    }


    public List<File> queryByIds(String ids) {
        List<File> fileList = new ArrayList<>();
        if (!StringUtils.isEmpty(ids)) {
            String[] idsArray = ids.split(",");
            List<Long> idsList = Arrays.stream(idsArray)
                .map(Long::valueOf)
                .collect(Collectors.toList());
            // 创建 QueryWrapper 实例
            QueryWrapper<File> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_del", "0");
            queryWrapper.in("id", idsList);
            List<File> list = this.list(queryWrapper);
            for (File file : list) {
                file.setUrl(url + file.getFilePath());
            }
            fileList.addAll(list);
        }
        return fileList;
    }

    @Override
    public List<FileVO> selectByFileIds(List<Object> fileIds) {
        List<FileVO> files = this.baseMapper.selectByFileIds(fileIds);
        if (CollectionUtils.isEmpty(files)) {
            files = new ArrayList<>();
        } else {
            for (FileVO file : files) {
                file.setUrl(url + file.getUrl());
            }
        }
        return files;
    }
}