package com.tofly.watermeter.util.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.tofly.common.ftp.config.FtpUtil;
import com.tofly.watermeter.em.Constant;
import com.tofly.watermeter.entity.File;
import com.tofly.watermeter.service.FileService;
import com.tofly.watermeter.util.service.FileUpLoadService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
@AllArgsConstructor
public class FileUploadServiceImpl implements FileUpLoadService {

    private final FileService fileService;

    @Override
    public StringBuilder saveFileList(List<MultipartFile> fileList, String filePathBean, String tableName) {
        StringBuilder fileIds = new StringBuilder("");
        //保存照片
        fileList.forEach(file -> {
            //文件名
            String fileName = file.getOriginalFilename();
            if (!"".equals(fileName)) {
                //文件路径
                assert fileName != null;
                String filePath = filePathBean + IdWorker.getIdStr() + fileName.substring(fileName.lastIndexOf(Constant.POINT));
                FtpUtil.uploadFile2Ftp(file, filePath);
                File localFile = new File();
                localFile.setFilePath(filePath);
                localFile.setFileName(fileName);
                localFile.setOtherName(IdWorker.getIdStr() + fileName.substring(fileName.lastIndexOf(Constant.POINT)));
                //关联表名称
                localFile.setTableName(tableName);
                //获取后缀
                String suffix = fileName.substring(fileName.lastIndexOf(Constant.POINT));
                localFile.setFileFormat(suffix);
                String size = String.format("%.2f", (double) file.getSize() / 1024 / 1024);
                localFile.setFileSize(size + "M");
                fileService.save(localFile);
                //获得文件ID
                fileIds.append(localFile.getId()).append(",");
            }
        });
        if (fileIds.length() > 0) {
            return fileIds.deleteCharAt(fileIds.length() - 1);
        }
        return fileIds;
    }
}
