/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.base.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.base.entity.Ftpfiles;
import com.tofly.base.mapper.FtpfilesMapper;
import com.tofly.base.service.FtpfilesService;
import com.tofly.common.ftp.config.FtpUtil;
import com.tofly.common.core.util.io.ZipUtil;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 公共基础附件信息表
 *
 * @author wangjian
 * @date Mon Feb 17 00:00:00 CST 2020
 */
@Service("ftpfilesService")
public class FtpfilesServiceImpl extends ServiceImpl<FtpfilesMapper, Ftpfiles> implements FtpfilesService {

    @Override
    public String customSaveBatch(List<Ftpfiles> listFtpFiles) {
        StringBuilder sb=new StringBuilder();
            listFtpFiles.forEach(ftpfiles -> {
                this.save(ftpfiles);
                sb.append(ftpfiles.getId()).append(";");
        });
        return sb.substring(0,sb.lastIndexOf(";"));
    }

    @Override
    @SneakyThrows
    public byte[] getDataFiles(Collection<Ftpfiles> listFtpFiles) {
        final int  BUFFER_SIZE = 2 * 1024;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for(Ftpfiles ftpfiles:listFtpFiles){
            zip.putNextEntry(new ZipEntry(ftpfiles.getOriginalName()+ftpfiles.getFileType()));
            // copy文件到zip输出流中
            byte[] buf = new byte[BUFFER_SIZE];
            try(InputStream in =FtpUtil.getInputStremforFile(ftpfiles.getFilePath())) {
                int len;
                while ((len = in.read(buf)) != -1) {
                    zip.write(buf, 0, len);
                }
                // Complete the entry
                zip.closeEntry();
            }catch (IOException e){
                throw new IOException("zip error from ZipUtils",e);
            }
        }
        ZipUtil.close(zip);
        return outputStream.toByteArray();
    }
}
