package com.tofly.xrtygis.custom.util.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.common.ftp.config.FtpUtil;
import com.tofly.xrtygis.custom.util.service.FileInfoService;
import com.tofly.xrtygis.em.Constant;
import com.tofly.xrtygis.entity.File;
import com.tofly.xrtygis.mapper.FileMapper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author 20126
 */
@Service
public class FileInfoServiceImpl extends ServiceImpl<FileMapper, File> implements FileInfoService {

    /**
     * 文件上传
     */
    @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");
                this.save(localFile);
                //获得文件ID
                fileIds.append(localFile.getId()).append(",");
            }
        });
        if (fileIds.length() > 0) {
            return fileIds.deleteCharAt(fileIds.length() - 1);
        }
        return fileIds;
    }
}
