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.custom.util.service.IFileInfoService;
import com.tofly.xrtygis.em.Constant;
import com.tofly.xrtygis.entity.File;
import com.tofly.xrtygis.entity.IFile;
import com.tofly.xrtygis.mapper.FileMapper;
import com.tofly.xrtygis.mapper.IFileMapper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author JF
 */
@Service
public class IFileInfoServiceImpl extends ServiceImpl<IFileMapper, IFile> implements IFileInfoService {

    /**
     * 文件上传
     */
    @Override
    public StringBuilder saveFileList(List<MultipartFile> fileList, String filePathBean, String tableName) {
        StringBuilder filePaths = 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);
                IFile localFile = new IFile();
                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);
                localFile.setFileSize(file.getSize() + "KB");
                this.save(localFile);
                //获得文件ID
                filePaths.append(localFile.getId()).append(",");
            }
        });
        if (filePaths.length() > 0) {
            return filePaths.deleteCharAt(filePaths.length() - 1);
        }
        return filePaths;
    }

    @Override
    public Boolean removeFileList(List<String> filePathList) {
//        List<IFile> files = this.listByIds(filePathList);
        // 删除远程文件
        filePathList.forEach(FtpUtil::deleteFile);
        return true;
    }
}
