package com.jeeplus.modules.test.freemarker.web;

import com.jeeplus.common.config.Global;
import com.jeeplus.common.utils.FileUtils;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.tools.utils.TwoDimensionCode;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "${adminPath}/test/freemarker")
public class FreemarkerDocController extends BaseController {

    @RequestMapping(value = {"index", ""})
    public String index() throws Exception{
        return "modules/test/freemarker/Freemarker";
    }

    @RequestMapping(value="downloadDoc")
    @ResponseBody
    public void downloadDoc(HttpServletRequest request, HttpServletResponse response,String encoderContent)  {

        String name = "justin";
        Template template=null;
        File path = new File(this.getClass().getResource("/").getPath()+"/freemarker");
        Configuration cfg = new Configuration();
        try {
            cfg.setDirectoryForTemplateLoading(path);
            template = cfg.getTemplate("security.ftl");
        } catch (IOException e) {
            e.printStackTrace();
        }
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        Map<String,Object> data  = new HashMap<>();
        data.put("repType","苏兴造字");
        data.put("repYear","2019");
        data.put("repNum","0700");
        data.put("querySite","www.baidu.com");

        String realPath = Global.getAttachmentDir() + " qrcode/";
        FileUtils.createDirectory(realPath);
        String qrCodeName="test.png"; //encoderImgId此处二维码的图片名
        String filePath = realPath + qrCodeName;  //存放路径
        TwoDimensionCode.encoderQRCode(encoderContent, filePath, "png");//执行生成二维码
        String imageStr = getImageStr(filePath);
        data.put("qrcode",imageStr);

        try {
            // 调用工具类的createDoc方法生成Word文档
            file = createDoc(data,template);
            fin = new FileInputStream(file);

            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword; charset=UTF-8");
            // 设置浏览器以下载的方式处理该文件名
            String fileName = "防伪报告模板.doc";
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));

            out = response.getOutputStream();
            byte[] buffer = new byte[1024];  // 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        }catch (Exception e){

        }finally {
            try {
                out.flush();
                if(fin != null) fin.close();
                if(out != null) out.close();
                if(file != null) file.delete(); // 删除临时文件
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private static File createDoc(Map<?, ?> dataMap, Template template) {
        String name =  "d:/test.doc";
        File f = new File(name);
        Template t = template;
        try {
            // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);
            w.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return f;
    }

    private String getImageStr(String path) {
        // 1、校验是否为空
        if (path == null || path.trim().length() <= 0) {
            return "";
        }

        // 2、校验文件是否为目录或者是否存在
        File picFile = new File(path);
        if (picFile.isDirectory() || (!picFile.exists()))
            return "";

        // 3、校验是否为图片
        try {
            BufferedImage image = ImageIO.read(picFile);
            if (image == null) {
                return "";
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            return "";
        }

        // 4、转换成base64编码
        String imageStr = "   ";
        try {
            byte[] data = null;
            InputStream in = new FileInputStream(path);
            data = new byte[in.available()];
            in.read(data);
            BASE64Encoder encoder = new BASE64Encoder();
            imageStr = encoder.encode(data);
        } catch (Exception e) {
            imageStr = "";
            e.printStackTrace();
        }

        return imageStr;
    }
}

