package cn.com.qmth.stmms.ms.admin.exporter;

import cn.com.qmth.stmms.ms.admin.utils.PdfUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/exportPdf")
public class pdfExporter {

    @PostMapping
    public void pdf(@RequestBody Map map, HttpServletResponse response) {
        List<String> bases = JSONObject.parseArray(JSONObject.toJSONString(map.get("content")), String.class);
        try {
            ArrayList<String> imageUrllist = new ArrayList();
            File file = new File("d://"+String.valueOf(System.currentTimeMillis()));
            if (!file.exists()) {
                file.mkdirs();
            }
            for (String base : bases) {
                String imgFilePath = file.getPath() + File.separator + System.currentTimeMillis() + ".png";
                boolean convertFlag = PdfUtils.base64ToImage(base, imgFilePath);
                if (convertFlag) {
                    imageUrllist.add(imgFilePath);
                }
            }
            if(imageUrllist.size() == 0){
                throw new RuntimeException("导出失败");
            }
            String pdfFilePath = file.getPath() + File.separator + System.currentTimeMillis() + ".pdf";
            PdfUtils.imageToPdf(imageUrllist, pdfFilePath);
            outputFile(response, new File(pdfFilePath), "导出pdf"+System.currentTimeMillis() + ".pdf", file.getPath());
        } catch (Exception e) {
            throw new RuntimeException("导出失败");
        }
    }

    public static void outputFile(HttpServletResponse response, File file, String fileName, String rootPath) {
        try {
            if (!file.exists()) {
                response.sendError(404, "File not found!");
            }
            BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
            byte[] buf = new byte[1024];
            int len = 0;

            String fName = new String(fileName.getBytes(), "ISO-8859-1");
            response.reset();
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + fName);
            OutputStream outStream = response.getOutputStream();
            while ((len = br.read(buf)) > 0) {
                outStream.write(buf, 0, len);
            }

            br.close();
            outStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //下载完毕删除文件
        delete(rootPath);
    }

    public static void delete(String path){
        File file = new File(path);
        if(!file.exists()){
            return;
        }
        if(file.isFile()){
            file.delete();
        }
        File[] files = file.listFiles();
        for (File f : files) {
            if(f.isFile()){
                f.delete();
            }else{
                delete(f.getAbsolutePath());
            }
        }
    }

    public static void main(String[] args) throws Exception {
        //base64转图片
//        String imgSrc = PdfUtils.getImageStr("C:\\Users\\xf520\\Desktop\\1.png");
//        System.out.println(imgSrc);
//        String imgFilePath = "d:\\32.jpg";
//        PdfUtils.base64ToImage(imgSrc, imgFilePath);
//        ArrayList<String> imageUrllist = new ArrayList<String>();
//        imageUrllist.add(imgFilePath);
//        imageUrllist.add(imgFilePath);
//        PdfUtils.imageToPdf(imageUrllist, "d:\\11.pdf");

        delete("D:\\1596164055913");
    }

}
