package com.tofly.dispatch.util;


import com.tofly.dispatch.common.FlowConstant;
import com.tofly.dispatch.service.FileService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class UploadFiles {

    /**
     *
     * @param fileService 文件Service
     * @param fileList 文件集合
     * @param fileIdsdb 数据库存储ID
     * @param fileIds 传入的ID
     * @param filePath 文件路径
     * @param tableName 表名称
     * @return
     */
    public static String saveFiles(FileService fileService, List<MultipartFile> fileList, String fileIdsdb, String fileIds, String filePath, String tableName){
        if(fileIds!=null && fileIds.equals("[]")){
            fileIds="";
        }
        StringBuilder fileIdList = null;
        if (CollectionUtils.isNotEmpty(fileList)) {
            fileIdList = fileService.saveFileList(fileList, filePath, tableName);
            if(fileIdList==null||fileIdList.length()==0){
                return fileIds;
            }
        }

        String fs = fileIds;
        if (StringUtils.isNotEmpty(fileIdsdb) && !fileIdsdb.equals(fileIds)) {
            List<Long> removeFileId = new ArrayList<>();
            if (StringUtils.isEmpty(fileIds)) {
                removeFileId = Arrays.stream(fileIdsdb.split(FlowConstant.CSV)).map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toList());
            } else {
                removeFileId = Arrays.stream(fileIdsdb.split(FlowConstant.CSV)).filter(st -> !fs.contains(st)).map(st -> Long.parseLong(st.trim())).collect(Collectors.toList());
            }
            // 删除对应文件数据
            if (!removeFileId.isEmpty()) {
                // 删除远程文件
                fileService.removeFileList(removeFileId);
            }
        }
        StringBuilder files = new StringBuilder();
        if (StringUtils.isEmpty(fileIds) || StringUtils.isEmpty(fileIdList)) {
            if(StringUtils.isNotEmpty(fileIds)){
                files.append(fileIds);
            }else if(StringUtils.isNotEmpty(fileIdList)){
                files.append(fileIdList);
            }
        } else {
            files.append(fileIds).append(FlowConstant.CSV).append(fileIdList);
        }
        return files.toString();
    }

}
