package com.xjrsoft.module.system.service.impl;

import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.utils.FileZipUtil;
import com.xjrsoft.module.system.entity.File;
import com.xjrsoft.module.system.mapper.FileMapper;
import com.xjrsoft.module.system.service.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 文件关联关系表 服务实现类
 * </p>
 *
 * @author tzx
 * @since 2022-03-08
 */
@Service
public class FileServiceImpl extends MPJBaseServiceImpl<FileMapper, File> implements IFileService {

    @Autowired
    private ResourceLoader resourceLoader;

    @Override
    public boolean deleteFile(String encode) {
        return false;
    }

    @Override
    public byte[] downloadFileByZip(Long folderId) {
        List<File> fileList = this.list(Wrappers.<File>query().lambda().eq(File::getFolderId, folderId));

        //声明一个Map，将所有文件装进去，map的key是完整的文件名
        Map<String, byte[]> byteAryMap = new HashMap<>();

        for (int i = 0; i < fileList.size(); i++) {
//            String localFilePath = "C:\\Users\\大数据与最优化研究所\\Downloads\\" + fileList.get(i).getFileName() + fileList.get(i).getFileType();
//            System.err.println(localFilePath);
            try {
                URL url = new URL(fileList.get(i).getFileUrl());
                URLConnection conn = url.openConnection();
                InputStream in = conn.getInputStream();
//                        FileOutputStream fos = new FileOutputStream(localFilePath)
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                byte[] byteArray = outputStream.toByteArray();
                byteAryMap.put(fileList.get(i).getFileName() + fileList.get(i).getFileType(), byteArray);
//                    System.err.println(byteArray.length);
//                    outputStream.writeTo(fos);

//                System.out.println("File downloaded successfully.");
                in.close();
                outputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        //执行下面这段代码就可以拿到压缩之后的byte数组
        return FileZipUtil.byteAryMap2Zip(byteAryMap);
    }
}
