package com.sunxung.factoring.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sunxung.factoring.component.exception.BusinessException;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.*;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.entity.ValidatorEntity.ValidatorType;
import com.sunxung.factoring.entity.acceptance.AcceptanceSignConfirmationElectronicInfo;
import com.sunxung.factoring.entity.purchcontractmanagement.PurchContractElectronicInfo;
import com.sunxung.factoring.entity.purchcontractmanagement.PurchContractSupplementElectronicInfo;
import com.sunxung.factoring.entity.settlement.SettlementBasicInfo;
import com.sunxung.factoring.entity.settlement.SettlementGoodsInfo;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.entity.sys.FileStorage.Belong;
import com.sunxung.factoring.entity.sys.FileStorageDO;
import com.sunxung.factoring.mapper.sys.FileStorageMapper;
import com.sunxung.factoring.service.acceptancesheet.IAcceptanceSignConfirmationElectronicInfoService;
import com.sunxung.factoring.service.purchcontractmanagement.IPurchContractSupplementElectronicInfoService;
import com.sunxung.factoring.service.purchcontractmanagement.PurchContractElectronicInfoService;
import com.sunxung.factoring.service.settlement.SettlementBasicInfoService;
import com.sunxung.factoring.service.settlement.SettlementGoodsInfoService;
import com.sunxung.factoring.service.sys.FileService;
import com.sunxung.factoring.service.sys.FileStorageService;
import com.sunxung.factoring.service.sys.ISysAttachmentRefService;
import com.sunxung.factoring.service.sys.dto.AttachmentDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
public class FileStorageServiceImpl implements FileStorageService {

    @Autowired
    private FileStorageMapper fileStorageMapper;

    @Autowired
    private ISysAttachmentRefService sysAttachmentRefService;

    @Autowired
    private SettlementBasicInfoService settlementBasicInfoService;

    @Autowired
    private SettlementGoodsInfoService settlementGoodsInfoService;

    @Autowired
    private IPurchContractSupplementElectronicInfoService supplementElectronicInfoService;

    @Autowired
    private PurchContractElectronicInfoService purchContractElectronicInfoService;

    @Autowired
    private IAcceptanceSignConfirmationElectronicInfoService acceptanceSignConfirmationElectronicInfoService;

    @Autowired
    private FileService fileService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FileStorage add(FileStorage fileStorage) {
        ValidatorUtil.validator(ValidatorType.ADD, fileStorage);
        fileStorageMapper.add(fileStorage);
        return get(fileStorage.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<FileStorage> add(List<FileStorage> fileStorages) {
        List<FileStorage> newFileStorages = new ArrayList<FileStorage>();
        if (fileStorages == null) {
            return newFileStorages;
        }
        for (FileStorage fileStorage : fileStorages) {
            this.add(fileStorage);
        }
        return newFileStorages;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FileStorage update(FileStorage fileStorage) {
        ValidatorUtil.validator(ValidatorType.UPDATE, fileStorage);
        fileStorageMapper.update(fileStorage);
        return get(fileStorage.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBelongById(Long id, Belong belong) {
        return fileStorageMapper.updateBelongById(id, belong) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        fileStorageMapper.delete(id);
        return true;
    }

    @Override
    public FileStorage get(Long id) {
        return fileStorageMapper.get(id);
    }

    @Override
    public List<FileStorage> add(HttpServletRequest request, FileModuleDict.ChildEnum moduleType)
            throws IllegalStateException, IOException {
        List<FileStorage> fileStorages = new ArrayList<FileStorage>();
        if (!(request instanceof MultipartHttpServletRequest)) {
            return fileStorages;
        }
        MultiValueMap<String, MultipartFile> multiValueMap = ((MultipartHttpServletRequest) request).getMultiFileMap();
        if (multiValueMap == null || CollectionUtil.isEmpty(multiValueMap.values())) {
            throw new ValidatorException(CodeUtil.FAIL, "文件不能为空");
        }
        for (Entry<String, List<MultipartFile>> entry : multiValueMap.entrySet()) {
            if (entry == null || CollectionUtil.isEmpty(entry.getValue())) {
                continue;
            }
            for (MultipartFile multipartFile : entry.getValue()) {
                fileStorages.add(addFileStorage(multipartFile, moduleType));
            }
        }
        return fileStorages;
    }

    @Override
    public FileStorage addFileStorage(MultipartFile multipartFile, FileModuleDict.ChildEnum moduleType)
            throws IllegalStateException, IOException {
        FileStorage fileStorage = new FileStorage(multipartFile, moduleType);
        File file = new File(fileStorage.getAbsolutePath());
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        multipartFile.transferTo(file);
        try {
            return this.add(fileStorage);
        } catch (ValidatorException ve) {
            file.delete();
            throw ve;
        } catch (Exception e) {
            file.delete();
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteFile(Long fileId) {

        if (fileId == null) {
            throw new ValidatorException(CodeUtil.FAIL, "文件id不能为空");
        }
        FileStorage fileStorage = fileStorageMapper.get(fileId);
        if (fileStorage != null && fileStorage.getAbsolutePath() != null) {
            File file = new File(fileStorage.getAbsolutePath());
            if (file.exists() && file.isFile()) {
                if (file.delete()) {
                    return delete(fileId);
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
        return false;
    }

    @Override
    public List<FileStorage> findByBelongId(String belongId) {
        return fileStorageMapper.findByBelongId(belongId);
    }

    @Override
    public String getAbsoluteFilePath(HttpServletRequest request, FileModuleDict.ChildEnum moduleType)
            throws IllegalStateException, IOException {
        if (!(request instanceof MultipartHttpServletRequest)) {
            return "";
        }
        MultiValueMap<String, MultipartFile> multiValueMap = ((MultipartHttpServletRequest) request).getMultiFileMap();
        if (multiValueMap == null || CollectionUtil.isEmpty(multiValueMap.values())) {
            throw new ValidatorException(CodeUtil.FAIL, "文件不能为空");
        }
        for (Entry<String, List<MultipartFile>> entry : multiValueMap.entrySet()) {
            if (entry == null || CollectionUtil.isEmpty(entry.getValue())) {
                continue;
            }
            for (MultipartFile multipartFile : entry.getValue()) {
                return getAbsoluteFileStorage(multipartFile, moduleType);
            }
        }
        return "";
    }

    @Override
    public String getFilePath(HttpServletRequest request, FileModuleDict.ChildEnum moduleType)
            throws IllegalStateException, IOException {
        if (!(request instanceof MultipartHttpServletRequest)) {
            return "";
        }
        MultiValueMap<String, MultipartFile> multiValueMap = ((MultipartHttpServletRequest) request).getMultiFileMap();
        if (multiValueMap == null || CollectionUtil.isEmpty(multiValueMap.values())) {
            throw new ValidatorException(CodeUtil.FAIL, "文件不能为空");
        }
        for (Entry<String, List<MultipartFile>> entry : multiValueMap.entrySet()) {
            if (entry == null || CollectionUtil.isEmpty(entry.getValue())) {
                continue;
            }
            for (MultipartFile multipartFile : entry.getValue()) {
                return getFileStorage(multipartFile, moduleType);
            }
        }
        return "";
    }

    private String getFileStorage(MultipartFile multipartFile, FileModuleDict.ChildEnum moduleType)
            throws IllegalStateException, IOException {
        FileStorage fileStorage = new FileStorage(multipartFile, moduleType);
        File file = new File(fileStorage.getAbsolutePath());
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        multipartFile.transferTo(file);
        try {
            return fileStorage.getPath();
        } catch (ValidatorException ve) {
            file.delete();
            throw ve;
        } catch (Exception e) {
            file.delete();
            throw e;
        }
    }

    private String getAbsoluteFileStorage(MultipartFile multipartFile, FileModuleDict.ChildEnum moduleType)
            throws IllegalStateException, IOException {
        FileStorage fileStorage = new FileStorage(multipartFile, moduleType);
        File file = new File(fileStorage.getAbsolutePath());
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        multipartFile.transferTo(file);
        try {
            return fileStorage.getAbsolutePath();
        } catch (ValidatorException ve) {
            file.delete();
            throw ve;
        } catch (Exception e) {
            file.delete();
            throw e;
        }
    }

    @Override
    public ResponseEntity<Object> downloadFile(Long id) {
        FileStorage fileStorage = fileStorageMapper.get(id);
        if (fileStorage != null) {
            String fileName = fileStorage.getOriginalName();
            String fileNameEncodeStr = "null";
            try {
                fileNameEncodeStr = java.net.URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                fileNameEncodeStr = "";
            }
            String path = fileStorage.getAbsolutePath();
            File file = new File(path);

            try {
                InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

                HttpHeaders headers = new HttpHeaders();
//                headers.add("Content-Disposition", "attachment; filename=" + fileNameEncodeStr);
//                headers.add("Cache-Control", "no-cache,no-store,must-revalidate");
                headers.add("Content-Disposition", "attachment;filename=" + fileNameEncodeStr);
                headers.add("Access-Control-Expose-Headers", "Content-Disposition");
                headers.add("Pragma", "no-cache");
                headers.add("Expires", "0");

                ResponseEntity<Object> responseEntity = ResponseEntity.ok()
                        .headers(headers)
                        .contentLength(file.length())
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .body(resource);
                return responseEntity;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 通过Url下载 采购合同文件、出征文件 并存储
     *
     * @param contractId
     * @param moduleType
     * @param downUrl
     * @return
     */
    @Override
    public FileStorage addFileStorageWithBelongAndName(String contractId, FileModuleDict.ChildEnum moduleType, String downUrl, Long supplemementId) {
        //文件重命名
        String fileName = "";
        if (FileModuleDict.ChildEnum.PURCHASE_CONTRACT_FILE == moduleType || FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SIGN_FILE_REPORT == moduleType || FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SIGN_FILE == moduleType) {
            PurchContractElectronicInfo purchContractElectronicInfo = purchContractElectronicInfoService.lambdaQuery().eq(PurchContractElectronicInfo::getContractId, contractId).one();
            fileName = purchContractElectronicInfo.getContractName();
        } else if (FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SIGN_FILE_REPORT == moduleType) {
            SettlementBasicInfo settlementBasicInfo = settlementBasicInfoService.getById(Long.valueOf(contractId));
            fileName = settlementBasicInfo.getSettlementNumber();
        } else if (FileModuleDict.ChildEnum.SETTLEMENT_UPSTREAM_SIGNED_FILE == moduleType) {
            SettlementBasicInfo settlementBasicInfo = settlementBasicInfoService.getById(Long.valueOf(contractId));
            List<SettlementGoodsInfo> settlementGoodsInfos = settlementGoodsInfoService.list(new QueryWrapper<SettlementGoodsInfo>()
                    .eq("settlement_basic_info_id", settlementBasicInfo.getId()));
            BigDecimal allPurchaseTotalPrice = BigDecimal.ZERO;
            if (CollectionUtil.isNotEmpty(settlementGoodsInfos)) {
                allPurchaseTotalPrice = settlementGoodsInfos.stream().map(SettlementGoodsInfo::getPurchaseTotalPrice)
                        .reduce(BigDecimal::add).orElse(new BigDecimal(0.00));
            }
            fileName = settlementBasicInfo.getSettlementNumber() + "-" + allPurchaseTotalPrice + "-上游结算已签署";
        } else if (FileModuleDict.ChildEnum.ACCEPTANCE_UPSTREAM_FILE_SIGN == moduleType) {
            //文件重命名
            fileName = contractId;
        } else if (FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SUPPLEMENT_SIGN_FILE == moduleType || FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SUPPLEMENT_FILE_REPORT == moduleType
                || FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SUPPLEMENT_FILE == moduleType) {
            PurchContractSupplementElectronicInfo purchContractSupplementElectronicInfo = supplementElectronicInfoService.lambdaQuery().eq(PurchContractSupplementElectronicInfo::getContractId, contractId).one();
            fileName = purchContractSupplementElectronicInfo.getContractName();

        } else if (FileModuleDict.ChildEnum.ACCEPTANCE_SIGN_CONFIRM_BACK_FILE == moduleType) {
            AcceptanceSignConfirmationElectronicInfo acceptanceSignConfirmationElectronicInfo = acceptanceSignConfirmationElectronicInfoService.lambdaQuery().eq(AcceptanceSignConfirmationElectronicInfo::getContractId, contractId).one();
           // FileStorage fileStorage = get(acceptanceSignConfirmationElectronicInfo.getFileId());
            //原始文件是存在 c端的
            FileStorageDO fileStorage = fileService.getById(
                acceptanceSignConfirmationElectronicInfo.getFileId());
            fileName = fileStorage.getOriginalName().replace(fileStorage.getType(), "");
        } else if (FileModuleDict.ChildEnum.ACCEPTANCE_SIGN_CONFIRM_REPORT_FILE == moduleType) {
            AcceptanceSignConfirmationElectronicInfo acceptanceSignConfirmationElectronicInfo = acceptanceSignConfirmationElectronicInfoService.lambdaQuery().eq(AcceptanceSignConfirmationElectronicInfo::getContractId, contractId).one();
            //FileStorage fileStorage = get(acceptanceSignConfirmationElectronicInfo.getFileId());
            FileStorageDO fileStorage = fileService.getById(
                acceptanceSignConfirmationElectronicInfo.getFileId());
            fileName = fileStorage.getOriginalName().replace(fileStorage.getType(), "");
        } else {
            fileName = contractId;
        }
        String name = moduleType.getCname();
        String suffix = ".pdf";
        if (FileModuleDict.ChildEnum.SETTLEMENT_UPSTREAM_SIGNED_FILE != moduleType && FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SUPPLEMENT_SIGN_FILE != moduleType
                && FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SUPPLEMENT_FILE != moduleType && FileModuleDict.ChildEnum.PURCHASE_CONTRACT_FILE != moduleType && FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SIGN_FILE != moduleType) {
            fileName = fileName + name;
        }

        FileStorage fileStorage = new FileStorage(contractId, moduleType, fileName, suffix);

        String absolutePath = fileStorage.getAbsolutePath();
        File file = new File(absolutePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            FileUtil.downloadFile(downUrl, absolutePath);
            return this.add(fileStorage);
        } catch (Exception ve) {
            file.delete();
            throw new BusinessException(CodeUtil.FAIL, ve.getMessage());
        }
    }

    @Override
    public List<FileStorage> findByBelongIdAndBelongType(String belongId, String belongType) {
        return fileStorageMapper.findByBelongIdAndBelongType(belongId, belongType);
    }

    @Override
    public void saveAttachmentRefByFileStorage(FileStorage fileStorage, FileModuleDict.ChildEnum moduleType, Long entityId) {
        List list = new ArrayList();
        list.add(fileStorage);
        AttachmentDto attachmentDto = AttachmentDto.builder()
                .setEntityId(entityId)
                .setChildEnum(moduleType)
                .build();
        sysAttachmentRefService.saveFileAndRefHis(list, attachmentDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<FileStorage> doUploadFiles(HttpServletRequest request, String moudleName) throws IOException {
        if (!(request instanceof MultipartHttpServletRequest)) {
            return null;
        }
        MultiValueMap<String, MultipartFile> multiValueMap = ((MultipartHttpServletRequest) request).getMultiFileMap();
        if (multiValueMap == null || CollectionUtil.isEmpty(multiValueMap.values())) {
            throw new ValidatorException(CodeUtil.FAIL, "文件不能为空");
        }
        List<FileStorage> list = new ArrayList<>();
        List<MultipartFile> files = multiValueMap.get("file");
        for (MultipartFile multipartFile : files) {
            FileStorage fileStorage;
            File file;
            fileStorage = new FileStorage(multipartFile, moudleName);
            file = new File(fileStorage.getAbsolutePath());
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            multipartFile.transferTo(file);
            add(fileStorage);
            list.add(fileStorage);
        }
        return list;
    }

    @Override
    public void deleteInvalidFileStorage() {
        List<Long> fileStorageIds = fileStorageMapper.selectInvalidFileStorage();
        if (CollectionUtil.isNotEmpty(fileStorageIds)) {
            fileStorageIds.stream().forEach(
                    f -> deleteFile(f)
            );
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteFileStorage(Long id) {
        if (id == null || id == 0L) {
            throw new ValidatorException(CodeUtil.FAIL, "文件id错误");
        }
        FileStorage fileStorage = fileStorageMapper.get(id);
        if (fileStorage != null) {
            File file = new File(fileStorage.getAbsolutePath());
            if (file.exists()) {
                fileStorageMapper.delete(id);
                return true;
            }
        }
        return false;
    }

    @Override
    public void downloadZipFile(List<FileStorage> fileStorageList, String name, FileModuleDict.ChildEnum moduleType, HttpServletResponse response) {
        File zipFile = downloadZip(fileStorageList, name, moduleType);
        doDownloadZip(response, zipFile);
    }

    @Override
    public void renameFileStorageList(List<FileStorage> fileStorageList) {
        //根据文件原名进行去重
        Map<String, Integer> nameCounts = new HashMap<>();
        for (FileStorage file : fileStorageList) {
            nameCounts.put(file.getOriginalName(), nameCounts.getOrDefault(file.getOriginalName(), 0) + 1);
        }
        Set<String> duplicates = new HashSet<>();
        for (Map.Entry<String, Integer> entry : nameCounts.entrySet()) {
            if (entry.getValue() > 1) {
                duplicates.add(entry.getKey());
            }
        }
        Map<String, Integer> renameCounts = new HashMap<>();
        for (int i = 0; i < fileStorageList.size(); i++) {
            FileStorage fileStorage = fileStorageList.get(i);
            if (duplicates.contains(fileStorage.getOriginalName())) {
                int count = renameCounts.getOrDefault(fileStorage.getOriginalName(), 0) + 1;
                int index = fileStorage.getOriginalName().lastIndexOf(".");
                String newName = fileStorage.getOriginalName().substring(0, index) + DateUtil.dateToString(new Date(), "yyyyMMdd") + "-" + count + fileStorage.getFileType();
                renameCounts.put(fileStorage.getOriginalName(), count);
                fileStorage.setOriginalName(newName);
                fileStorageList.set(i, fileStorage);
            }
        }
    }

    /**
     * 打包zip文件
     *
     * @param fileStorageList 文件
     * @param moduleType      文件所属模块枚举实例
     * @param name            文件名称
     */
    public File downloadZip(List<FileStorage> fileStorageList, String name, FileModuleDict.ChildEnum moduleType) {

        try {
            name = new String(name.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e1) {
            throw new BusinessException(CodeUtil.FAIL, "下载附件转码失败：" + e1.getMessage());
        }
        String desPath = FileUtil.getAbsolutePath(name, ".zip", moduleType);
        File zipFile = new File(desPath);
        if (!zipFile.getParentFile().exists()) {
            zipFile.getParentFile().mkdirs();
        }
        ZipOutputStream zipStream = null;
        FileInputStream zipSource = null;
        BufferedInputStream bufferStream = null;
        try {
            // 构造最终压缩包的输出流
            zipStream = new ZipOutputStream(new FileOutputStream(zipFile));
            for (FileStorage fileStorage : fileStorageList) {
                String path = fileStorage.getAbsolutePath();
                File file = new File(path);
                // 将需要压缩的文件格式化为输入流
                zipSource = new FileInputStream(file);
                // 压缩条目不是具体独立的文件，而是压缩包文件列表中的列表项，称为条目，就像索引一样
                ZipEntry zipEntry = new ZipEntry(fileStorage.getOriginalName());
                // 定位该压缩条目位置，开始写入文件到压缩包中
                zipStream.putNextEntry(zipEntry);
                // 输入缓冲流
                bufferStream = new BufferedInputStream(zipSource, 1024 * 10);
                int read = 0;
                // 创建读写缓冲区
                byte[] buf = new byte[1024 * 10];
                while ((read = bufferStream.read(buf, 0, 1024 * 10)) != -1) {
                    zipStream.write(buf, 0, read);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            try {
                if (null != bufferStream) {
                    bufferStream.close();
                }
                if (null != zipStream) {
                    zipStream.close();
                }
                if (null != zipSource) {
                    zipSource.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return zipFile;
    }

    /**
     * 下载文件夹
     *
     * @param res
     * @param file
     */
    public void doDownloadZip(HttpServletResponse res, File file) {
        try {
            if (file.exists()) {
                String fileName = file.getName();
                fileName = new String(fileName.getBytes("UTF-8"));
                String basePath = file.getAbsolutePath();
                InputStream in = new FileInputStream(new File(basePath));
                fileName = URLEncoder.encode(fileName, "UTF-8");
//                res.setHeader("content-disposition", "attachment;filename=" + fileName);
//                res.setHeader("Content-Type", "application/vnd.ms-exce");
                res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
                res.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
                OutputStream out = res.getOutputStream();
                byte[] b = new byte[1024];
                int len = -1;
                while ((len = in.read(b)) != -1) {
                    out.write(b, 0, len);
                    out.flush();
                }
                // 关闭
                in.close();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void do_UploadFile(HttpServletResponse res, Long id) {
        // TODO Auto-generated method stub
        try {
            FileStorage fileStorage = fileStorageMapper.get(id);
            if (null != fileStorage) {
                String fileName = fileStorage.getOriginalName();
                fileName = new String(fileName.getBytes("UTF-8"));
                String basePath = fileStorage.getAbsolutePath();
                InputStream in = new FileInputStream(new File(basePath));
                fileName = URLEncoder.encode(fileName, "UTF-8");
                res.setHeader("content-disposition", "attachment;fileName=" + fileName);
                OutputStream out = res.getOutputStream();
                byte[] b = new byte[1024];
                int len = -1;
                while ((len = in.read(b)) != -1) {
                    out.write(b, 0, len);
                }
                // 关闭
                out.close();
                in.close();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public List<FileStorage> saveFileStorage(List<Long> fileIds) {

        List<FileStorage> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(fileIds)) {
            for (Long fileId : fileIds) {
                FileStorageDO fileStorageDO = fileService.getById(fileId);
                FileStorage fileStorage = new FileStorage();
                fileStorage.setFileType(fileStorageDO.getStorageType());
                fileStorage.setOriginalName(fileStorageDO.getOriginalName());
                fileStorage.setAbsolutePath(fileStorageDO.getAbsolutePath());
                fileStorage.setPath(fileStorageDO.getPath());
                fileStorage.setSize(fileStorageDO.getSize());
                add(fileStorage);
                list.add(fileStorage);
            }
        }
        return list;
    }

    @Override
    public void updateBusinessId(Long fileId, Long businessId) {
        if (fileId != null) {
            fileStorageMapper.updateBusinessId(fileId,businessId);
        }
    }


}
