package com.eversec.service;

import com.eversec.common.Kv;
import org.redkale.net.http.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


/**
 * Created by liangxianyou at 2019/2/21 11:06.
 */
@WebServlet(value = {"upload", "/upload/*"}, comment = "文件管理入口")
public class UploadServlet extends BaseServlet {

    @HttpMapping(url = "/upload/excel", auth = false, comment = "Execel上传")
    public void uploadExcel(HttpRequest request, HttpResponse response) {
        try {
            for (MultiPart part : request.multiParts()) {
                File destFile = new File(apphome, "upload/" + part.getFilename());
                destFile.getParentFile().mkdir();
                part.save(destFile);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        response.finish("");
    }

    @HttpMapping(url = "/upload/files", auth = false, comment = "已经上传文件的列表")
    public void uploadFiles(HttpRequest request, HttpResponse response) {
        List<Kv> list = new ArrayList();

        File dir = new File(apphome, "upload");
        if (dir.exists() && dir.isDirectory()) {
            for (File file : dir.listFiles()) {
                list.add(
                        Kv.of("name", file.getName())
                                .set("size", file.length())
                                .set("modified", file.lastModified())
                );
            }
            list = list.stream().sorted(Comparator.comparing(x -> Long.parseLong(x.get("modified") + ""))).collect(Collectors.toList());
        }
        response.finish(list);
    }

    @HttpMapping(url = "/upload/del", auth = false, comment = "删除文件")
    public void uploadDel(HttpRequest request, HttpResponse response) {
        String fileName = request.getParameter("fileName");
        File file = new File(apphome, "upload/" + fileName);
        if (file.exists()) {
            File target = new File(apphome, "upload_back/" + fileName);
            try {
                target.getParentFile().mkdirs();
                Files.move(file.toPath(), target.toPath(), new StandardCopyOption[]{StandardCopyOption.REPLACE_EXISTING});
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        response.finish("");
    }


}
